Use Template Elements in Angular

InstructorJohn Lindquist

Share this video with your friends

Send Tweet

The <template> element is a core piece of building complex UI in Angular. You can get a reference to these elements, then pass them around and create new elements based on them.

Fabio Bedini
~ 7 years ago

I think you should use ngOnInit because of both in ngAfterViewInit and ngAfterContentInit if you use binding like

<ng-template #myTemplate>
{{name}}
</ng-template>

name = 'whisher';

You get ExpressionChangedAfterItHasBeenCheckedError

Isaac Mann
~ 6 years ago

@t301000 yes, you can use ngAfterViewInit since John is accessing the <template> with @ViewChild. You would need to use ngAfterContentInit if you were accessing the <template> with @ContentChild (i.e. a parent component was passing down the <template> in the contents of the BasicComponent.

Phalgun Vaddepalli
~ 2 years ago

The code for BasicComponent does work with Angular 15. It should be updated as below:

@Component({ selector: 'basic', template: <ng-template #foo> This is content inside a template </ng-template> }) export class BasicComponent{ @ViewChild('foo', {static: true}) template!: TemplateRef<any>

constructor(private view:ViewContainerRef){}

ngOnInit() { this.view.createEmbeddedView(this.template) this.view.createEmbeddedView(this.template) this.view.createEmbeddedView(this.template) } }