zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    Java构造和解析Json数据的两种方法详解一
    微信小程序-自定义组件
    微信小程序
    微信公众号
    微信小程序
    微信小程序
    微信小程序
    vue
    vue
    sass 和 css 互转网址
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6511469.html
Copyright © 2011-2022 走看看