【问题标题】:materialize css checkbox not working with model variable物化css复选框不适用于模型变量
【发布时间】:2020-08-12 06:28:02
【问题描述】:

这是html

<div class="checkbox checkbox-circle">
       <label>
        <input type="checkbox" [attr.checked]="isSelected ? true : null" class="filled-in"
          (change)="rowToggleSelection(row,$event,i)" />
        <span></span>
      </label>
</div>

有一个按钮可以将true/false 设置为isSelected,它可以正常工作,直到我通过单击复选框本身来更改复选框的值。单击复选框后,它会从按钮停止工作。

【问题讨论】:

  • 您应该对attr.checked 使用两种方式绑定,即[(attr.checked)]="isSelected",以确保在您手动检查时更改该值。另外我认为你不应该使用三元运算符将值赋值给isSelected,因为它已经是一个布尔值。
  • 有什么理由不使用[(ngModel)]?
  • @isAif,我正在使用这个循环,每个对象都有 isSelected,当我使用 ngModel 然后单击单个值时它选择了所有
  • @Eliseo 在循环中无法正常工作
  • @isAif 是的,我使用的是相同的,[(attr.checked)]="item.isSelected",这会显示默认选择的所有项目

标签: angular checkbox materialize


【解决方案1】:

使用 ngModel,看看你在 .ts 中不需要更多的东西

<form *ngFor="let item of items" class="checkbox checkbox-circle">
       <label>
        <input name="ck" type="checkbox" [(ngModel)]="item.isSelected"  class="filled-in"
           />
          <span>{{item.name}}</span>
      </label>
</form>
<pre>
{{items|json}}
</pre>

【讨论】:

    【解决方案2】:

    Materialize checkbox 使用 checked 而不是 attr.checked 将其标记为选中。

    打字稿文件

    // items to use as checkbox
    public items = [
        {
          name: "first",
          isSelected: false
        },
        {
          name: "second",
          isSelected: true
        }
      ];
    
    // toggle the checkbox
    toggleCheckbox(item) {
        item.isSelected=!item.isSelected;
    }
    

    模板文件

    <form *ngFor="let item of items" class="checkbox checkbox-circle">
           <label>
            <input type="checkbox" [checked]="item.isSelected" class="filled-in"
              (change)="toggleCheckbox(item)" />
              <span>{{item.name}}</span>
          </label>
    </form>
    

    【讨论】:

      【解决方案3】:

      没有什么对我有用,所以我使用材料图标来实现相同的效果

      <!-- checked -->
      <i class="material-icons label-icon active" *ngIf="isSelected">radio_button_checked</i>
      <!-- un-checked -->
      <i class="material-icons label-icon" *ngIf="!isSelected">radio_button_unchecked</i>
      

      还有一些CSS

      .label-icon {
          font-size: 15px;
          &.active {
              color: $color-active;
          }
      }
      

      这是完美的工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-20
        • 2014-09-13
        • 2018-12-31
        • 1970-01-01
        • 2017-12-08
        相关资源
        最近更新 更多