【问题标题】:Angular 8 : Set default selected value for select tagAngular 8:为选择标签设置默认选择值
【发布时间】:2020-03-13 14:28:27
【问题描述】:

我想为选择标签设置一个默认选项值,这些值在我的组件中声明为表格并使用 ngFor 指令显示:

<form>
    <div class="form-group col-4">
      <span class="badge badge-theme mb-3">Quantité</span>
      <select class="form-control" id="exampleFormControlSelect1">
        <option *ngFor="let quantity of Quantities" [ngValue]="quantity">{{quantity}}</option>
      </select>
    </div>
    <div class="form-group col-4">
      <span class="badge badge-theme mb-3">Message personnalisé</span>
      <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
    </div>
  </form>

components.ts

  Quantities = Array(50).fill(0).map((x,i)=>i);

【问题讨论】:

  • 您的选择正在填充值,您无法设置默认值,对吗?
  • 是的,就是这样@PareshLomate

标签: html angular select option ngfor


【解决方案1】:

我创建了Stackblitz

我所做的是在组件中创建了一个变量,然后将其与 select 标签绑定。 [(ngModel)]="selectedValue"

然后可以根据您的逻辑使用该变量。

【讨论】:

    【解决方案2】:

    你可以这样做:

    component.html

     <select [(ngModel)]="seletedValue" class="form-control" id="exampleFormControlSelect1">
            <option *ngFor="let quantity of Quantities" [ngValue]="quantity">{{quantity}}</option>
     </select>
    

    component.ts

    seletedValue = ''; // set some default value from Quantities
    

    component.html
    
     <select [(ngModel)]="seletedValue" class="form-control" id="exampleFormControlSelect1">
            <option value="" [disabled]="true">Select quantity</option>
            <option *ngFor="let quantity of Quantities" [ngValue]="quantity">{{quantity}}</option>
     </select>
    

    【讨论】:

      猜你喜欢
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多