4

I have a modal window component, and I'm inserting the modal content component with transclusion via <ng-content></ng-content>. I need to call a function in my modal content from the modal component. In this case it's to reset the state of the modal content. How can I get a reference to my modal content so that I can call one of it's functions? Or is there a better way to communicate with my child content component?

UPDATE: I am transcluding different components, so I do need a way to get the reference without knowing what type the transcluded content is.

I've tried several workarounds that I've found, and I'm not having any luck. If someone can provide a plunkr, that would help out a lot.

BBaysinger
  • 6,614
  • 13
  • 63
  • 132

2 Answers2

1

You should be able to access this using the ContentChild decorator.

Parent:

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

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

    ...

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

UPDATE: Note that I originally had "ViewChild" -- here's the original link.

See more here: http://learnangular2.com/viewChild/

EDIT:

See Gunter's comment -- he's correct that ViewChild won't work in this case. ContentChild would be a similar, but correct answer.

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

EDIT 2:

For an ng-content type of issue, it looks like maybe you can do this:

In Parent:

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


@ContentChild('child') contentChild: ChildComponent
chrispy
  • 3,552
  • 1
  • 11
  • 19
  • 1
    In this case it should be `@ContentChild()`. `@ViewChild()` is for components added to `ParentComponent`s template directly. – Günter Zöchbauer Feb 16 '17 at 18:38
  • @ViewChild(ChildComponent) only works if you happen to know that ChildComponent is the class that is transcluded. For me this wont work because I'm passing in different components. It doesn't work either if those classes each subclass some superclass. – BBaysinger Feb 16 '17 at 18:55
  • 1
    @BBaysinger I saw an answer in that thread that says you can add the #templateRef to the transcluded component where it is being included (i.e. not on the ng-content), then you can use that as the selector instead. – chrispy Feb 16 '17 at 18:58
0

Chrispy's comment is correct. "...you can add the #templateRef to the transcluded component where it is being included (i.e. not on the ng-content), then you can use that as the selector instead."

So I have in my parent (modal) component:

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

Then where the modal is brought in I have:

<modal>
  <transcluded-component #transcludedContent>
  </transcluded-component>
</modal>
BBaysinger
  • 6,614
  • 13
  • 63
  • 132