簡體   English   中英

如何在父組件中以角度4動態加載組件

[英]How to load dynamically a component in angular 4 in the parent component

我正在創建要加載到父組件中的模板組件,具體取決於我從服務器得到的響應。 我將給您一個簡短的示例,說明我正在嘗試使用偽代碼執行的操作。

這是我的html父組件:

<div class="parent-container">
    <div *ngIf="template1"> (load template1.component) </div>
    <div *ngIf="template2"> (load template2.component) </div>
    etc...
</div>

那么我將擁有不同的組件(為簡潔起見,我只列出其中一個)

<div class="child-container">
    <div> {{userName}} </div>
    <div> {{contactNo}} </div>
    <div> {{address}} </div>
</div>

因此在ngInit上,父級向服務器發出一個http請求並獲取一個值。 取決於父級中的值,我應該能夠將子級模板加載到父級中並顯示它。 因此,加載后,頁面將如下所示:

<div class="parent-container">
    <div class="child-container">
        <div> {{userName}} </div>
        <div> {{contactNo}} </div>
        <div> {{address}} </div>
    </div>
</div>

有可能成角度嗎? 我如何創建它? 謝謝

[ 編輯 ]

我實現了dee zg的建議,這是代碼:

@ViewChild(HostDirective) host: HostDirective;

OnNgInit(){}

//switch will be a response from a server 
selector(switch){
    switch(switch) { 
       case 'component1': { 
         this.loadComponent(Component1);
         break; 
      }  
      default: { 

         break; 
      } 
   } 

  }

  loadComponent(component){   


    var componentFactory = this._componentFactoryResolver.resolveComponentFactory(component);
    var viewContainerRef = this.host;
    this.viewContainerRef.clear();
    var componentRef = this.viewContainerRef.createComponent(componentFactory);

    (componentRef.instance);

  }

這就是我的主人里面

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[host]',
})
export class HostDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

和html

<ng-template host></ng-template>

有趣的是,如果將loadComponent內部的任何內容加載到OnInit中,那么它將起作用。 如果從loadComponent調用它,則將獲得該主機未定義的信息。

在模板中:

<ng-template #yourComponentHost></ng-template>

在組件中:

@ViewChild('yourComponentHost', { read: ViewContainerRef })
  yourComponentHost;
.
.
.
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(YourComponentType1);
    const viewContainerRef = this.yourComponentHost;
    viewContainerRef.clear();
    const componentRef = viewContainerRef.createComponent(componentFactory);

    const yourComponentType1Instance = (<YourComponentType1>componentRef.instance);

在這里,您可以通過yourComponentType1Instance來訪問組件。 當然,您將在resolveComponentFactory執行自己的開關邏輯,以根據所需條件使用所需的組件。

這會讓您感到困惑。 因為遇到問題,為什么不為孩子創建組件。

<div class="parent-container">
    <div *ngIf="template1"> <template1 [myData]="myData"></template1> </div>
    <div *ngIf="template2"> <template2 [myData]="myData"></template2> </div>
    etc...
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM