[Angular] Using ngTemplateOutlet to create dynamic template
Angular to Using create Template Dynamic
2023-09-14 08:59:18 时间
I can use <tamplete> syntax and a entry component as a container to create a dynamic component. Notice it will create a empty div as a placeholder in the DOM. If we don't wanner this empty div, we can actually using ng-conainer together with ngTemplateOutlet (for template ref) and ngTemplateOutletContext (the context).
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> <hr /> <ng-container [ngTemplateOutlet]="tmpl" [ngTemplateOutletContext]="ctx" ></ng-container> </div> ` }) export class AppComponent implements AfterContentInit { @ViewChild('entry', { read: ViewContainerRef }) entry: ViewContainerRef; @ViewChild('tmpl') tmpl: TemplateRef<any>; ctx = { $implicit: { name: 'John', age: 34 }, location: 'USA' } ngAfterContentInit() { this.entry.createEmbeddedView(this.tmpl, { $implicit: { name: 'Zhentian', age: 27 }, location: 'China' }) } }
And in the generated DOM we can see that there is no empty div created.
相关文章
- 自定义 angular-datetime-picker 格式
- angular组件的基本使用
- Angular HTTP 请求自定义 timeout 值的一种实现思路
- angular入门教程_初学者织围巾简单教程慢动作
- Angular 面试题汇总2-Component/Service (Angular v8+)
- angular基础面试题_java web面试题
- to program_I Just Want To
- 前端面试题angular_Vue前端面试题
- Angular 14 新的 inject 函数介绍
- Angular 应用里 index.html 的作用
- Angular 应用开发里使用 ForRoot 解决 Lazy Loaded Module 里单例行为丢失的问题
- 关于 Angular 应用对浏览器 Back 按钮支持问题的讨论
- Angular 项目路径添加指定的访问前缀
- Angular 依赖注入错误消息:ERROR Error NullInjectorError No provider for XX
- Angular 服务器端渲染场景里,服务器端和客户端渲染出的 HTML 源代码有可能不完全一致
- Angular与React、Vue.js的对比
- 基于豆瓣API+Angular开发的webApp