![](/img/trans.png)
[英]How do I dynamically access or render Children in an Angular Component?
[英]How do I remove a component dynamically in angular 9?
我必須創建一個多選過濾器,它可以接受要單擊的多選項值,以便優化后端某些 get API 端點的響應。
每當用戶點擊一個選項時,一個“芯片”組件將動態呈現以了解用戶:“嘿,你只是通過這個和那個過濾器選項過濾結果”
在互聯網上環顧四周,我發現了這個stackblitz
在此代碼示例中,我以某種方式理解這一行:
let componentFactory = this.CFR.resolveComponentFactory(ChildComponent);
let childComponentRef = this.VCR.createComponent(componentFactory);
我們在ViewContainerRef
插入給定子組件的實例。 找到一個有點像這樣的對象:
_data: Object { renderElement: <!-- -->, componentView: undefined, viewContainer: {…}, … }
_elDef: Object { nodeIndex: 4, bindingIndex: 0, outputIndex: 1, … }
_embeddedViews: Array(5) [ {…}, {…}, {…}, … ] //here
_view: Object { def: {…}, parent: {…}, state: 1036, … }
在__embeddedViews
對象下,動態生成的視圖將堆疊起來
后來決定刪除哪些視圖,這個stackblitz的創建者只是獲取組件並創建一個ViewContainerRef.indexOf(component)
來獲取存儲組件的索引並驗證動態生成的組件是否存在於該數組中。 然后他/她只是刪除調用this.ViewContainerRef.remove(index);
的視圖this.ViewContainerRef.remove(index);
有趣的是,在我的實現中,當我記錄我的ViewContainerRef
我得到這個對象作為響應:
_hostTNode: Object { type: 0, index: 23, injectorIndex: 34, … }
_hostView: Array(94) [ ..., {…}, 147, … ]
_lContainer: Array(12) [ <!--
芯片按預期成功動態添加,但沒有 _embeddedViews,因此我無法動態刪除它們,因為ViewContainerRef.indexOf(chip)
將始終返回 -1 為“不,我這里沒有“芯片””請可以有人啟發我並展示我在這里做錯了什么?
你有這樣的不一致是因為你以錯誤的方式使用 ViewContainerRef API。
這是indexOf方法的簽名:
abstract indexOf(viewRef: ViewRef): number;
這個簽名在 Angular 更新期間從未改變。
您所指的 stackblitz 使用 Angular 6 版本,該版本在幕后利用 ViewEngine,但在您的代碼中,您使用的是 Angular 9 及更高版本,其中 Ivy 編譯器發揮作用。
在stackblitz你有:
this.VCR.indexOf(componentRef as any);
這意味着您正在傳遞 ComponentRef 實例而不是 ViewRef 實例。 它的工作是偶然的,因為 indexOf 方法看起來像:
ViewContainerRef_.prototype.indexOf = function (viewRef) {
return this._embeddedViews.indexOf(viewRef._view);
};
和
ComponentRef._view === ViewRef._view
中的ViewEngine
。
您應該改為傳遞ViewRef
實例:
this.VCR.indexOf(componentRef.hostView)
該演示適用於 Ivy(您的特定情況),但也適用於 ViewEngine。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.