Home > Back-end >  Creating multiple Angular components dynamically
Creating multiple Angular components dynamically

Time:01-26

I have an array of data objects:

const arr = [
   {type: 'CustomA', id: 1, label: 'foo'},
   {type: 'CustomB', src: './images/some.jpg'}
   {type: 'CustomX', firstName: 'Bob', secondName:'Smith'}
]

These objects will always have a type but the rest of the properties on each will be specific to that type.
I have a component set up that can accept and display each of the possible data objects, doing whatever parsing and internal logic is required.
I want to look through that list, check the type of each object that I find and add the relevant component to the page. So, if I find type: 'CustomA I can add a CustomADisplay component to the page and pass it the data object to work with.

How best to achieve this when I don't know in advance how many items will be in that list or what their types will be?
Basically, who can I dynamically create and add components to page while the app is running.
I am currently playing around with ViewContainerRef as per the docs but this seems to require a target element in the template and until I get my data I'm not going to know how many of these are needed.

Hope that makes sense. Any advice very gratefully received.

CodePudding user response:

I guess that you are thinking off in something like this:

HTML for your array

arr = [
      {type: 'CustomA', id: 1, label: 'foo'},
      {type: 'CustomB', src: './images/some.jpg'}
      {type: 'CustomX', firstName: 'Bob', secondName:'Smith'}
];

 <ng-container *ngFor="let item of arr" [ngSwitch]="item.type">

    <ng-container *ngSwitchCase="CustomA">
       <app-custom-a-display [data]="item"><app-custom-a-display>
    </ng-container>

    <ng-container *ngSwitchCase="CustomB">
       <app-custom-b-display [data]="item"><app-custom-b-display>
    </ng-container>

    <ng-container *ngSwitchDefault>
       <app-custom-x-display [data]="item"><app-custom-x-display>
    </ng-container>

  </ng-container>

TS example for your CustomADisplay:

...
@Component({
  selector: 'app-custom-a-display',
  templateUrl: './custom-a-display.component.html',
  styleUrls: ['./custom-a-display.component.scss'],
})
export class CustomADisplayComponent {
private _localData;
@Input()
get data() {
   return _localData;
}
set data(data) {
    this._localData= data;   
}

constructor() {
// you will have your {type: 'CustomA', id: 1, label: 'foo'}
// accesible in 'data' variable
}

   
}
  •  Tags:  
  • Related