gpt4 book ai didi

angular mat-checkbox动态地使用ngModel

转载 作者:太空狗 更新时间:2023-10-29 17:08:50 26 4
gpt4 key购买 nike

我有一个 Offer 类,它有一个属性“units”作为对象数组。

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,这些单位必须是用户可以选择的复选框。我也在使用 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>

单位属性加载使用:

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));

当我发送表单时,选中的属性不包含选中的值。

我做错了什么??

最佳答案

添加 [checked]="unit.checked" 并删除 ngModelidname mat-checkbox。这会在您加载页面时进行单向绑定(bind),但要使双向绑定(bind)工作,您需要做类似我在我的项目中所做的事情:

传递 $event on change 并在组件文件中手动设置值:

将您的 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;
}

编辑/更新:最近找到了一种无需显式处理的双向绑定(bind)解决方案

确保 model.units 具有 checked 属性。这是添加它的最简单方法:

组件.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>

如果您还想控制启用/禁用选项,请尝试添加:

组件.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>

关于angular mat-checkbox动态地使用ngModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47384092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com