组件间事件绑定Angular 2
问题描述:
我在Angular应用程序中有一个主组件和许多子组件。我使用的是渲染子组件。像这样的东西。组件间事件绑定Angular 2
<body class="nav-md">
<mainComponent></mainComponent>
<router-outlet></router-outlet>
</body>
我的主要组件有一个搜索框和一个按钮。当我点击mainComponent中的按钮时,我想调用我的子组件的函数。任何帮助,将不胜感激。
答
在这种情况下,您可以使用ViewChild。
例子:
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from '../child.component';
@Component({
selector: 'mainComponent',
template: '<search (onSearch)="onSearch($event)"></search><child-component></child-component>',
})
export class MainComopnent{
// ViewChild takes a class type or a reference name string.
// Here we are using the type
@ViewChild(ChildComponent) child: ChildComponent;
onSearch(search: string) {
this.child.say(search);
}
}
@Component({
selector: 'child-component'
})
export class ChildComponent {
say(something: string) {
console.log(something);
}
}
请新增主要成分和子组件的HTMl \ TS的代码,这样任何一个可以提供帮助。 –