首页 > 语言 > JavaScript > 正文

Angular.js实现动态加载组件详解

2024-05-06 15:16:36
字体:
来源:转载
供稿:网友

前言

有时候需要根据URL来渲染不同组件,我所指的是在同一个URL地址中根据参数的变化显示不同的组件;这是利用Angular动态加载组件完成的,同时也会设法让这部分动态组件也支持AOT。

动态加载组件

下面以一个Step组件为示例,完成一个3个步骤的示例展示,并且可以通过URL user?step=step-one 的变化显示第N个步骤的内容。

1、resolveComponentFactory

首先,还是需要先创建动态加载组件模块。

import { Component, Input, ViewContainerRef, ComponentFactoryResolver, OnDestroy, ComponentRef } from '@angular/core';@Component({ selector: 'step', template: ``})export class Step implements OnDestroy { private currentComponent: ComponentRef<any>; constructor(private vcr: ViewContainerRef, private cfr: ComponentFactoryResolver) {} @Input() set data(data: { component: any, inputs?: { [key: string]: any } } ) {  const compFactory = this.cfr.resolveComponentFactory(data.component);  const component = this.vcr.createComponent(compFactory);  if (data.inputs) {  for (let key in data.inputs) {   component.instance[key] = data.inputs[key];  }  }  this.destroy();  this.currentComponent = component; } destroy() { if (this.currentComponent) {  this.currentComponent.destroy();  this.currentComponent = null; } } ngOnDestroy(): void { this.destroy(); }}

抛开一销毁动作不谈的话,实际就两行代码:

let compFactory = this.cfr.resolveComponentFactory(this.comp);

利用 ComponentFactoryResolver 查找提供组件的 ComponentFactory,而后利用这个工厂来创建实际的组件。

this.compInstance = this.vcr.createComponent(compFactory);

这一切都非常简单。

而对于一些基本的参数,是直接对组件实例进行赋值。

  for (let key in data.inputs) {   component.instance[key] = data.inputs[key];  }

最后,还需要告诉Angular AOT编译器为用户动态组件提供工厂注册,否则 ComponentFactoryResolver 会找不到它们,最简单就是利用 NgModule.entryComponents 进行注册。

@NgModule({ entryComponents: [ UserOneComponent, UserTwoComponent, UserThirdComponent ]})export class AppModule { }

但这样其实还是挺奇怪的,entryComponents 本身可能还会存在其他组件。而动态加载组件本身是一个通用性非常强,因此,把它封装成名曰 StepModule 挺有必要的,这样的话,就可以创建一种看起来更舒服的方式。

@NgModule({ declarations: [ Step ], exports: [ Step ]})export class StepModule { static withComponents(components: any) { return {  ngModule: StepModule,  providers: [  { provide: ANALYZE_FOR_ENTRY_COMPONENTS, useValue: components, multi: true }  ] } }}

通过利用 ANALYZE_FOR_ENTRY_COMPONENTS 将多个组件以更友好的方式动态注册至 entryComponents。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选