我在hierarhy中有组件:app.component> intro.component> header.component。我想用在app.component中定义的方法header.component中。我认识到有办法用@viewChild制作它。什么是最简单的方法来使其工作?angular2使用另一个组件的方法
//编辑 我想对header.component.html中的html标记执行(单击)事件。在这个函数中,我想从app.component运行方法。
我在hierarhy中有组件:app.component> intro.component> header.component。我想用在app.component中定义的方法header.component中。我认识到有办法用@viewChild制作它。什么是最简单的方法来使其工作?angular2使用另一个组件的方法
//编辑 我想对header.component.html中的html标记执行(单击)事件。在这个函数中,我想从app.component运行方法。
一个可能的例子:
在HTML中app.component.html:
...<app-intro></app-intro>
在intro.compoennt.html的HTML:
...<app-header #header></app-header>
和app.component 。:
@ContentChild("header")
public headerComponent: HeaderComponent;
你也可以传递回调函数的子组件为@input(阵营风格):
\t //app.component.html:
\t <app-intro [appMethod] = "boundMethod"></app-intro>
\t export class AppComponent { \t
\t ngOnInit() {
this.boundMethod = this.appMethod.bind(this);
\t }
\t appMethod() {
console.log("appMethod called");
\t }
\t }
\t //intro.component:
\t <app-header [appMethod] = "appMethod"></app-header>
\t export class IntroComponent {
\t @Input() public appMethod: Function;
\t }
\t //header.component:
\t export class HeaderComponent {
\t @Input() appMethod: Function;
\t ngOnInit() {
appMethod(); // Call parent method
\t }
\t }
你在正确的方向。你应该使用@ViewChild装饰器。 –
你是什么意思的方法'初始化'在app.component?你在问如何调用在header.component中的app.component中定义的方法,反之亦然?或者是关于在app.component中初始化为传递给header.component的'property'? – amal
我的意思是说这个方法已经定义好了。 U更新后,谢谢 –