【问题标题】:Checkbox not getting checked/unchecked as expected复选框未按预期选中/取消选中
【发布时间】:2021-06-11 18:23:07
【问题描述】:

我有一个复选框列表,如下所示:

<div class="col-md-4 md-padding-s"  *ngFor="let node of nodeList; let j=index;">
                  <md-checkbox-group>
                    <md-checkbox
                      class="md-h6 row md-padding--xs"
                      name="{{node.FQDN}}"
                      label="{{node.FQDN}}"
                      value="{{node.FQDN}}"
                      required="true"
                      htmlId="filter_label_{{a}}_{{j}}"
                      (ngModelChange)="updateSelection(node)"
                      [formControlName]="servers"
                      [(ngModel)]="node.selected">
                    </md-checkbox>
                  </md-checkbox-group>
                </div>

我的updateSelection 函数是.ts 文件是:

  updateSelection(node) {
         console.log('node', node)
        node.selected = node.selected ? false : true;
        if(node.selected) {
          this.serverList.push(node.FQDN);
          this.isServerSelected = true;
        }else{
          this.serverList.pop();
          this.serverList = this.serverList.filter((x, i, a) => a.indexOf(x) == i)
          if(this.serverList.length == 0) {
            this.isServerSelected = false;
            this.alertService.error('Error', 'Please select atleast 1 server', this.alertConfig);
          }
        }
    }

现在,必须根据node.selected 值选中或取消选中复选框。但是发生的事情是,当我单击复选框文本时,node.selected 值必须根据当前正在发生的updateSelection 函数进行更改。但是当我单击周围的文本时,该复选框没有被选中或取消选中。只有当我点击复选框时,该值才会被选中/取消选中。我哪里错了?

【问题讨论】:

    标签: angular checkbox


    【解决方案1】:

    您需要提供对节点对象的新引用,以使更改反映在 UI 中。

     updateSelection(node) {
             console.log('node', node)
            node.selected = node.selected ? false : true;
    // here add this 
    node = {...node}
            if(node.selected) {
              this.serverList.push(node.FQDN);
              this.isServerSelected = true;
            }else{
              this.serverList.pop();
              this.serverList = this.serverList.filter((x, i, a) => a.indexOf(x) == i)
              if(this.serverList.length == 0) {
                this.isServerSelected = false;
                this.alertService.error('Error', 'Please select atleast 1 server', this.alertConfig);
              }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 1970-01-01
      • 2012-02-18
      • 2010-11-03
      • 1970-01-01
      • 2019-08-30
      相关资源
      最近更新 更多