[Angular] Using ngTemplateOutlet to create dynamic template
Angular to Using create Template Dynamic
2023-09-14 09:00:52 时间
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] Subscribing to router events
- [Angular] Using ngTemplateOutlet to create dynamic template
- [Angular] @ViewChild and template #refs to get Element Ref
- [Angular] Using ngOnChanges lifeCycle hook to break object reference
- [Angular 2] Using a Reducer to Change an Object's Property Inside an Array
- [Angular 2] Using ng-for to repeat template elements
- [Angular] Parent scope, scope overwritten, using factory() to share data between controller
- [React] useImperativeHandle, similar to Angular Directive `exportAs`
- [Angular] How to show global loading spinner for application between page navigation
- [Angular] Introduction to Angular Internationalization (i18n)
- [Angular] Two ways to create Angular Animation, using animation() or using state()
- [Angular] NgRx/effect, why to use it?
- [Angular 2] ElementRef, @ViewChild & Renderer
- [Angular 2] How To Debug An Angular 2 Application - Debugging via Augury or the Console
- [Angular 2] *ngFor
- [Angular 2] Using ng-model for two-way binding
- [Angular-Scaled Web] 8. Using $http to load JSON data
- [AngularJS] Using angular.bootstrap to Initialize Your App
- SAP Spartacus的自定义Angular Url Matcher实现
- Another way to define Angular controller
- 动手开始创建第一个 Angular 应用并通过 gh-pages 发布到 Github 上