动态渲染时更改 angular 2 中子组件的顺序

Change the order of the child components in angular 2 while rendering on the fly

我对 angular 2 世界有点陌生,所以如果这是一个幼稚的问题,请原谅。

我想读取一个 json 文件,其中包含我需要为页面显示的各种组件的元数据。

我需要阅读此 json 并按照此处列出的顺序呈现子组件。

我已经成功地使用 angular 2 提供的动态组件加载器 API 在 for 循环中动态加载子组件。但是,还有一些其他要求使得此 API 的使用有点复杂。

所以我正在寻找另一种方法来做同样的事情。这就像从父组件的 ts 文件中操作 DOM 以按照 JSON.

中提到的相同顺序获取子组件

任何线索都会非常有帮助。 非常感谢!

PS:很抱歉没有发布代码。我用我的手机发布了这个。

如果您不想使用 DynamicComponentLoader(不推荐使用 ViewContainerRef.createComponent(),但具有相同的限制)我只看到使用包含所有可能组件并仅呈现的元素的选项被选中的那个

@Component({
  selector: 'wrapper-component',
  directives: [Cmp1, Cmp2, Cmp3, ... Cmp10],
  template: `
    <div [ngSwitch]="type">
      <cmp1 *ngSwitchCase="'cmp1'"></cmp1>
      <cmp2 *ngSwitchCase="cmp2"></cmp2>
      <cmp3 *ngSwitchCase="cmp3"></cmp3>
      ....
      <cmp10 *ngSwitchCase="cmp4"></cmp4>
      <div *ngSwitchDefault>not supported</div>
    </div>
`})
export class WrapperComponent {
  @Input() type:string;
}

并像

一样使用它
@Component({
  selector: 'parent-cmp',
  template: `
    <wrapper-component *ngFor="let item of someJson" [type]="item.componentName"></wrapper-component>
  `})
export class ParentComponent {
  someJson; // assign the JSON here
}