-1

所以目前我有一个组件,它有多个按钮可以配置选项:

test.component.html

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

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

测试组件.ts

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

父组件.html

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

想法是这个组件更大并且可以重用,只有按钮和操作会改变,但它总是需要表单。

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

4

1 回答 1

1

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

您不仅可以提供元素,还可以提供它们的功能。

父.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);
  }
}

父.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>

这显然也适用于按钮阵列(或集合或地图或其他)。

于 2020-10-07T08:54:02.923 回答