In my simplified scenario there is a parent component, which contains all the business logic.
The parent creates a child component which is only responsible to display a list of buttons.
I want to handle the click events for such buttons in the parent, but, using the suggested EventEmitter pattern I'm forced to use a useless switch case in the parent, in order to detect which button is pressed.
It would be much easier to directly pass the callbacks as input of the child, but I think it's not a good practice. Also these callbacks, as far as I can see, are executed in the context of the child, which is not the desired outcome.
Am I missing something? Is there a better way to achieve my needs? Or I'm completely approaching the problem in a wrong way?
The parent:
import { Component } from "@angular/core";
@Component({
selector: "parent",
template: ` <child
[buttons]="buttons"
(click)="onButtonClick($event)"
></child>
<span>{{ description }}</span>`
})
export class ParentComponent {
description = "";
buttons = ["foo", "bar", "baz"];
onButtonClick(button: string) {
switch (button) {
case "foo":
this.description = "Calling foo()";
this.foo();
break;
case "bar":
this.description = "Calling bar()";
this.bar();
break;
case "baz":
this.description = "Calling baz()";
this.baz();
break;
}
}
foo() {}
bar() {}
baz() {}
}
The child:
import { Component, EventEmitter, Input, Output } from "@angular/core";
@Component({
selector: "child",
template: ` <span *ngFor="let button of buttons">
<button (click)="onClick(button)">{{ button }}</button>
</span>`
})
export class ChildComponent {
@Input() buttons: string[];
@Output() click = new EventEmitter<string>();
onClick(button: string) {
this.click.emit(button);
}
}
And a working sandbox.