簡體   English   中英

有沒有辦法在 Angular 中在運行時對組件進行戰略加載?

[英]Is there any way to do stratergic loading of component at runtime in Angular?

  • 我有這個應用程序,我在其中對服務器執行 rest 調用並接收 JSON 響應,其中包含特定 UI 設置的名稱。
  • 假設從服務器接收到的數據如下,
    回復:-
{
    "uiSetting" : "ui-type-one"
}
  • 可以有多個 UI 設置,如 ui-type-2、ui-type-3 等。
  • angular 中有沒有辦法根據這個 uiSetting 值來決定在運行時加載哪個組件 如下

@Component({
  selector: 'base-strategy',
  templateUrl: './base.component.html',
  styleUrls: ['./base.component.css']
})
export class BaseStrategy {
}


@Component({
  selector: 'ui-type-one-strategy',
  templateUrl: './UiTypeOne.component.html',
  styleUrls: ['./ui-type-one.component.css']
})
export class UiTypeOneStrategy extends BaseStrategy {

}

@Component({
  selector: 'ui-type-two-strategy',
  templateUrl: './UiTypeTwo.component.html',
  styleUrls: ['./ui-type-two.component.css']
})
export class UiTypeTwoStrategy extends BaseStrategy {

}

HTML 會是這樣的。

<!-- If response received is ui-type-one this should show UI of ui-type-one-strategy. 
If response received is  ui-type-two this should show UI of ui-type-two-strategy. and so on.
-->
<base-strategy></base-strategy>

我知道 angular 中的 ng-template 但我想用作最后一個選項,我是 angular 的新手,因此想知道是否有任何這樣的方法來定義基於響應的 UI 策略。

您可以使用動態組件加載器動態創建組件。

Angular 提供了ComponentFactoryResolver可以與ViewContainerRef一起使用來動態加載組件。

在您的情況下,可能基於響應,您可以動態加載組件。

代碼一瞥:

async load(comp: string) {
    let component: Type<any>;
    switch (comp) {
      case 'A': {
        component = (await import('./comp-a/comp-a.module')).default;
        break;
      }
      case 'B': {
        component = (await import('./comp-b/comp-b.module')).default;
        break;
      }
    }
    const factory = this.cfr.resolveComponentFactory(component);
    this.container?.clear();
    this.container.createComponent(factory);
}

演示: https://stackblitz.com/edit/angular-ivy-n2zrqt?file=src%2Fapp%2Fapp.component.ts

文檔: https://angular.io/guide/dynamic-component-loader#loading-components

在 Angular v13 中,無需ComponentFactoryResolver即可創建組件。 在此處查看博客: https://blog.angular.io/angular-v13-is-now-available-cce66f7bc296

暫無
暫無

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

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