Angular 6 nested ViewChild inside ng-template is null

Erwol picture Erwol · Nov 8, 2018 · Viewed 9.2k times · Source

We are using a modal (ng-bootstrap's one) in our application. That modal looks like:

<ng-template #modal let-modal>
    <app-audio #audio></app-audio>
</ng-template>

And it's logic:

@ViewChild('modal')
modal: ElementRef;

@ViewChild('audio')
audio: AudioComponent;

The modal is opened with:

this.modalService.open(this.modal, { size: 'lg' });

Everything fine till here. The modal opens and the audio component is shown. But now, we want to access the logic that is inside the component, and when doing something like:

this.audio.somePublicComponentFunction()

It happens that this.audio is null. I have already tried to get the child with angular's change detector, but cannot find a way to properly link this.audio with the actual component. Any ideas? Thanks a lot.

You can see the issue here: stackblitz.com/edit/angular-ofmpju

Answer

Amit Chigadani picture Amit Chigadani · Nov 8, 2018

You can call the method audio.someFunction() from the template itself.

<ng-template #modal let-modal>
  <div style="background-color: red;"> 
  <h1>Modal header</h1>
  <app-audio #audio></app-audio>
  <!-- on click, call audio comp method someFunction() using its reference --> 
  <button (click)="audio.someFunction()">Operate with audio from inside modal</button>
  </div>
</ng-template>

No need of @ViewChild property here. This should do the trick for you.

Forked demo