繁体   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