Angular.js實(shí)現(xiàn)動(dòng)態(tài)加載組件詳解
前言
有時(shí)候需要根據(jù)URL來渲染不同組件,我所指的是在同一個(gè)URL地址中根據(jù)參數(shù)的變化顯示不同的組件;這是利用Angular動(dòng)態(tài)加載組件完成的,同時(shí)也會(huì)設(shè)法讓這部分動(dòng)態(tài)組件也支持AOT。
動(dòng)態(tài)加載組件
下面以一個(gè)Step組件為示例,完成一個(gè)3個(gè)步驟的示例展示,并且可以通過URL user?step=step-one 的變化顯示第N個(gè)步驟的內(nèi)容。
1、resolveComponentFactory
首先,還是需要先創(chuàng)建動(dòng)態(tài)加載組件模塊。
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();
}
}
拋開一銷毀動(dòng)作不談的話,實(shí)際就兩行代碼:
let compFactory = this.cfr.resolveComponentFactory(this.comp);
利用 ComponentFactoryResolver 查找提供組件的 ComponentFactory,而后利用這個(gè)工廠來創(chuàng)建實(shí)際的組件。
this.compInstance = this.vcr.createComponent(compFactory);
這一切都非常簡單。
而對(duì)于一些基本的參數(shù),是直接對(duì)組件實(shí)例進(jìn)行賦值。
for (let key in data.inputs) {
component.instance[key] = data.inputs[key];
}
最后,還需要告訴Angular AOT編譯器為用戶動(dòng)態(tài)組件提供工廠注冊(cè),否則 ComponentFactoryResolver 會(huì)找不到它們,最簡單就是利用 NgModule.entryComponents 進(jìn)行注冊(cè)。
@NgModule({
entryComponents: [ UserOneComponent, UserTwoComponent, UserThirdComponent ]
})
export class AppModule { }
但這樣其實(shí)還是挺奇怪的,entryComponents 本身可能還會(huì)存在其他組件。而動(dòng)態(tài)加載組件本身是一個(gè)通用性非常強(qiáng),因此,把它封裝成名曰 StepModule 挺有必要的,這樣的話,就可以創(chuàng)建一種看起來更舒服的方式。
@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 將多個(gè)組件以更友好的方式動(dòng)態(tài)注冊(cè)至 entryComponents。
const COMPONENTS = [ ];
@NgModule({
declarations: [ ...COMPONENTS ],
imports: [
StepModule.withComponents([ ...COMPONENTS ])
]
})
export class AppModule { }
2、一個(gè)示例
有3個(gè)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 略同,這里組件還需要進(jìn)行注冊(cè):
const STEPCOMPONENTS = [ UserOneComponent, UserTwoComponent, UserThirdComponent ];
@NgModule({
declarations: [ ...STEPCOMPONENTS ],
imports: [
StepModule.withComponents([ ...STEPCOMPONENTS ])
]
})
export class AppModule { }
這里沒有 entryComponents 字眼,而是為 StepModule 模塊幫助我們動(dòng)態(tài)注冊(cè)。這樣至少看起來更內(nèi)聚一點(diǎn),而且并不會(huì)與其他 entryComponents 在一起,待東西越多越不舒服。
最后,還需要 UserComponent 組件來維護(hù)步驟容器,會(huì)根據(jù) URL 參數(shù)的變化,利用 StepComponent 組件動(dòng)態(tài)加載相應(yīng)組件。
@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';
// 組件與參數(shù)對(duì)應(yīng)表
const compMaps = {
'step-one': { component: UserOneComponent, inputs: { step: step } },
'step-two': { component: UserTwoComponent },
'step-third': { component: UserThirdComponent },
};
this.stepComp = compMaps[step];
});
}
}
非常簡單的使用,而且又對(duì)AOT比較友好。
總結(jié)
文章里面一直都在提AOT,其實(shí)AOT是Angular為了提供速度與包大小而生的,按我們項(xiàng)目的經(jīng)驗(yàn)來看至少在包的大小可以減少到 40% 以上。
當(dāng)然,如果你是用angular cli開發(fā),那么,當(dāng)你進(jìn)行 ng build --prod 的時(shí)候,默認(rèn)就已經(jīng)開啟 AOT 編譯模式。
好了,以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家腳本之家的支持。
相關(guān)文章
教你用AngularJS框架一行JS代碼實(shí)現(xiàn)控件驗(yàn)證效果
簡單來說Angular.js是google開發(fā)者設(shè)計(jì)和開發(fā)的一套前端開發(fā)框架,幫助你簡化前端開發(fā)的負(fù)擔(dān)。到底能簡化到什么程度呢,今天我們來看下,一行代碼實(shí)現(xiàn)控件驗(yàn)證效果,有木有嚇尿?2014-06-06
使用AngularJS 跨站請(qǐng)求如何解決jsonp請(qǐng)求問題
這篇文章主要介紹了使用AngularJS 跨站請(qǐng)求如何解決jsonp請(qǐng)求問題,下面通過本文給大家分享解決辦法,需要的朋友參考下2017-01-01
利用Angular2 + Ionic3開發(fā)IOS應(yīng)用實(shí)例教程
這篇文章主要給大家介紹了關(guān)于利用Angular2 + Ionic3開發(fā)IOS應(yīng)用的相關(guān)資料,文中通過示例代碼和圖文介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-01-01
AngularJS實(shí)現(xiàn)表格的增刪改查(僅限前端)
這篇文章主要介紹了AngularJS實(shí)現(xiàn)表格的增刪改查,僅限前端,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
Angular 輸入框?qū)崿F(xiàn)自定義驗(yàn)證功能
AngularJS 表單和控件可以驗(yàn)證輸入的數(shù)據(jù)。本文給大家介紹Angular 輸入框?qū)崿F(xiàn)自定義驗(yàn)證功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下2017-02-02
使用JavaScript的AngularJS庫編寫hello world的方法
這篇文章主要介紹了使用JavaScript的AngularJS庫編寫hello world的方法,AngularJS是一款高人氣的JavaScript庫,需要的朋友可以參考下2015-06-06
AngularJS的ng-repeat指令與scope繼承關(guān)系實(shí)例詳解
這篇文章主要介紹了AngularJS的ng-repeat指令與scope繼承關(guān)系,結(jié)合實(shí)例形式通過ng-repeat指令詳細(xì)分析了scope繼承關(guān)系,需要的朋友可以參考下2017-01-01
angular6的table組件開發(fā)的實(shí)現(xiàn)示例
這篇文章主要介紹了angular6的table組件開發(fā)的實(shí)現(xiàn)示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12

