I need to generate a component dynamically. I followed this tutorial of Dynamic Component Loader. The problem is that I use *ngIf directive in my template. Now I'm stuck at the following error in my AdBannerComponent:
TypeError: "this.adHost is undefined"
The code from the tutorial is provided on stackblitz.
Here is the code of my AdBannerComponent template:
<div *ngIf="flag">
<h3>Advertisements {{flag.name}}:</h3>
<ng-template ad-host></ng-template>
</div>
How should I use ng-template to display generated component with ngIf directive?
This is because of you have used view child. If you want to use viewchild the component should be rendered as a child component. but with *ngIf it is conditionally rendered. so you can use display:none style instead of *ngIf. display:none only change the visibility.
please refer this link for understand about *ngIf vs display:none
Your edited demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With