[英]Is there any way to do stratergic loading of component at runtime in Angular?
{
"uiSetting" : "ui-type-one"
}
@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.