• [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.

  • 相关阅读:
    每日口语(6.12)
    The usage of thumb
    Chart相关网站
    每日口语(6.14)
    我为世界杯狂
    一个很简单的javascript问题,看你能否答对
    【转】理解伪元素:Before和:After
    JS BOM之location.hash详解
    JS BOM之location对象
    JS BOM之location.hash的用法
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6511469.html
Copyright © 2020-2023  润新知