Lijin Durairaj
Lijin Durairaj

Reputation: 5242

How to use createEmbeddedView method of TemplateRef in angular4?

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')
  }
}

Upvotes: 11

Views: 27135

Answers (2)

beegG
beegG

Reputation: 11

There is an alternative(easier) route that produces the same effect as the createEmbeddedView(). The next example provides both the short notation and long form notation:

@Component({
    selector: 'app-root',
    template: `
    <ng-template #yourTemplateRef let-item="data">
        Data is: {{data}}
    </ng-template>
    <!-- Long notation -->
    <ng-container 
       [ngTemplateOutlet]="yourTemplateRef"
       [ngTemplateOutletContext]="{data: data}">
    </ng-container>

 <!-- Short notation -->
    <ng-container 
      *ngTemplateOutlet="yourTemplateRef; context: {data: data}">
    </ng-container>
    `
})
export class AppComponent { data = 123; }

Upvotes: 1

Max Koretskyi
Max Koretskyi

Reputation: 105517

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.

Upvotes: 21

Related Questions