角度复选框,应始终保持选中状态

时间:2019-04-25 07:51:20

标签: angular typescript

就我而言,我有2个复选框 Active和InActive,默认情况下,在加载页面时,两者都将设置为true,用户可以取消选中它们中的任何一个,但是不能同时取消选中它们。

我试图做的是在值更新时使用getter获取值和方法调用,并检查更改是否为“有效”

.ts代码

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-actions-filter',
  templateUrl: './actions-filter.component.html',
  styleUrls: ['./actions-filter.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})

export class ActionsFilterComponent implements OnInit {
  private _isActive: boolean = true;
  get isActive(): boolean {
    return this._isActive;
  }

  setActive(value: boolean) {
    if (this._isInActive === false && value === false) {
      this._isActive = true;
      return;
    }
    this._isActive = value;
  }`

  private _isInActive: boolean = true;
  get isInActive(): boolean {
    return this._isInActive;
  }

  setInActive(value: boolean) {
    if (this._isActive === false && value === false) {
      this._isInActive = true;
      return;
    }
    this._isInActive = value;
  }

  constructor() { }`

  ngOnInit() {
  }
}

和我的.html

<div class="app-filter-block">
  <div class="btn-group">
    <div class="checkbox btn">
      <input type="checkbox" id="btn-action-active" (change)='setActive($event.target.checked)' [checked]="isActive" />
      <label for="btn-action-active">Active</label>
    </div>
    <div class="checkbox btn">
      <input type="checkbox" id="btn-action-inactive" (change)='setInActive($event.target.checked)'
        [checked]='isInActive' />
      <label for="btn-action-inactive">Inactive</label>
    </div>
  </div>
</div>

更新:为了清楚起见,正在使用复选框 https://clarity.design/documentation/button-group

1 个答案:

答案 0 :(得分:0)

如果未选中另一个复选框,您也可以简单地禁用它。

<div class="app-filter-block">
  <div class="btn-group">
    <div class="checkbox btn">
      <input type="checkbox" id="btn-action-active" 
      (change)='setActive($event.target.checked)' 
      [disabled]="!isInActive"
      [checked]="isActive" />
      <label for="btn-action-active">Active</label>
    </div>
    <div class="checkbox btn">
      <input type="checkbox" id="btn-action-inactive" 
      (change)='setInActive($event.target.checked)'
      [disabled]="!isActive"
      [checked]='isInActive' />
      <label for="btn-action-inactive">Inactive</label>
    </div>
  </div>
</div>