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


Posted in Javascript onMay 28, 2017

前言

有时候需要根据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。

const COMPONENTS = [ ];

@NgModule({
 declarations: [ ...COMPONENTS ],
 imports: [
 StepModule.withComponents([ ...COMPONENTS ])
 ]
})
export class AppModule { }

2、一个示例

有3个Step步骤的组件,分别为:

// user-one.component.ts
import { Component, OnDestroy, Input, Injector, EventEmitter, Output } from '@angular/core';
@Component({
 selector: 'step-one',
 template: `<h2>Step One Component:params value: {{step}}</h2>`
})
export class UserOneComponent implements OnDestroy {
 private _step: string;
 @Input() 
 set step(str: string) {
 console.log('@Input step: ' + str);
 this._step = str;
 }
 get step() {
 return this._step;
 }

 ngOnInit() {
 console.log('step one init');
 }
 ngOnDestroy(): void {
 console.log('step one destroy');
 }

}

user-two、user-third 略同,这里组件还需要进行注册:

const STEPCOMPONENTS = [ UserOneComponent, UserTwoComponent, UserThirdComponent ];

@NgModule({
 declarations: [ ...STEPCOMPONENTS ],
 imports: [
 StepModule.withComponents([ ...STEPCOMPONENTS ])
 ]
})
export class AppModule { }

这里没有 entryComponents 字眼,而是为 StepModule 模块帮助我们动态注册。这样至少看起来更内聚一点,而且并不会与其他 entryComponents 在一起,待东西越多越不舒服。

最后,还需要 UserComponent 组件来维护步骤容器,会根据 URL 参数的变化,利用 StepComponent 组件动态加载相应组件。

@Component({
 selector: 'user',
 template: `<step [comp]="stepComp"></step>`
})
export class UserComponent {
 constructor(private route: ActivatedRoute) {}
 stepComp: any;
 ngOnInit() {
 this.route.queryParams.subscribe(params => {
  const step = params['step'] || 'step-one';
  // 组件与参数对应表
  const compMaps = {
  'step-one': { component: UserOneComponent, inputs: { step: step } },
  'step-two': { component: UserTwoComponent },
  'step-third': { component: UserThirdComponent },
  };
  this.stepComp = compMaps[step];
 });
 }
}

非常简单的使用,而且又对AOT比较友好。

总结

文章里面一直都在提AOT,其实AOT是Angular为了提供速度与包大小而生的,按我们项目的经验来看至少在包的大小可以减少到 40% 以上。

当然,如果你是用angular cli开发,那么,当你进行 ng build --prod 的时候,默认就已经开启 AOT 编译模式。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家三水点靠木的支持。

Javascript 相关文章推荐
jQuery中使用Ajax获取JSON格式数据示例代码
Nov 26 Javascript
js实现日期级联效果
Jan 23 Javascript
js图片切换具体实现代码
Oct 13 Javascript
JS实现“隐藏与显示”功能(多种方法)
Nov 24 Javascript
前端编码规范(3)JavaScript 开发规范
Jan 21 Javascript
angularjs $http实现form表单提交示例
Jun 09 Javascript
详解Angular-ui-BootStrap组件的解释以及使用
Jul 13 Javascript
JavaScript面向对象程序设计中对象的定义和继承详解
Jul 29 Javascript
JS面向对象编程实现的Tab选项卡案例详解
Mar 03 Javascript
vue实现简单学生信息管理
May 30 Javascript
原生JS实现多条件筛选
Aug 19 Javascript
vue组件添加事件@click.native操作
Oct 30 Javascript
利用node.js如何搭建一个简易的即时响应服务器
May 28 #Javascript
利用Angular.js编写公共提示模块的方法教程
May 28 #Javascript
Angular2入门教程之模块和组件详解
May 28 #Javascript
关于Angular2 + node接口调试的解决方案
May 28 #Javascript
对象不支持indexOf属性或方法的解决方法(必看)
May 28 #Javascript
设置cookie指定时间失效(实例代码)
May 28 #Javascript
Mac系统下Webstorm快捷键整理大全
May 28 #Javascript
You might like
将兴奋、喜悦和坎加斯带到戴安娜:亚马逊公主
2020/03/03 欧美动漫
微信公众平台消息接口校验与消息接口响应实例
2014/12/23 PHP
php生成验证码函数
2015/10/20 PHP
JavaScript 异步调用框架 (Part 3 - 代码实现)
2009/08/04 Javascript
JavaScript实现GriwView单列全选(自写代码)
2013/05/13 Javascript
把jQuery的类、插件封装成seajs的模块的方法
2014/03/12 Javascript
jquery跨域请求示例分享(jquery发送ajax请求)
2014/03/25 Javascript
javascript字母大小写转换的4个函数详解
2014/05/09 Javascript
js显示当前日期时间和星期几
2015/10/22 Javascript
js实现的下拉框二级联动效果
2016/04/30 Javascript
微信小程序使用第三方库Underscore.js步骤详解
2016/09/27 Javascript
JS实现拖拽的方法分析
2016/12/20 Javascript
Webpack如何引入bootstrap的方法
2017/06/17 Javascript
vue iView 上传组件之手动上传功能
2018/03/16 Javascript
Vue打包部署到Nginx时,css样式不生效的解决方式
2020/08/03 Javascript
[10:34]DOTA2上海特级锦标赛全纪录
2016/03/25 DOTA
Python中的赋值、浅拷贝、深拷贝介绍
2015/03/09 Python
Python中selenium实现文件上传所有方法整理总结
2017/04/01 Python
uwsgi+nginx部署Django项目操作示例
2018/12/04 Python
Python实现FTP弱口令扫描器的方法示例
2019/01/31 Python
python全栈知识点总结
2019/07/01 Python
Django 后台获取文件列表 InMemoryUploadedFile的例子
2019/08/07 Python
python3实现elasticsearch批量更新数据
2019/12/03 Python
详解Django配置JWT认证方式
2020/05/09 Python
详解Python多线程下的list
2020/07/03 Python
雅诗兰黛澳大利亚官网:Estée Lauder澳大利亚
2019/05/31 全球购物
企业为何需要商业计划书
2013/12/26 职场文书
党员干部承诺书
2014/03/25 职场文书
工作鉴定评语
2014/05/04 职场文书
地理科学专业自荐信
2014/09/01 职场文书
致百米运动员广播稿5篇
2014/10/13 职场文书
2014年施工员工作总结
2014/11/18 职场文书
2014年市场部工作总结
2014/11/25 职场文书
团员个人年度总结
2015/02/26 职场文书
卫生院义诊活动总结
2015/05/07 职场文书
教师节联欢会主持词
2015/07/04 职场文书