我之前在子组件模板中添加了一个按钮元素,但由于代码分离,我不得不将该按钮放在子模板之外(在父模板中)。
我不确定如何在该按钮上绑定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;绑定子组件本身内部的事件。
答案 0 :(得分:1)
您可以使用模板变量来引用兄弟姐妹
<button (click)="child.doSomething($event)">click me</button>
<child #child></child>