我有很多设备。我想使用ui-switch显示每个设备的警报状态。假设所有设备数据都像
alldevicedata=[{"id": 23, "alertonoff": "1"},
{"id": 34, "alertonoff": "0"},
{"id": 35, "alertonoff": "1"},
{"id": 36, "alertonoff": "0"} ]
HTML就像
<div *ngFor="let item of alldevicedata" class="form-group">
Alert
<span class="floatright">
<ui-switch id="alertonoff" name="alertonoff" size="small"
[(ngModel)]="toggleValue" (ngModelChange)="item.alertonoff=toggleValue ?'1':'0'"
color="#1abc9c"></ui-switch>
</span>
</div>
如果我拨动开关,则该垂直项的alertonoff值会正确更改。意味着如果我更改第二个数字的开关,则第二个项的值只会更改。
但是一次所有开关都会更改状态。意味着如果将第二个数字开关拨到ON位置,那么所有其他数字也都将打开。
我想显示每个警报的状态,如果alldevicedata.alertonoff = 1,则ui开关打开,否则关闭。 Stackblitz: https://stackblitz.com/edit/angular-zg21jt?embed=1&file=src/app/app.module.ts 预先感谢。
答案 0 :(得分:2)
之所以会这样,是因为所有开关都绑定到相同的值。尝试像这样更改ngModel:
<ui-switch id="alertonoff" name="alertonoff" size="small" [(ngModel)]="item.checked" (ngModelChange)="onModelChanged(item)" color="#1abc9c"></ui-switch>
,并在组件类中:
allDeviceData = [
{ 'id': 23, 'alertonoff': '1', 'checked': true },
{ 'id': 34, 'alertonoff': '0', 'checked': false },
{ 'id': 35, 'alertonoff': '1', 'checked': true },
{ 'id': 36, 'alertonoff': '0', 'checked': false }
];
onModelChanged(item) {
item.alertonoff = item.checked ? '1' : '0';
console.log(item.id, item.alertonoff);
}
答案 1 :(得分:1)
您的代码正确,只是您缺少对象属性名称。 由于您要遍历所有项目,并且每个项目的开关都绑定有相同的值 因此,请用您的代码替换此代码。
注意这一行:[(ngModel)] =“ toggleValue”到---> [(ngModel)] =“ item.alertonoff”
<div *ngFor="let item of alldevicedata" class="form-group">
Alert
<span class="floatright">
<ui-switch id="alertonoff" name="alertonoff" size="small" [(ngModel)]="item.alertonoff" (ngModelChange)="item.alertonoff=toggleValue ?'1':'0'" color="#1abc9c"></ui-switch>
答案 2 :(得分:0)
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div *ngFor="let item of alldevicedata" class="form-group">
Alert{{item.alertonoff}}
<span class="floatright">
<ui-switch id="alertonoff" name="alertonoff" size="small"[(ngModel)]="item.alertonoff" color="#1abc9c"></ui-switch>
</span>
</div>