3

I am facing a bizarre issue with Angular. I want to pass TemplateRef as an input to my component so that I can leverage it, but Angular is not updating the ref when it changes or gets defined. Here's what I am doing:

DummyComponent to which I want to pass TemplateRef:

import { Component, Input, TemplateRef, OnChanges } from '@angular/core';

@Component({
  selector: 'dummy',
  template: `<h1>Dummy: {{name}}</h1>`
})
export class DummyComponent implements OnChanges{ 

  @Input()
  public templateRef: TemplateRef<any>;

  name = 'Angular';

  public ngOnChanges(changes: SimpleChanges) {
    // Template ref is not updating.
    console.log('DummyComponent -->', changes);
  }
}

AppComponent which is using the DummyComponent:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <h1>Hello {{name}}</h1>
  <button (click)="flag=!flag">Toggle</button>
  <br>{{flag}}
  <ng-container *ngIf="flag">
    <ng-template #myTemp></ng-template>
  </ng-container>
  <pre>
    <!-- TemplateRef is not updating -->
    <dummy [templateRef]="myTemp"></dummy>
  </pre>
  `
})
export class AppComponent { name = 'Angular'; flag = false; }

As you can see, I am supplying myTemp template reference to the dummy component. When myTemp ref gets defined i.e. when flag = true; It should be passed to DummyComponent. But it's not happening. Can anyone please tell me what I am missing? Here's the plunkr to play around.

Hitesh Kumar
  • 3,508
  • 7
  • 40
  • 71
  • 1
    Have a look at this https://stackoverflow.com/questions/36642487/angular2-ngif-and-local-template-variables – Yoni Affuta Nov 09 '17 at 12:27
  • @YoniAffuta Thank you very much. Still I would like to keep the question open, since answers in the link above are workaround. – Hitesh Kumar Nov 09 '17 at 12:46

0 Answers0