首页 > 解决方案 > 无法在下拉框中设置默认选定选项

问题描述

如何在下拉框中将默认值设置为“我感兴趣”。这是代码。我也尝试删除 name 属性,但这不是一个好的解决方案。

<div class="form-group">
  <select (blur) = "validateTopic(topic.value)" (change)="validateTopic(topic.value)" class="custom-select form-control" #topic="ngModel" [class.is-invalid]="topic.invalid && topic.touched" name="topic" [(ngModel)]="userModel.topic" required [value]="'I am interested in'">
    <option value='default' selected>I am interested in </option>
    <option *ngFor="let sub of topics">{{sub}}</option>
  </select>
  <small class="text-danger" [class.d-none]="!topicHasError && topic.touched">Please choose a topic</small>
</div>

默认情况下,下拉框中没有选择任何内容。

标签: htmlangularhtml-selectangular7

解决方案


 <div class="form-group">
  <select (blur) = "validateTopic(topic.value)" (change)="validateTopic(topic.value)" class="custom-select form-control" #topic="ngModel" [class.is-invalid]="topic.invalid && topic.touched" name="topic" [(ngModel)]="userModel.topic" required [value]="'default'">
    <option value='default' selected>I am interested in </option>
    <option *ngFor="let sub of topics" [value]="sub">{{sub}}</option>
  </select>
  <small class="text-danger" [class.d-none]="!topicHasError && topic.touched">Please choose a topic</small>
</div>

推荐阅读