[Angular] Create dynamic content with <tempalte>

本文介绍如何使用Angular通过Entry Component在运行时动态创建模板。我们利用ViewChild装饰器获取模板引用,并通过ComponentFactoryResolver创建视图。示例展示了如何将具体的数据绑定到动态生成的模板中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

转载于:https://www.cnblogs.com/Answer1215/p/6511469.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值