I have custom component tab
. The template of this tab
component looks like:
<ng-content></ng-content>
I use tab
component like this:
<tab>
<ng-template>
...
</ng-template>
</tab>
Inside the tab
component I have an Input
parameter. According to this Input
parameter I want this slotted ng-template
to be rendered or not. How can I implement this? How can I render this ng-template
from inside the tab
component?
If you are using ng-template
, you cannot use ng-content
to render this. You need to use the ngTemplateOutlet
directive:
Parent template:
<button (click)="show = !show">Toggle</button>
<tab [show]="show">
<ng-template>
I am rendered
</ng-template>
</tab>
Child ts:
export class HelloComponent {
@ContentChild(TemplateRef)
template?: TemplateRef<any>;
@Input()
show?: boolean;
}
Child template:
<ng-container *ngIf="show" [ngTemplateOutlet]="template"></ng-container>
Another way would be to leave the showing to the parent component:
Parent template:
<button (click)="show = !show">Toggle</button>
<tab>
<ng-template [ngIf]="show">
I am rendered
</ng-template>
</tab>
Child template:
<ng-content></ng-content>
The last answer sounds like it opposes my first answer where I mentioned that you cannot use ng-content
to render the ng-template
, but in this case the *ngIf
is taking care of the rendering of the template.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.