简体   繁体   中英

Angular checked function is ignored because of ngModel

Im new to Angular.

Im 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>
 </tbody>

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 im 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

可能是因为在DOM渲染时无法加载您的业务逻辑文件,请尝试对加载的适当数据使用自调用功能。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM