Lopes
Lopes

Reputation: 363

Angular NgFor loop 2 arrays of objects

I want to loop through two different arrays with ngFor and display them in html.

 <div class="form-check ml-5" *ngFor="let item of competencias.competencias; let i = index">
    <input class="form-check-input" type="checkbox" [value]="item.id [(ngModel)]="arrayCompetencias[i].checked"> 
    <label class="form-check-label">
       <strong> {{ item.id }} </strong>  : {{ item.descripcion}}
    </label>
   </div>   

Those 2 arrays has the same length but I want to combine them as to show separate data. First array has a list of data just to display and is fine. Second array arrayCompetencias I want just to see if user check the checkbox or not and save it as ngModel.

When trying to get the parameter data in arrayCompetencias[i].checked it through me an error that the field is undefined, but I am initializing them before.

First Array

competencias = [{id: string, descripcion: string}]

Second Array

arrayCompetencias = [{checked: boolean, id: string}]
[(ngModel)]="arrayCompetencias[i].checked">  

How can i read only this field into the array and set according User checked or not

Upvotes: 0

Views: 1773

Answers (2)

Palash Kanti Bachar
Palash Kanti Bachar

Reputation: 616

Nothing I have changes only a problem in your data. You can check the code here

Upvotes: 0

Amr Saeed
Amr Saeed

Reputation: 305

I fixed some typos on your code and added some edits.

Try to use this example and it should work perfectly with you.

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  competencias = [{id: "1", description: "This is a description"}]
  arrayCompetencias = [{checked: true, id: "1"}]
}
<div *ngFor="let item of competencias; let i = index">
  <input type="checkbox" 
    [value]="item.id" 
    [checked]="arrayCompetencias[i].checked"
    (change)="arrayCompetencias[i].checked = !arrayCompetencias[i].checked">
  <label>
    <strong> {{ item.id }} </strong> : {{ item.description}}
  </label>
</div>

Upvotes: 0

Related Questions