Angular 8 : 为 select 标签设置默认 selected 值

Angular 8 : Set default selected value for select tag

我想为 select 标签设置默认选项值,这些值在我的组件中声明为 table 并使用 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);

您可以通过以下方式进行:

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>

我创建了Stackblitz

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

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