Angular 角度2使用另一个组件的方法

Angular 角度2使用另一个组件的方法,angular,Angular,我有层次结构中的组件:app.component>intro.component>header.component。我想在header.component中使用,该方法在app.component中定义。我知道有办法通过@viewChild实现。最简单的方法是什么 //编辑 我想在header.component.html中的html标记上执行(单击)事件。在这个函数中,我想从app.component运行方法。一个可能的例子: 在app.component.html中的html中: ...&l

我有层次结构中的组件:app.component>intro.component>header.component。我想在header.component中使用,该方法在app.component中定义。我知道有办法通过@viewChild实现。最简单的方法是什么

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

一个可能的例子:

在app.component.html中的html中:

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

选中

您还可以将回调函数作为@input(React样式)传递给子组件:

//app.component.html:
导出类AppComponent{
恩戈尼尼特(){
this.boundMethod=this.appMethod.bind(this);
}
appMethod(){
log(“调用appMethod”);
}
}
//简介部分:
导出类导入组件{
@Input()公共appMethod:函数;
}
//header.component:
出口类标题组件{
@Input()appMethod:函数;
恩戈尼尼特(){
appMethod();//调用父方法
}

}
您的方向是正确的。你应该使用@ViewChild装饰器。你说app.component中的方法“initialized”是什么意思?您是否询问如何在header.component中调用app.component中定义的方法,或者反之亦然?或者是关于在app.component中初始化的要传递到header.component的“属性”吗?我的意思是该方法已定义。U更新的帖子,谢谢。另一种可能的情况是,您使用一种可以注入任何控件的服务来传递对象;当我想在header.component中运行方法时,在app.component中?对不起,是的,这是一个问题:如果你想在其控制之外使用它,你必须将它声明为public。另外,我选中了,“@ViewChild”和“@ContentChild:选中它”之间有一点不同。如果它不是模板中的直接子级,您将无法使用'@ViewChild'看到它,但'@ContentChild将“扫描”DOM。我更新了答案
...<app-header #header></app-header>
@ContentChild("header")
public headerComponent: HeaderComponent;