gpt4 book ai didi

使用嵌入插入的组件的 Angular 2+ 调用函数(ng-content)

转载 作者:搜寻专家 更新时间:2023-10-30 21:52:03 24 4
gpt4 key购买 nike

我有一个模态窗口组件,我正在通过 <ng-content></ng-content> 插入带有嵌入的模态内容组件。 .我需要从模态组件调用模态内容中的函数。在这种情况下,它是重置模态内容的状态。我怎样才能获得对我的模态内容的引用,以便我可以调用它的功能之一?或者是否有更好的方式与我的子内容组件进行通信?

更新:我正在嵌入不同的组件,所以我确实需要一种方法来获取引用而不知道嵌入的内容是什么类型。

我已经尝试了几种我发现的解决方法,但我没有任何运气。如果有人可以提供一个 plunkr,那将有很大帮助。

最佳答案

您应该能够使用 ContentChild 装饰器访问它。

家长:

import {ChildComponent} from "../child-path";

export class ParentComponent {
@ContentChild(ChildComponent) childComponent: childComponent;
var parentVar = "data";

...

ngAfterViewInit(){
childComponent.callYourFunction(parentVar);
}
}

更新:请注意,我最初有“ViewChild”——这是原始链接。

在这里查看更多: http://learnangular2.com/viewChild/

编辑:

请参阅 Gunter 的评论——他是正确的,ViewChild 在这种情况下不起作用。 ContentChild 将是一个相似但正确的答案。

https://angular.io/docs/ts/latest/api/core/index/ContentChild-decorator.html

编辑 2:

对于 ng-content 类型的问题,看起来你可以这样做:

在父级中:

<parent-component>
<child-component #child></child-component>
</parent-component>


@ContentChild('child') contentChild: ChildComponent

关于使用嵌入插入的组件的 Angular 2+ 调用函数(ng-content),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42281327/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com