在我的简化场景中,有一个parent
组件,其中包含所有业务逻辑.
parent
创建child
组件,该组件仅负责显示按钮列表.
我想处理parent
中此类按钮的点击事件,但是,使用建议的EventEmitter
模式,我不得不在parent
中使用无用的switch case
,以检测按下了哪个按钮.
直接将回调作为child
的输入传递要容易得多,但我认为这不是一个好做法.而且,据我所知,这些回调是在子对象的上下文中执行的,这不是期望的结果.
我错过什么了吗?有没有更好的方法来满足我的需求?或者我完全以错误的方式处理这个问题?
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 100.