I want to pass html element from parent to child based on conditions like If user click button in parent child should display button or If user select chckbox then child should display checkbox This is my scenario
To solve this I am using ngTemplateOutlet, ngContent through content projection concepts in angular.
I am getting error in console ERROR Error: templateRef.createEmbeddedView is not a function
I tried like this
<button (click)="getType('button')">Display button in child</button>
<div>
<label>checkbox</label>
<input type="checkbox" (change)="getType('checkbox')">
</div>
<app-child>
<ng-container [ngTemplateOutlet]="dynamicElement"></ng-container>
<ng-template #tp2>
<button>Hey I am button passed dynamically from parent</button>
</ng-template>
<ng-template #tp3>
<label>I am checkbox passed from parent</label>
<input type="checkbox" (change)="getType('checkbox')">
</ng-template>
Please find link I work out https://stackblitz.com/edit/angular-yzzsgs-dnfgaq?file=src/app/app.component.ts
Is there any other way?
Any help will appreciable
Thanks in advance
Modify your code as following:
export class AppComponent {
@ViewChild('tp2') public readonly tp2;
@ViewChild('tp3') public readonly tp3;
title = 'Tour of Heroes';
dynamicElement: any;
heroes = [
new Hero(1, 'Windstorm'),
new Hero(13, 'Bombasto'),
new Hero(15, 'Magneta'),
new Hero(20, 'Tornado')
];
myHero = this.heroes[0];
getType (type) {
console.log(type);
if (type == 'button') {
this.dynamicElement = this.tp2;
} else {
this.dynamicElement = this.tp3;
}
}
}
You need to import ViewChild directive from '@angular/core' by the way and with it get Ref's from the template for passing it to the ngTemplateOutlet