Skip to content
Advertisement

How to traverse a typed array?

I have the following class model in my application Angular:

export class IItemsModel {
  public description: string;
  public itemDetail: IItemDetailModel;
  public itemCategories: IItemCategoriesModel[];  // array of IItemCategoriesModel
}

export class IItemCategoriesModel {
  public id: string | number;
  public description: string;
}

And my Controller:

itemModel: IItemsModel;
selectedCategories: any[] = [];

ngOnInit() {
  this.itemModel = new IItemsModel();
  this.itemModel.itemCategories = [];
}

onSubmit(form: NgForm) {
  // here I format the data
}

In the template I have a multiple select where I fill an array with the id’s of the chosen categories.

[25, 38]  // selectedCategories

Problem, I’m using ngModel to link the form with the controler, but to send the pre-filled data to the API, I have to format the id’s to the model format, that is:

{
  ...,
  itemDetail: 'something',
  itemCategories: [
    { id: any Id },
    { id: other Id }
  ]
}

I try to format the data as follows in the onSubmit() method:

for(let i=0; i<this.selectedCategories.length; i++) {
  this.itemModel.itemCategories[i].id = this.selectedCategories[i];
}

But I get the error:

TypeError: Cannot set property ‘id’ of undefined @ undefined:undefined

How could you be formatting the itemCategories to be able to send the data correctly to the API?

Advertisement

Answer

Use forEach to iterate instead of for loop.

this.selectedCategories.forEach(f => {
    this.itemModel.itemCategories.push({ id: f, description: '' })
});

Since your selectedCategories object is an array of numbers, it doesn’t have id property in it. That’s why you’re getting errors.

Working demo at StackBlitz.

Click the button and check the console log.

Advertisement