如何使用angular2获取选中和取消选中的值

时间:2019-01-03 11:08:14

标签: angular typescript

我有一个列表,这些列表取自API,并以HTML显示。 但是该列表已禁用,我无法检查和取消选中值。

我的要求:

1. I want `HasHomeDashboard`to be disabled and it must be active always.
2. I must be able to check and uncheck the checkboxes except `HasHomeDashboard`.
3. On click of `save Changes`, i want to get in console in this format 

TS:

saveSidebar() {
     let params = { UserId: 1209 }
    console.log(params,"params")
  }

我希望控制台参数像这样:,基于选中和取消选中值(分别为0和1)。

 {
                "Id": "1",
                "HasHomeDashboard": "1",
                "HasUserManagement": "1",
                "HasDicom": "1",
                "HasEMR": "1",
                "HasCaseManagement": "1",
                "HasSystemSettings": "0",
                "HasReport": "1",
                "UserId":"1209"
    }

Demo

2 个答案:

答案 0 :(得分:1)

如果您想在ts中这样做,可以这样做(有效)。

  selectedMenu(evt, item) {
    let keyTemp: string = item.key.toString();
    let valueTemp = item.value;
    this.userMenu[0][keyTemp] = this.boxChecked(item.value);
  }

  boxChecked(value: any) {
    if (value === 0) 
      return 1;
    else
      return 0;
  }

希望它可以帮助您, 再见

答案 1 :(得分:1)

我修改了一些代码,

HTML:

<div *ngFor="let item of objectToArray(menu)">
          <input
            type="checkbox" 
             [checked]="item.value" 
            (click)="selectedMenu($event.target.checked, item)"
            [disabled]="item.IsDisabled">
          <span class="nav-text p-l10">{{item.key}}</span>
</div>

TS:

objectToArray(object) {
    const keyValues = [];
    for(let key in object) {
      if(key !== 'Id') {
        const objectToPush = {
          key,
          value: (key == 'HasCaseManagement') ? 1 : object[key],
          IsDisabled: (key == 'HasCaseManagement')
        };
        keyValues.push(objectToPush);
      }
    }
    this.selectedMenuIds = keyValues;
    return keyValues;
  }

  selectedMenu(evt, item) {
    this.userMenu[0][item.key] = this.swapChecked(item.value);
    this.selectedMenuIds[0] = item.value;
  }

  saveSidebar() {
    let params = { Id: 1209, HasCaseManagement:"" }
    this.selectedMenuIds.push(params);
    console.log(this.selectedMenuIds)
  }

  swapChecked(value: any) {
    return (value === 0) ? 1 : 0
  }