[Angular] Create dynamic content with <tempalte>
2024-08-31 19:21:12
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进击C#——语法之线程同步
- java JSP(原创新手可进)
- 2 django系列之django分页与templatetags
- eclipse+android+opencv环境搭建的步骤
- Java-继承 共3题
- Scalaz(41)- Free :IO Monad-Free特定版本的FP语法
- django 视图开发与url配置
- Hive_DDL与DML
- python model对象转为dict数据
- 4.0以后的新布局方式GridLayout
- Lipo Error!! can't open input file
- php中getimagesize函数的用法
- C# 线程间互相通信
- Protel 99SE铺铜问题总结
- 生成md5密码
- HDU/HDOJ 2612 Find a way 双向BFS
- SQL Server on Red Hat Enterprise Linux——RHEL上的SQL Server(全截图)
- linux命令行解刨
- eclipse中搜狗输入法中文状态下输出的全是英文
- JBOD