[Angular] Create dynamic content with <tempalte>

To create a dynamic template, we need to a entry component as a placeholder. Then we can use entry component to create a new Tamplete into it.

 

import { Component, TemplateRef, ComponentRef, ViewContainerRef, ViewChild, AfterContentInit, ComponentFactoryResolver } from '@angular/core';

import { AuthFormComponent } from './auth-form/auth-form.component';

import { User } from './auth-form/auth-form.interface';

@Component({
  selector: 'app-root',
  template: `
    <div>
      <div #entry></div>
      <template #tmpl let-obj let-location="location">
          <details>
            <summary>{{obj.name}}</summary>
            <p> - Age: {{obj.age}}</p>
            <p> - Address :{{location}}</p>
          </details>
      </template>
    </div>
  `
})
export class AppComponent implements AfterContentInit {

  @ViewChild('entry', { read: ViewContainerRef }) entry: ViewContainerRef;
  @ViewChild('tmpl') tmpl: TemplateRef<any>

  ngAfterContentInit() {
    this.entry.createEmbeddedView(this.tmpl, {
      $implicit: {
        name: 'Zhentian',
        age: 27
      },
      location: 'China'
    })
  }

}

 

As we can see, we defined:

let-obj let-location="location"

let-obj: because nothing is assigned to 'let-obj', it means it will show all the $implicit value we defined in when we 'createEmbeddedView' as a second arguement.

 

If we open dev tools, we can see there is a '<div></div>' placeholder was created and the template we created is actually not inject into the placeholder div block, it is below placeholder.

posted @ 2017-03-06 19:11  Zhentiw  阅读(239)  评论(0编辑  收藏  举报