【问题标题】:Angular 4 -ngx-toggle-switch not working with ngforAngular 4 -ngx-toggle-switch 不适用于 ngfor
【发布时间】:2018-12-13 12:35:58
【问题描述】:

我有很多设备。我想使用 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 值会正确更改。意味着如果我更改第二个数字开关,那么第二个项目的值只会更改。

但一次所有的开关都会改变状态。意味着如果将第二个数字开关切换到打开,那么所有其他的也都像这样打开。

我想显示每个警报的状态,如果 alldevicedata.alertonoff=1,则 ui 开关打开,否则关闭。 堆栈闪电战: https://stackblitz.com/edit/angular-zg21jt?embed=1&file=src/app/app.module.ts 提前致谢。

【问题讨论】:

  • 你可以在stackbiz中添加你的代码,这样我们就可以帮助你错过@priya
  • 好吧。给我一些时间
  • 抱歉,您使用的是什么版本的 angular
  • 对不起。 "ngx-toggle-switch": "^2.0.5",
  • 我问的是角度版本

标签: angular typescript angular4-forms


【解决方案1】:

发生这种情况是因为所有开关都绑定到相同的值。尝试像这样更改 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);
}

【讨论】:

  • 我已添加属性 checked 以不修改 alertonoff 属性。您可以对alertonoff 属性进行直接绑定,但是,所有开关将在开始时打开,因为 ui-switch 需要 boolean 值,并且当您切换某些开关时,alertonoff 属性会被修改对或错。
【解决方案2】:

您的代码是正确的,只是您缺少对象属性名称。 由于您正在循环所有项目并且每个项目的开关都绑定了相同的值 所以用你的代码替换这个代码。

注意这一行:[(ngModel)]="toggleValue" to ---> [(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>

【讨论】:

    【解决方案3】:
    <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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-15
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 2018-07-21
      相关资源
      最近更新 更多