【问题标题】:How to add undefined value in angular select option如何在角度选择选项中添加未定义的值
【发布时间】:2018-10-12 19:51:04
【问题描述】:

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

我在我的 Angular 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 中未定义和禁用

【问题讨论】:

  • 不要使用[ngValue] 尝试仅使用value
  • 你有我的问题的答案吗。
  • 你的意思是用户不应该选择选项1?它必须被禁用。
  • 在选项一中,当我循环加载年份时,无论我显示什么,我都需要禁用。我需要设置条件 if value = cagr then [ngValue]="undefined" disabled 这是我想要实现的目标。

标签: angular select


【解决方案1】:

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

<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>

这里有一个Sample StackBlitz 供您参考。

【讨论】:

  • 我们可以在循环中使用条件,例如,如果值为 cagr,则执行此操作,否则使用该值。这解决了我的问题
  • 很高兴我能帮上忙 :)
猜你喜欢
  • 2012-10-19
  • 2020-12-25
  • 1970-01-01
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-23
相关资源
最近更新 更多