How to use createEmbeddedView method of TemplateRef in angular4?

Lijin Durairaj picture Lijin Durairaj · Dec 22, 2017 · Viewed 13k times · Source

I am starting to learn DOM manipulation in Angular and notice templateRef and its method createEmbeddedView. I am more curious to learn about this method. Now all my question is, how to use the createEmbeddedView of this method

@Component({
  selector: 'app-root',
  template: `
<ng-template #template>

</ng-template>
  `
})
export class AppComponent implements AfterViewChecked {
        @ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;      
  constructor() { }

  ngAfterViewChecked() {
    this._template.createEmbeddedView('this is a embedded view')
  }
}

Answer

Max Koretskyi picture Max Koretskyi · Dec 22, 2017

You can create an embedded view using createEmbeddedView method then attach that view to the DOM via ViewContainerRef:

@Component({
    selector: 'app-root',
    template: `
        <ng-template #template let-name='fromContext'><div>{{name}}</ng-template>
        <ng-container #vc></ng-container>
    `
})
export class AppComponent implements AfterViewChecked {
    @ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
    @ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
    constructor() { }

    ngAfterViewChecked() {
        const view = this._template.createEmbeddedView({fromContext: 'John'});
        this.vc.insert(view);
    }
}

Or you can create a view using ViewContainerRef directly:

ngAfterViewChecked() {
    this.vc.createEmbeddedView(this._template, {fromContext: 'John'});
}

The context is an object with properties and you can access those properties through let- bindings.

To learn more read Exploring Angular DOM manipulation techniques using ViewContainerRef and also see this answer.