我的模型基本上是对象列表,并且每个对象都包含一个布尔值。这些布尔值必须由用户更新,因此我编写了一个为每个对象创建复选框的组件,然后将此复选框与其背后的模型绑定。
但是,这是行不通的!如果我检查一个复选框,则该模型似乎根本根本不会更新。
为了说明我的问题,我创建了一个最小的工作示例:
import {Component, Input, OnInit} from '@angular/core';
@Component({
selector: 'component-test',
template: `
<div *ngIf="!!data">
<div *ngFor="let item of data">
<ion-checkbox ([ngModel])="item.checked"></ion-checkbox>
</div>
</div>
<ion-button (click)="console_log()">print output</ion-button>
`
})
export class TestComponent {
@Input() data: any;
console_log() {
console.log(this.data);
}
}
@Component({
selector: 'page-test',
template: `
<ion-header>
<ion-toolbar color="primary">
<ion-title>
Test
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<component-test [data]="params.data | async"></component-test>
</ion-content>
`
})
export class TestPage implements OnInit {
params: any = {};
async get_data() {
return [{checked: false}, {checked: false}, {checked: false}];
}
ngOnInit() {
this.params['data'] = this.get_data();
}
}
您可以看到:
- 数据在父组件(页检验) 中异步加载
- 数据将传递给testocomponent(包含复选框)(组件测试)
- 我添加了一个按钮,该按钮在控制台中输出数据以验证模型的当前状态。
预期行为:
- 当我切换复选框时,模型中的布尔值应反映复选框的状态,反之亦然
观察到的行为:
- 当我切换复选框并将模型输出到控制台时,我完全没有更改。
您的代码是正确的,但是您犯了一点错误... NGMODEL应该写为 [(ngmodel)] note])著名线:香蕉中的香蕉在香蕉中。:)
,代码将是:
<div *ngIf="!!data">
<div *ngFor="let item of data">
<ion-checkbox [(ngModel)]="item.checked"></ion-checkbox>
</div>
</div>
ngModel
语法是错误的
<div *ngIf="!!data">
<div *ngFor="let item of data">
<ion-checkbox [(ngModel)]="item.checked"></ion-checkbox>
</div>
</div>
您编写了ngModel
错误。正确的两种方式绑定语法的方式为
[(attribute or prop)]
代码:
<ion-checkbox [(ngModel)]="item.checked"></ion-checkbox>
最终对我有用(所有其他答案也有效)是为了确保formsModule在模块中导入。
如果组件加载了懒惰,则没有提供错误消息,而是"懒惰模块"。仍然需要它。
bootstrap Angular示例:
<div class="form-check">
<label class="form-check-label">
<input
class="form-check-input"
type="checkbox"
(change)="form.checkbox = !form.checkbox";
changed[exchangeId] = true"
[checked]="form.checkbox"
/>
<span class="form-check-sign"> </span> Agree
</label>
</div>