首页 > 解决方案 > Angular 7 & Typescript - 如何检查是否选中了动态必需复选框以禁用按钮

问题描述

如果所需的复选框为真,我想启用该按钮。我有一个 file.reducer.ts 文件,它具有按钮和复选框属性,file.component.html 循环通过复选框和按钮,以及 file.component.ts 我想检查是否选中了所需的复选框,然后启用按钮。这是我不确定如何检查正确的复选框并禁用按钮(event.target == requiredCheckbox)的地方。

文件.component.html:

      <div *ngFor="let checkbox of checkboxes">

    <label class="cui-overlay__checkbox-container">
      {{checkbox.content}}
      {{checkbox.required ? '(Required)' : '(Optional)'}}

      <input type="checkbox" (change)="isChecked($event)">

      <span class="cui-overlay__checkbox-check"></span>

    </label>

  </div>

  <ul
    [attr.data-stack]="stack"
    class="cui-overlay__buttons">

    <li
      *ngFor="let button of buttons"
      class="cui-overlay__button">

      <cui-button
        (buttonPress)="onPress($event)"
        [state]="button"
        [disabled]="button.disabled">
      </cui-button>

    </li>

  </ul>

文件.component.ts:

  get buttons() {
    return this.state.buttons
  }

  get checkboxes() {
    return this.state.checkboxes
  }

  get contents() {
    return this.state.contents
  }

  get stack() {
    return this.state.stack
  }

  get title() {
    return this.state.title
  }

  get visible() {
    return this.state.visible
  }

  onPress(button) {
    console.log(button.value)
  }

  isChecked(event) {
    var requiredCheckbox = this.state.checkboxes.find(checkbox => checkbox.required === true);
    console.log(requiredCheckbox);
    for (let button of this.state.buttons) {
      if (button.value === "Submit Application" && event.target == requiredCheckbox) {
        button.disabled = false;
      }
    }
  }

文件.reducer.ts:

    buttons: [
        {
          circle: false,
          icon: null,
          iconColor: 'primary-dark',
          shadow: true,
          text: 'Disabled Button Enabled once Required is checked',
          type: ButtonType.PRIMARY,
          value: 'Submit Application',
          disabled: true
        },
        {
          circle: false,
          icon: null,
          iconColor: 'primary-dark',
          shadow: true,
          text: 'Cancel',
          type: ButtonType.SECONDARY,
          value: 'Review Application',
          disabled: false
        }
      ],
      checkboxes: [
        {
          content: 'This checkbox is not required',
          required: false
        },
        {
          content: 'This is the required checkbox.',
          required: true
        }
      ],

<!-- end snippet -->

谢谢!

标签: angulartypescript

解决方案


在 HTML 文件中写入:

<mat-checkbox class="small-text" (change)="onChkChange($event)" [(indeterminate)]="isIndeterminate" color="warn"> {{item}} </mat-checkbox>

和 TS 文件:

isIndeterminate = false;


onChkChange() {
    console.log('Checked value changed.');
    if(!this.isIndeterminate){
      console.log('Hi');
    }
  }

每次选中复选框时,控制台上都会打印“已更改检查值”,并且 inDeterminate 值更改为 !indeterminate,


推荐阅读