代码之家  ›  专栏  ›  技术社区  ›  Vingtoft

角度编程设置元素属性

  •  -1
  • Vingtoft  · 技术社区  · 6 年前

    我正在利用角材料创建一个很棒的Web应用程序。 请考虑以下代码:

    <mat-checkbox class="master" (click)='checkAll()'>Checkbox MASTER</mat-checkbox>
    <mat-checkbox class="checkbox">Checkbox 2</mat-checkbox>
    <mat-checkbox class="checkbox">Checkbox 3</mat-checkbox>
    

    代码产生三个复选框。 选中第一个复选框时,还应选中其他两个复选框。如果未选中第一个复选框,则其他两个复选框应正常工作。

    组件中:

    checkAll() {
      // How can I programmatically set the [checked] property here for .checkbox?
    }
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   Andrei Tătar    6 年前

    这里有一个简单的解决方案,可以勾选任何数量的复选框。 如果手动选中所有复选框,它还将更新主复选框:

    组件类

    get master() {
      return this.checkboxes.every(c => c.checked);
    }
    set master(v) {
      this.checkboxes.forEach(c => c.checked = v);
    }
    checkboxes = new Array(5).fill(0).map(v => ({checked: false}));
    

    组件模板

    <label>
      <input type="checkbox" #masterCheckbox [checked]="master" 
      (change)="master=masterCheckbox.checked">
      Check/Uncheck ALL
    </label>
    
    <ng-container *ngFor="let chk of checkboxes; let index=index">
      <br>
      <label>
        <input type="checkbox" [checked]="chk.checked" (change)="chk.checked=!chk.checked">
        Checkbox {{index}}
      </label>
    </ng-container>
    

    https://stackblitz.com/edit/checkbox-behavior?file=src%2Fapp%2Fapp.component.html

        2
  •  1
  •   shildmaiden    6 年前

    将[checked]属性添加到第二个和第三个mat复选框:

    <mat-checkbox class="master" (click)='checkAll()'>Checkbox MASTER</mat-checkbox>
    <mat-checkbox class="checkbox" [checked]="checkedWhenFirstIsChecked">Checkbox 2</mat-checkbox>
    <mat-checkbox class="checkbox" [checked]="checkedWhenFirstIsChecked">Checkbox 3</mat-checkbox>
    

    在组件中用false初始化“checkedwherstisschecked”。

    并在函数中将其设置为true:

    checkedWhenFirstIsChecked: boolean = false;
    
    checkAll() {
      this.checkedWhenFirstIsChecked = true;
    }
    

    使用“checked”周围的[],已经创建了单向绑定,您只需设置该值即可。

        3
  •  1
  •   Vega Stipe    6 年前

    下面是一个例子:

    HTML

    <mat-checkbox class="master" (click)='checkAll()'>Checkbox MASTER</mat-checkbox>
    <mat-checkbox [checked]="property1" class="checkbox">Checkbox 2</mat-checkbox>
    <mat-checkbox [checked]="property2" class="checkbox">Checkbox 3</mat-checkbox>
    

    班级:

      //setting to different properties gives you the choice to check them individually
      property1;
      property2;
    
      checkAll() { 
         // this supposes that you want to uncheck in group also, if not set them just to 'true'
         this.property1 = !this.property1; 
         this.property2 = !this.property2;
      }
    

    Demo

    推荐文章