How to create reusable component with custom buttons configuration

1.2k views Asked by At

So currently I have component which have multiple buttons configurable with options:

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>

And idea is that this component is much bigger and reusable where only buttons and action which would be pushed changes, but it always require form.

Is there other better solution to get such component, using ng-content and triggering form in parent component somehow?

1

There are 1 answers

0
scy On BEST ANSWER

Not entirely sure if you want to provide all buttons and their (click) methods, or if this component should simply execute given inputs with very little logic on its own. The latter is interesting, if you want to set up reusably styled components like a popup with the given buttons.

You could feed not only the elements but their functionality as well.

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>

This obviously also works with button arrays (or sets or maps or whatever).