带有ngModel的动态角度复选框 [英] angular mat-checkbox dynamically with ngModel
问题描述
我有一个要约类,它具有一个属性单位"作为对象数组.
I have a class Offer which have one property "units" as array of objects.
export class Offer {
public propertyA: string;
public propertyB: string;
public units: Unit[];
}
export class Unit {
public code: string,
public name: string,
public checked: boolean
}
我正在使用Angular2,这些单位必须是用户可以选择的复选框. 我也在用角形材料.
I am using Angular2, these units must be checkboxes the user can select. Also I am using angular material.
html代码如下:
<div *ngFor="let unit of model.units; let i=index">
<mat-checkbox [(ngModel)]="model.units[i].checked"
id="units[{{i}}]" name="units[{{i}}]">
{{ unit.name }}
</mat-checkbox>
</div>
units属性使用以下方式加载:
The units property is loaded using:
this.model.units.push(new Unit("code1","name1", false));
this.model.units.push(new Unit("code2","name2", false));
this.model.units.push(new Unit("code3","name3", false));
我发送表单时,选中的属性不包含选中的值.
When I send the form the checked property does not contains the checked value.
我在做什么错??
推荐答案
添加[checked]="unit.checked"
并从mat-checkbox
中删除ngModel
,id
和name
.加载页面时,这会执行一种单向绑定,但是要使两种方式绑定工作,您需要做类似的事情,就像我在我的项目中所做的那样:
Add [checked]="unit.checked"
and remove ngModel
, id
and name
from your mat-checkbox
. This does one way binding when you load the page but to make the two way binding work you need to do something similar like this which i have done in my project:
在更改时通过$event
并手动在组件文件中设置值:
Pass the $event
on change and set the value in the component file manually:
将HTML更改为:
<div *ngFor="let unit of model.units">
<mat-checkbox [checked]="unit.checked"
(change)="valueChange(model.units,unit,$event)">
{{ unit.name }}
</mat-checkbox>
</div>
将此添加到组件文件:
valueChange(model.units, unit, $event) {
//set the two-way binding here for the specific unit with the event
model.units[unit].checked = $event.checked;
}
编辑/更新:最近找到了一种无需明确处理的双向绑定解决方案
EDIT/UPDATE: Found a solution recently for two way binding without handling it explicitly
确保model.units
具有checked
的属性.这是添加它的最简单方法:
Make sure model.units
have a property for checked
. This is the easiest way to add it:
component.ts:
component.ts:
this.model.units.forEach(item => {
item.checked = false; //change as per your requirement
});
html:
<div *ngFor="let unit of model.units;let i=index">
<mat-checkbox [(ngModel)]="unit.checked" [checked]="unit.checked"
name="{{i}}-name"> //make sure name is unique for every item
</mat-checkbox>
</div>
如果您还想控制启用/禁用选项,请尝试添加以下内容:
If you want to control the enable/disable options as well try adding this:
component.ts:
component.ts:
this.model.units.forEach(item => {
item.checked = false;//change as per your requirement
item.disabled = true;//change as per your requirement
});
html:
<div *ngFor="let unit of model.units;leti=index">
<mat-checkbox [(ngModel)]="unit.checked" [checked]="unit.checked"
[disabled]="unit.disabled"
name="{{i}}-name">//make sure name is unique for every item
</mat-checkbox>
</div>
这篇关于带有ngModel的动态角度复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!