Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom directive with ng-template and ngIf?

Tags:

angular

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?

like image 751
FIL Avatar asked Oct 20 '25 16:10

FIL


1 Answers

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

like image 87
Asanka Avatar answered Oct 23 '25 07:10

Asanka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!