Search code examples
angular7angular8parent-childangular-templateangular-template-variable

Angular: how do I access the reference variable which is in a ng-template


Is there a way to access #interface, which is declared inside ng-template element?

I must put the <interface-settings inside <ng-template.

Because I would need to use the *ngTemplateOutlet.

As I could not find a solution for this, I have to add another <interface-settings #interface and not declare it inside ng-template.

would appreciate if you know other workaround. Thanks

 //  parent.html
 <button type="button" (click)="interface.apply()"></button>

 <ng-template>
    <interface-settings #interface></interface-settings>
 <ng-template>

 //child.ts (interface-settings.ts)

apply() {
   console.log("apply");
 }

Solution

  • ng-template is used by Angular for templating - meaning it is not rendered in DOM unless certain conditions tell Angular to use it in the actual DOM.

    So when you have your component "interface-setting" inside ng-template - it is not accessible/known by your application unless:

    • the ng-template condition was applied and
    • your host (parent) component has a reference to it:

    For instance, similar to your example:

    <button type="button" (click)="hello.sayHello()">Method Inside Hello</button>
    
    <ng-template>
      <hello #hello></hello>
    <ng-template>
    

    The above on its own won't work as 2 conditions mentioned above are not met. To fix you need to use ViewChild to get reference to the hello component. Like so:

    import { Component, ViewChild } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
    
      @ViewChild('hello') hello;
    
    }
    

    Then you need to make sure the ng-template is used (whatever triggers the ng-template to be placed in DOM for your app):

    <ng-template [ngIf]="true">
      <hello #hello></hello>
    <ng-template>
    

    Now the reference to the method inside child component will work:

    https://stackblitz.com/edit/angular-ivy-hnmw17?file=src/app/app.component.html

    You can read more how Angular's structural directives under the hood use ng-template: https://angular.io/guide/structural-directives