加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 输入与输出事件绑定

发布时间:2020-12-17 17:47:17 所属栏目:安全 来源:网络整理
导读:我正在寻找一个争论,为什么在事件中使用@Output比在Angular 2中传递@Input函数更好. 使用@Input: 父模板: my-component [customEventFunction]=myFunction/my-component 在parent-component.ts中: myFunction = () = { console.log("Hello world")} 在my-
我正在寻找一个争论,为什么在事件中使用@Output比在Angular 2中传递@Input函数更好.

使用@Input:

父模板:

<my-component [customEventFunction]=myFunction></my-component>

在parent-component.ts中:

myFunction = () => {
  console.log("Hello world")
}

在my-component.ts中

@Input() customEventFunction: Function;

someFunctionThatTriggersTheEvent() {
  this.customEventFunction();
}

使用@Output:

父模板:

<my-component (onCustomEvent)=myFunction()></my-component>

在parent-component.ts中:

myFunction() {
  console.log("Hello world")
}

在my-component.ts中

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

someFunctionThatTriggersTheEvent() {
  this.onCustomEvent.emit();
}

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

思考?

解决方法

@Output事件绑定的优点:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读