如何使用自定义按钮配置创建可重用组件

时间:2020-10-07 07:37:42

标签: angular angular-reactive-forms viewchild ng-template ng-content

因此,目前我有一个组件,该组件具有可通过选项配置的多个按钮:

test.component.html

<button
    *ngIf="cleaning"
    (click)="onCleaning()"
>
    {{'btn.cleaning'|translate}}
</button>

<button
    *ngIf="remove"
    (click)="onRemoving()"
>
    {{'btn.remove'|translate}}
</button>

test.component.ts

@Input() cleaning: boolean;
@Input() remove: boolean;
cleaningForm: FormGroup;

parent.component.html

<test [cleaning]="true" [remove]="false"></test>

想法是,此组件更大且可重用,其中只有要按下的按钮和操作会发生变化,但始终需要表单。

是否还有其他更好的解决方案来获取此类组件,以某种方式在父组件中使用ng-content和触发形式?

1 个答案:

答案 0 :(得分:1)

不确定是否要提供所有按钮及其(单击)方法,或者该组件是否应该仅凭很少的逻辑简单地执行给定的输入。如果您想使用给定的按钮来设置可重用样式的组件(如弹出窗口),则后者很有趣。

您不仅可以提供元素,还可以提供其功能。

Parent.ts

export class ParentComponent implements OnInit {
  public cbFunction: (e: MouseEvent) => void //or whatever return value

  public ngOnInit(): void {
    this.cbFunction = ((e: MouseEvent) => { this.doFancyStuff(); }).bind(this);
  }
}

Parent.html

<child [callback]="cbFunction" name="cbFktBtn"></child>

Child.ts

export class ChildComonent {
   @Input() callback: (e: MouseEvent) => void;
   @Input() name: string;
}

Child.html

<button (click)="callback($event)">{{name}}</button>

这显然也适用于按钮数组(或集合或地图等)。

相关问题