如何在Angular中下拉列表为空时禁用按钮?

时间:2018-03-27 17:51:44

标签: angular angular-forms

我想检查下拉列表是否为空。 如果不为空,请启用提交按钮。 如果为空,请禁用提交按钮。 以下是我的HTML

<form  [formGroup]="addTaskForm"  (ngSubmit)="submit()" >
<mat-form-field>
  <mat-select placeholder="Favorite animal" [formControl]="animalControl" required>
    <mat-option>--</mat-option>
    <mat-option *ngFor="let animal of animals" [value]="animal">
      {{animal.name}}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="animalControl.hasError('required')">Please choose an animal</mat-error>

</mat-form-field>
<mat-form-field>
  <mat-select placeholder="Favorite food" [formControl]="foodControl" required>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{ food.viewValue }}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="foodControl.hasError('required')">Please choose an food</mat-error>

</mat-form-field>

<div mat-dialog-actions>
    <button mat-button (click)="onNoClick()">Cancel</button>

<button type="submit"  mat-button cdkFocusInitial [disabled]="!formCtrl.form.valid">submit</button>
</div>
</form>

demo

帮帮我

1 个答案:

答案 0 :(得分:1)

请尝试下面的代码,

<form [formGroup]="addTaskForm"  (ngSubmit)="submit()" >
<mat-form-field>
  <mat-select placeholder="Favorite animal" [formControl]="animalControl" required>
    <mat-option>--</mat-option>
    <mat-option *ngFor="let animal of animals" [value]="animal">
      {{animal.name}}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="animalControl.hasError('required')">Please choose an animal</mat-error>

</mat-form-field>
<mat-form-field>
  <mat-select placeholder="Favorite food" [formControl]="foodControl" required>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{ food.viewValue }}
    </mat-option>
  </mat-select>
  <mat-error *ngIf="foodControl.hasError('required')">Please choose an food</mat-error>

</mat-form-field>

<div mat-dialog-actions>
    <button mat-button (click)="onNoClick()">Cancel</button>

<button type="submit"  mat-button cdkFocusInitial [disabled]="foodControl.hasError('required') || animalControl.hasError('required')">submit</button>
</div>
</form>