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

时间:2017-02-16 17:53:41

标签: angular typescript

我有一个模态窗口组件,我通过<ng-content></ng-content>插入模态内容组件并进行翻译。我需要从模态组件中调用模态内容中的函数。在这种情况下,它可以重置模态内容的状态。如何获得对模态内容的引用,以便我可以调用其中一个函数?或者是否有更好的方式与我的孩子内容组件进行通信?

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

我尝试了几种我找到的解决方法,但我没有运气。如果有人可以提供一个傻瓜,那将有很大帮助。

2 个答案:

答案 0 :(得分:1)

您应该可以使用ContentChild装饰器访问它。

父:

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

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

    ...

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

更新:请注意,我最初拥有&#34; ViewChild&#34; - 这是原始链接。

在此处查看更多信息: 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

答案 1 :(得分:0)

Chrispy的评论是正确的。 &#34; ...您可以将#templateRef添加到包含它的被转换组件中(即不在ng-content上),然后您可以将其用作选择器。&#34;

所以我的父母(模态)组件:

@ContentChild('transcludedContent') private transcludedContent: ModalContent;

然后我带来了模态:

<modal>
  <transcluded-component #transcludedContent>
  </transcluded-component>
</modal>