【问题标题】:How to Disable button when dropdown is empty in Angular?当Angular中的下拉列表为空时如何禁用按钮?
【发布时间】:2018-03-27 17:51:44
【问题描述】:

我想检查下拉菜单是否为空。 如果不为空,请启用提交按钮。 如果为空,则禁用提交按钮。 下面是我的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

帮帮我

【问题讨论】:

  • 您的演示中有多个控制台错误,如果您更正这些错误,您可能会找到解决方案。
  • 我在控制台中没有收到任何错误
  • 如果您的代码与您发布的演示相匹配,您绝对应该这样做。如果不是,那么您可能应该在寻求进一步帮助之前考虑修复演示。
  • 你能帮我吗@Claies
  • 我已经更新了我的答案,它正在工作,请尝试一下

标签: angular angular-forms


【解决方案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>

【讨论】:

猜你喜欢
  • 2018-02-27
  • 2020-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
相关资源
最近更新 更多