【问题标题】:Angular handle event from the ng-template child in parent component来自父组件中 ng-template 子项的 Angular 处理事件
【发布时间】:2018-07-27 06:59:31
【问题描述】:

在我的 Angular 应用程序中,我有一个自定义列表组件,它接收项目列表。使用它的组件,使用带有订单按钮的 custom-list-item 组件。

我需要处理自定义列表组件中的订单更改事件,最好的方法是什么

完整的解决方案托管在这里...

https://stackblitz.com/edit/angular-uw1v8g?file=src%2Fapp%2Fcustom-list%2Fcustom-list.component.ts

如果我对这个通用列表设计的处理不正确,请提出建议。

【问题讨论】:

标签: angular typescript


【解决方案1】:

我们应该如何处理这种情况可能有多种方法,但我想到的一种是使用浏览器的自定义事件并使用 Angular 的 HostListener 处理它们

var event = new CustomEvent(
      'myCustomEvent',
      { payload: 'data'}
    );

然后通过发送它

document.dispatchEvent(event);

通过 Angular 的 HostListener 处理它:

@HostListener('document:myCustomEvent', ['$event', '$event.detail.direction'])
  updateNodes(event, param1) {
    console.log(param1); //param 1 has $event.detail.direction value
  }

Full Example here

HostListener official docs

CustomEvent docs

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 2020-09-03
    相关资源
    最近更新 更多