Answer the question
In order to leave comments, you need to log in
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>
<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>
@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 {}
Answer the question
In order to leave comments, you need to log in
Because your task is available only inside the email with ngFor
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question