程序员

Angular 动态加载组件

2018-11-19  本文已影响57人  柳源居士

场景:
应用在运行期间加载一些新的组件。
用法:
锚点指令:

  1. 需要用锚点指令告诉angular 在哪里插入新组件。
    首先建立一个锚点指令,xx.directive.ts文件。并在构造方法里注入ViewContainerRef,来获取容器视图的访问权,这个容器就是那些动态加入的组件的宿主。指令文件的装饰器中包含一个指令名称,需要将其包含在需要显示的<ng-template ad-host> </ng-template>中。
 <ng-template ad-host> </ng-template>

<ng-template> 元素是动态加载组件的最佳选择,因为它不会渲染任何额外的输出。

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[ad-host]',
})
export class AdDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

ViewContainerRef来自于@angular/core.

  1. 传入组件数组
    传入组件数组,来动态加载传入的组件类,以及绑定到该组件上的任意数据。
    组件数组是一个对象接口,包含了组件类型以及该组件的数据:
import { Type } from '@angular/core';

export class AdItem {
  constructor(public component: Type<any>, public data: any) {}
}

需要引用ComponentFactoryResolver 。它会为每个组件解析出一个ComponentFactory,ComponentFactory又会为每个组件创建一个实例。

再使用viewContainerRef 的createComponent()方法,来返回一个component的引用。使用这个引用就可以与该组件进行交互,比如设置它的属性或调用它的方法。

loadComponent() {
    this.currentAdIndex = (this.currentAdIndex + 1) % this.ads.length;
    let adItem = this.ads[this.currentAdIndex];
    //解析出该组件的componentFactory ,adItem.component是一个组件类型
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(adItem.component);
    //adHost是锚点组件的引用
    let viewContainerRef = this.adHost.viewContainerRef;
    viewContainerRef.clear();
    //创建该动态组件的引用
    let componentRef = viewContainerRef.createComponent(componentFactory);
    //对该组件的属性赋值
    (<AdComponent>componentRef.instance).data = adItem.data;
  }

  1. 在@NgModule()里面声明entryComponents
    声明动态组件在entryComponents里:
    entryComponents:[动态组件1,动态组件2]
上一篇 下一篇

猜你喜欢

热点阅读