[英]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.