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.