输入与输出事件绑定

Ben*_*ong 5 typescript angular2-components typescript-decorator angular angular5

我正在寻找一个关于为什么使用@Output事件比@Input在Angular 2+中传递函数更好的论据.

使用@Input:

父模板:

<my-component [customEventFunction]=myFunction></my-component>
Run Code Online (Sandbox Code Playgroud)

在parent-component.ts中:

myFunction = () => {
  console.log("Hello world")
}
Run Code Online (Sandbox Code Playgroud)

在my-component.ts中

@Input() customEventFunction: Function;

someFunctionThatTriggersTheEvent() {
  this.customEventFunction();
}
Run Code Online (Sandbox Code Playgroud)

使用@Output:

父模板:

<my-component (onCustomEvent)=myFunction()></my-component>
Run Code Online (Sandbox Code Playgroud)

在parent-component.ts中:

myFunction() {
  console.log("Hello world")
}
Run Code Online (Sandbox Code Playgroud)

在my-component.ts中

@Output() onCustomEvent: EventEmitter<any> = new EventEmitter<any>();

someFunctionThatTriggersTheEvent() {
  this.onCustomEvent.emit();
}
Run Code Online (Sandbox Code Playgroud)

两者都实现了相同的目标,但我认为这种@Output方法比我在其他Angular包中看到的更为典型.有人可能会说,使用输入,如果只能有条件地触发事件,您可以检查函数是否存在.

思考?

Con*_*Fan 3

@Output事件绑定的优点:

  1. 使用 @Output 定义事件可以清楚地表明它期望回调方法使用标准 Angular 机制和语法来处理该事件。
  2. 许多事件处理程序可以订阅 @Ouptut 事件。另一方面,如果定义一个接受回调函数的 @Input 属性,则只能注册一个事件处理程序;分配第二个事件处理程序将断开第一个事件处理程序的连接。为了与标准 DOM 事件处理程序并行,@Input 回调函数绑定类似于设置onmousemove="doSomething()",而 @Output 事件绑定更像是调用btn.addEventListener("mousemove", ...)