R
R
rinatoptimus2017-08-18 10:51:20
Angular
rinatoptimus, 2017-08-18 10:51:20

Why doesn't ngModel work outside of the ngFor loop?

Angular 2.
The idea in this example is this: all tasks are initially visible. By clicking the checkbox, you can display either Day only or Night only. This is the expected result.
Until you reach the expected result, you must first remove the checkbox from the loop so that it is not inside the ngFor block.
This option (when the checkbox is inside ngFor) works:

<div  *ngFor="let task of tasks">
      <div class="col-md-3">
        <label class="btn-custom">
          <input type="checkbox" autocomplete="off" 
               [(ngModel)]="task.taskType" (ngModelChange)="onModelChange(task);">
        </label>
        <p>{{task.val}}</p>
      </div>
    </div>

But there isn't one:
<label class="btn-custom">
    <input type="checkbox" autocomplete="off" [(ngModel)]="task.taskType" (ngModelChange)="onModelChange(task);">
</label>

<div  *ngFor="let task of tasks">
      <div class="col-md-3">
        <p>{{task.val}}</p>
      </div>
</div>

Here is the whole file:
@Component({
  selector: 'my-app',
  template: `
    <div  *ngFor="let task of tasks">
      <div class="col-md-3">
        <label class="btn-custom">
          <input type="checkbox" autocomplete="off" 
               [(ngModel)]="task.taskType" (ngModelChange)="onModelChange(task);">
        </label>
        <p>{{task.val}}</p>
      </div>
    </div>

    <div>selected: {{getCheckedValues() | json}}</div>
  `,
})
export class App {
  
  tasks = [
    {chkBoxImageUrl: "http://placehold.it/160x100",id: "item-1",val: "1", taskType: true},
    {chkBoxImageUrl: "http://placehold.it/160x100", id: "item-2", val: "2", taskType: false},
    {chkBoxImageUrl: "http://placehold.it/160x100", id: "item-3", val: "3", taskType: true},
    {chkBoxImageUrl: "http://placehold.it/160x100", id: "item-4", val: "4", taskType: false}
  ];

  getCheckedValues() {
    //return this.tasks.filter(obj => obj.checked).map(obj => obj.val);
    //return this.tasks.filter(obj => obj).map(obj => obj.val);
    return this.tasks.filter(obj => obj.taskType).map(obj => obj.val);
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Plunkr .

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Manakov, 2017-08-18
@gogolor

Because your task is available only inside the email with ngFor

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question