Reorder child components in angular 2 when rendering on the fly

I'm a little new to the angular 2 world, so please excuse me if this is a naive question.

I want to read a json file containing meta for various components that I need to display for the page.

I need to read this json and display the child components in the order in which they are listed here.

I have successfully used the dynamic component loader API, which angular 2 provides for dynamic loading of child components inside a for loop. However, there are other requirements that make using this API a bit complicated.

So I'm looking for another way to do the same. It will be like manipulating the DOM from the ts file of the parent component to get the child components in the same order as in JSON.

Any conclusions would be very helpful. Many thanks!

PS: sorry you did not publish the code. I wrote this using a mobile phone.

+4
source share
1 answer

If you do not want to use DynamicComponentLoader(deprecated in favor ViewContainerRef.createComponent()with the same restrictions), I see only the possibility of using an element that wraps all possible components and displays only the one that is selected

@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;
}

and use it like

@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
}
+1
source

All Articles