如何使用Angular 2在父元素上绑定事件

时间:2016-07-19 11:15:41

标签: angular

我之前在子组件模板中添加了一个按钮元素,但由于代码分离,我不得不将该按钮放在子模板之外(在父模板中)。

我不确定如何在该按钮上绑定click事件,最终会触发子组件上的函数。

请建议。

父:

@Component({
 selector: 'app',
 template: `
   <button>Click me to call child's showMe()</button>
   <child></child>
 `
})

儿童:

@Component({
 selector: 'child',
 template: `Hi...`
})

class Child {
    public showMe() {
      console.log("ShowMe called...");
    }
   }

我不想将事件绑定代码放在父模板中但想要将按钮引用传递给子组件&amp;绑定子组件本身内部的事件。

1 个答案:

答案 0 :(得分:1)

您可以使用模板变量来引用兄弟姐妹

<button (click)="child.doSomething($event)">click me</button>
<child #child></child>
相关问题