angular动态组件

angular动态组件

实现原理
通过@ViewChild加自定义指令获取插入节点的viewContainerRef对象,再通过viewContainerRef的createComponent方法将使用ComponentFactoryResolver.resolveComponentFactory方法生成的对象挂载到插入节点
实现代码如下

  1. dynamic.component.ts
import { Component, OnInit, ComponentFactoryResolver, ViewChild } from '@angular/core';
import { DynamicDirective } from './dynamic.directive';
import { Tab1Component } from './tab1/tab1.component';
import { Tab2Component } from './tab2/tab2.component';
import { Tab3Component } from './tab3/tab3.component';@Component({selector: 'app-dynamic',templateUrl: './dynamic.component.html',styleUrls: ['./dynamic.component.sass']
})
export class DynamicComponent implements OnInit {components = [];@ViewChild(DynamicDirective, {static: true}) adHost: DynamicDirective;constructor(private componentFactoryResolver: ComponentFactoryResolver) { }ngOnInit() {this.components.push(Tab1Component);this.components.push(Tab2Component);this.components.push(Tab3Component);this.loadComponent(0);}loadComponent(index) {const component = this.components[index];//生成componentFactoryconst componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);const viewContainerRef = this.adHost.viewContainerRef;viewContainerRef.clear();// 挂载组件const componentInstance = viewContainerRef.createComponent<any>(componentFactory);// 挂载数据componentInstance.instance.data = {name: `我是TAB${index}`};}
}
  1. dynamic.component.html
<p>dynamic works!</p>
<button (click)="loadComponent(0)">tab1</button>
<button (click)="loadComponent(1)">tab2</button>
<button (click)="loadComponent(2)">tab3</button>
<ng-template appDynamic></ng-template>
  1. dynamic.directive.ts
import { Directive, ViewContainerRef } from '@angular/core';@Directive({selector: '[appDynamic]' //指令名称
})
export class DynamicDirective {constructor(public viewContainerRef: ViewContainerRef) { }}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部