Angular動態載入元件

2021-09-16 21:40:30 字數 2501 閱讀 9386

有時候需要根據url來渲染不同元件,我所指的是在同乙個url位址中根據引數的變化顯示不同的元件;這是利用angular動態載入元件完成的,同時也會設法讓這部分動態元件也支援aot。

下面以乙個step元件為示例,完成乙個3個步驟的示例展示,並且可以通過urluser?step=step-one的變化顯示第n個步驟的內容。

首先,還是需要先建立動態載入元件模組。

import  from '@angular/core';

@component()

export class step implements ondestroy

@input() set data(data: } )

}this.destroy();

this.currentcomponent = component;

} destroy()

} ngondestroy(): void

}

拋開一銷毀動作不談的話,實際就兩行**:

let compfactory = this.cfr.resolvecomponentfactory(this.comp);
利用componentfactoryresolver查詢提供元件的componentfactory,而後利用這個工廠來建立實際的元件。

this.compinstance = this.vcr.createcomponent(compfactory);
這一切都非常簡單。

而對於一些基本的引數,是直接對元件例項進行賦值。

for (let key in data.inputs)
最後,還需要告訴angular aot編譯器為使用者動態元件提供工廠註冊,否則componentfactoryresolver會找不到它們,最簡單就是利用ngmodule.entrycomponents進行註冊。

@ngmodule()
但這樣其實還是挺奇怪的,entrycomponents本身可能還會存在其他元件。而動態載入元件本身是乙個通用性非常強,因此,把它封裝成名曰stepmodule挺有必要的,這樣的話,就可以建立一種看起來更舒服的方式。

@ngmodule()

export class stepmodule ]}

}}

通過利用analyze_for_entry_components將多個元件以更友好的方式動態註冊至entrycomponents

const components = [  ];

@ngmodule()

有3個step步驟的元件,分別為:

// user-one.component.ts

import from '@angular/core';

@component()

export class useronecomponent implements ondestroy

get step()

ngoninit()

ngondestroy(): void

}

user-two、user-third 略同,這裡元件還需要進行註冊:

const stepcomponents = [ useronecomponent, usertwocomponent, userthirdcomponent ];

@ngmodule()

這裡沒有entrycomponents字眼,而是為stepmodule模組幫助我們動態註冊。這樣至少看起來更內聚一點,而且並不會與其他entrycomponents在一起,待東西越多越不舒服。

最後,還需要usercomponent元件來維護步驟容器,會根據 url 引數的變化,利用stepcomponent元件動態載入相應元件。

@component()

export class usercomponent

stepcomp: any;

ngoninit() },

'step-two': ,

'step-third': ,

};this.stepcomp = compmaps[step];

});}}

非常簡單的使用,而且又對aot比較友好。

文章裡面一直都在提aot,其實aot是angular為了提供速度與包大小而生的,按我們專案的經驗來看至少在包的大小可以減少到 40% 以上。

當然,如果你是用angular cli開發,那麼,當你進行ng build --prod的時候,預設就已經開啟 aot 編譯模式。

Angular中的動態元件載入

看了angular官網hero教程中的動態元件一節,然後還看了一篇講的不錯的文章,結合自己的理解,總結angular動態元件載入如下 首先我們抽象地考慮一下,動態元件載入需要哪些東西?首先你要載入的元件們應該定義出來,其次你需要乙個可以掛載這些動態元件的容器,並且要考慮怎麼把你的元件掛載到容器上。定...

Angular學習 模組和元件的動態載入

可以利用路由的loadchildren來動態載入angular模組和元件。1.建立乙個要動態載入的模組 包含相應的元件 dyn plugin.module.ts import from angular core import from angular common import from pfc p...

angular 動態元件型別

出處 元件型別1 純函式功能,而沒有檢視部分,即factory 類似於 http 元件型別2 不是常駐於檢視,而是動態插入的 有ui的一類元件,有輸入互動 不常被呼叫 類似於model對話方塊 元件型別3 不常駐於檢視,但會被經常呼叫,而且是動態插入的 無輸入互動 有ui的一類元件 類似於popov...