即使选择了一个值,下拉菜单仍然被禁用

问题描述

有两个下拉按钮 d1 和 d2。 d2 被禁用。从“d1”中选择一个值后,“d2”仍处于禁用状态。

<div class="card-container">
        <label>Country</label>
        <select placeholder="Country" [(ngModel)]="selectedCountry" (change)="changeCountry($event)" >
            <option>--Choose Country--</option>
            <option *ngFor="let country of Countries" >{{country.name}}</option>
        </select>
    </div>

    <div class="card-container">
        <label>State</label>
        <select placeholder="State" (change)="changeState($event)"
      [disabled]="selectedCountry">
            <option>--Choose State--</option>
            <option *ngFor="let state of states">{{state.name}}</option>
        </select>
    </div>

使用 [disabled]="selectedCountry" d2 被禁用但如果 [disabled]="!selectedCountry" 则不会禁用 我只想在选择 d1 时才使 d2 可选。

解决方法

[disabled]="selectedCountry" 表示如果您对 selectedCountry 有一些值,它将是 true,这意味着它被禁用。所以条件应该是相反的

[disabled]="!selectedCountry"

如果 selectedCountry 没有任何值,将禁用它。

<div class="card-container">
  <label>Country</label>
  <select placeholder="Country" [(ngModel)]="selectedCountry" (change)="changeCountry($event)" >
    <option>--Choose Country--</option>
    <option *ngFor="let country of Countries" >{{country.name}}</option>
  </select>
</div>

<div class="card-container">
  <label>State</label>
  <select placeholder="State" (change)="changeState($event)" [disabled]="!selectedCountry">
    <option>--Choose State--</option>
    <option *ngFor="let state of states">{{state.name}}</option>
  </select>
</div>

还要确保 selectedCountry 的初始值为 selectedCountry = ''