Angular checked function is ignored because of ngModel

50 Views Asked by At

I’m new to Angular.

I’m trying to create a checkbox table which compared with another table and will checked it if it existed.

This function works great, but when I'm adding ngModel - in order to save the changes, the checked function somehow ignored when first loading the page:

<tbody>
  <tr *ngFor="let w of workout;let i = index">
    <td>
      <div class="col-md-6">
        <input
          type="checkbox"
          name="workout_{{i}}"
          [checked]="checkIfExisted(w)"
          [value]="w"
          [(ngModel)]="program.workouts[i]">
      </div>
    </td>

    <td>
      <div class="col-md-6">{{w.workoutName}}</div>
    </td>
  </tr>

My function:

checkIfExisted(w:WORKOUT) {
    if(!this.program.workouts || this.program.workouts.length == 0) {
        console.log('no workouts found');
        return false;
    }

    this.arr = this.program.workouts.map(workout => workout.workoutId);

    if(this.arr.includes(w.workoutId)) {
        console.log('return true');
        return true;
    }

Program object:

import { WORKOUT } from './workout.model';
export class PROGRAM {
  programId:number = 0;
  programName:string = '';
  programTarget:string = '';
  programNote:string = '';
  numOfExercises:number;
  workouts: WORKOUT[];
}

Another issue is that when I’m saving, in the ngFrom, it saves it like this:

Web screen

{programName: "a", programTarget: "", programNote: "", numOfExercises: 1, workout_0: false, …}
numOfExercises:1
programName:"a"
programNote:""
programTarget:""
workout_0:false
workout_1:true

Instead of saving the whole object is saves: workout_0:false, workout_1:true

1

There are 1 best solutions below

1
user2852260 On

It might be your business logic file can't get loaded at the time of DOM rendering. Try using a self-invoking function with the appropriate data on load.