【问题标题】:Unable to set a option selected by default in angular 10无法设置在角度 10 中默认选择的选项
【发布时间】:2021-09-24 21:06:44
【问题描述】:

我已经尝试了所有可用的解决方案,但无法让这个简单的事情发挥作用。

这是我的 ts 文件。

options = [
    { value: '', label: 'Age group' },
    { value: '2-3', label: '2 to 3 years' },
    { value: '3-4', label: '3 to 4 years' },
    { value: '4-6', label: '4 to 6 years' },
    { value: '6-8', label: '6 to 8 years' },
    { value: '8-12', label: '8 to 12 years' },
  ];

  selectedValue: any = "6-8";

这是我的 HTML

<"form-inline waves-light ml-auto d-lg-none d-sm-flex" mdbWavesEffect>
   <div class="md-form my-0">
      <select class="browser-default custom-select" name="ageGroup" [(ngModel)]="selectedValue">
        <option value={{option.value}} *ngFor="let option of options">
            {{option.label}}
        </option>
      </select>
   </div>
</form>

这是输出预览。

无论我使用什么方法,这都是选择最后一个选项。

【问题讨论】:

标签: angular angular10


【解决方案1】:

试试这个代码,

<select id="duration" name="duration" [(ngModel)]="selectedValue">
  <option *ngFor="let duration of options" [ngValue]="duration.value"> 
        {{ duration.label }}
  </option>
</select>

STACKBLITZ DEMO

【讨论】:

【解决方案2】:

在 mat-option 中使用 [value]="option.id" 而不是 value="{{ option.id }}"

HTML:

  <mat-select [(ngModel)]="selectedValue">
    <mat-option *ngFor="let option of options" [value]="option.id">{{ option.name }} 
    </mat-option>
  </mat-select>

Ts:

 selectedValue = this.options[4].id;

【讨论】:

    【解决方案3】:

    HTML:

      <select id="duration" name="duration" [(ngModel)]="selectedValue">
    
         <option *ngFor="let duration of options" [ngValue]="duration.value"> 
            {{ duration.label }}
            </option>
    
     </select>
    

    TypeScript 代码:

    this.selectedValue = this.options[4].id;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-26
      • 2017-12-11
      • 1970-01-01
      相关资源
      最近更新 更多