2017-09-26 43 views
2

我在hierarhy中有组件:app.component> intro.component> header.component。我想用在app.component中定义的方法header.component中。我认识到有办法用@viewChild制作它。什么是最简单的方法来使其工作?angular2使用另一个组件的方法

//编辑 我想对header.component.html中的html标记执行(单击)事件。在这个函数中,我想从app.component运行方法。

+0

你在正确的方向。你应该使用@ViewChild装饰器。 –

+0

你是什么意思的方法'初始化'在app.component?你在问如何调用在header.component中的app.component中定义的方法,反之亦然?或者是关于在app.component中初始化为传递给header.component的'property'? – amal

+0

我的意思是说这个方法已经定义好了。 U更新后,谢谢 –

回答

0

一个可能的例子:

在HTML中app.component.html:

...<app-intro></app-intro> 

在intro.compoennt.html的HTML:

...<app-header #header></app-header> 

和app.component 。:

@ContentChild("header") 
public headerComponent: HeaderComponent; 

Che CK https://angular.io/api/core/ContentChild

+0

另一种可能的情况是,您使用服务,您可以注入到任何控制传递对象。 – ForestG

+0

为什么要声明@ViewChild(“header”)private headerComponent:HeaderComponent;在app.component中,当我想在header.component中运行方法? –

+0

对不起,是的,这是一个问题:如果你想让它在控制之外使用,你必须声明它是公开的。 – ForestG

1

你也可以传递回调函数的子组件为@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 }

相关问题