我有一个模态窗口组件,并且我正在通过嵌入插入模态内容组件<ng-content></ng-content>
。我需要从模态组件调用模态内容中的函数。在本例中,它是重置模式内容的状态。如何获取对模态内容的引用以便我可以调用它的函数之一?或者是否有更好的方式与我的子内容组件进行通信?
更新:我正在嵌入不同的组件,所以我确实需要一种方法来获取引用,而不知道嵌入的内容是什么类型。
我已经尝试了几种找到的解决方法,但我没有任何运气。如果有人可以提供一个 plunkr,那会有很大帮助。
您应该能够使用 ContentChild 装饰器来访问它。
Parent:
import {ChildComponent} from "../child-path";
export class ParentComponent {
@ContentChild(ChildComponent) childComponent: childComponent;
var parentVar = "data";
...
ngAfterViewInit(){
childComponent.callYourFunction(parentVar);
}
}
更新:请注意,我最初有“ViewChild”——这是原始链接。
在这里查看更多内容:http://learnangular2.com/viewChild/ http://learnangular2.com/viewChild/
EDIT:
请参阅 Gunter 的评论 - 他认为 ViewChild 在这种情况下不起作用,这是正确的。 ContentChild 是一个类似但正确的答案。
https://angular.io/docs/ts/latest/api/core/index/ContentChild-decorator.html https://angular.io/docs/ts/latest/api/core/index/ContentChild-decorator.html
EDIT 2:
对于 ng-content 类型的问题,看起来也许你可以这样做:
在父级中:
<parent-component>
<child-component #child></child-component>
</parent-component>
@ContentChild('child') contentChild: ChildComponent
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)