Home > Enterprise >  How to handle ngModel for multiple p-dropdowns in a ngfor Loop
How to handle ngModel for multiple p-dropdowns in a ngfor Loop

Time:11-17

I'm using Angular 14 for the first time. I've to show dynamic numbers of dropdowns in my child component. Actually Parent component will decide how many dropdowns will be there on child component. Parent is sending some data on the basis of that data, child component will render dropdowns. But nothing is displayed on the screen and there is an error in console which says ERROR TypeError: ctx_r0.bindedData is undefined. Here is the code:

parent.ts

this.colors = [
  { name: 'Black', code: 'BLK' },
  { name: 'Red', code: 'RED' },
  { name: 'Green', code: 'GRN' }
];

this.cars= [
  { id: 1, name: 'Hyundai' },
  { id: 2, name: 'Toyota' },
  { id: 3, name: 'Mercedes' },
];

this.engine= [
  { id: 1, name: 'Petrol' },
  { id: 2, name: 'Diesel' },
  { id: 3, name: 'Electronic' },
];


this.data = [this.colors, this,cars, this.engine] // this array is sent to child compoennt

parent.component.html

<app-child
    [data]="data">
</app-child>

child.component.ts

@Input() data: any[];

child.component.html

<span  *ngFor="let i of data" >
  <p-dropdown [options]="i" optionLabel="name" [(ngModel)]="bindedData[i]" ></p-dropdown>
</span>

child.component.ts

bindedData: any[];

Please correct my mistake.

CodePudding user response:

Just few corrections, maybe it will fix it.

First we can initialize the array to have initial values, based on the size of the array of data.

bindedData: any[] = [null, null, null];

Then we just need to set the ngModel to access the index of the list (let i = index) of the binded data, currently we are using the actual element of the array, which might be the cause of the issue!

<span  *ngFor="let list of data; let i = index" >
    <p-dropdown [options]="list" optionLabel="name" 
    [(ngModel)]="bindedData[i]" ></p-dropdown>
</span>
  • Related