首页 > 解决方案 > 如何在角度选择选项中添加未定义的值

问题描述

我正在尝试在我的 Angular 添加一个禁用值select option。例如,我有一个下拉列表,其中我有一个值 2 作为一个选项,我只想显示该值并且不应该被接受。

我在我的角度 HTML 代码中这样做:

<select id="anything" class="selectpicker" class='select-option' required [(ngModel)]='data.years' name="years" (ngModelChange)="toYear(data.years)">
  <option [ngValue]="undefined" disabled selected> Year </option>
  <option class='option' *ngFor='let option of years' [ngValue]="option">{{option}}</option>
</select>

这是我的代码,您可以看到我正在使用此代码:

<option [ngValue]="undefined" disabled  selected>Year</option>

这是可见但不可选择的,我正在循环中加载值我正在使用此数据进行循环:

years = [
  "All",
  "2005-06",
  "2006-07",
  "2007-08",
  "2008-09",
  "2009-10",
  "2010-11",
  "2011-12",
  "2012-13",
  "2013-14",
  "2014-15",
  "CAGR",
];

我想CAGR在这个下拉列表中禁用它,因为它在 Year 中未定义和禁用

标签: angularselect

解决方案


[disabled]="option === 'CAGR'"option你循环中使用怎么样:

<select 
  id = "anything" 
  class="selectpicker" 
  class='select-option' 
  required 
  [(ngModel)]='data.years' 
  name="years" 
  (ngModelChange)="toYear(data.years)">
    <option 
      [ngValue]="undefined" 
      disabled  
      selected>
      Year
    </option>
    <option 
      class='option' 
      *ngFor='let option of years'
      [disabled]="option === 'CAGR'"
      [ngValue]="option">
      {{option}}
    </option>
</select>

这是您参考的示例 StackBlitz


推荐阅读