1

如何将一个值设置为下拉菜单中的默认选定值?我正在使用 Angular 8。我有以下 html

<div class="form-group">
        <label class="form-control-label col-form-label-sm">Content Type</label>
        <select class="form-control form-control-sm" [(ngModel)]="item.contentType"  formControlName="contentType" name="contentType">
          <option   *ngFor="let contentType of contentTypes" [value]="contentType.name" >{{contentType.displayName}}</option>
        </select>
      </div>

我尝试过使用[selected]="contentType.name=='TEXT'",但下拉菜单仍然没有将默认选择值显示为“纯文本”。

<div class="form-group">
        <label class="form-control-label col-form-label-sm">Content Type</label>
        <select class="form-control form-control-sm" [(ngModel)]="item.contentType" formControlName="contentType" name="contentType">
          <option *ngFor="let contentType of contentTypes" [value]="contentType.name" [selected]="contentType.name=='TEXT'">{{contentType.displayName}}</option>
        </select>
      </div>

contentTypes 是一个数组[{"name":"TEXT","displayName":"Text Only"},{"name":"AUDIO","displayName":"Audio"},{"name":"VIDEO","displayName":"Video"}]

4

3 回答 3

2

卡鲁,

默认情况下,item.contentType 应该以与您的 contentTypes 列表中的某个选项对应的值进行初始化。例如,如果您item.contentType使用 value进行初始化,则默认情况下会预先选择带有 value 的选项。TEXTTEXT

或者,您可以只optionnull文本输入值Select content(例如)。并验证它,如果需要的话。就像是:

<div class="form-group">
   <label class="form-control-label col-form-label-sm">Content Type</label>
   <select class="form-control form-control-sm" [(ngModel)]="item.contentType"
         name="contentType">
      <option [value]="null">Select content</option>
      <option *ngFor="let contentType of contentTypes" [value]="contentType.name"> 
          {{contentType.displayName}}
      </option>
    </select> 
</div>

无论如何,除了您将使用哪种构建表单的方法(反应式表单或模板驱动表单)。因为您在选择组件的定义中犯了错误。如果您想使用模板驱动的表单模式,请仅使用[(ngModel)]定义和删除。formControlName="contentType"首先在提供的链接中研究这个。

于 2020-03-05T21:20:21.003 回答
0

像这样在选项中使用 [selected]。我认为您选择的条件是错误的

<select class="form-control" [(ngModel)]="item.contentType">
   <option *ngFor="let contentType of contentTypes" [value]="contentType.name" [selected]="contentType.name==item.contentType">{{contentType.displayName}}</option>
</select>
于 2021-09-10T03:18:03.330 回答
0

我可以通过这个例子使它工作

模板

<div class="form-group">
   <label class="form-control-label col-form-label-sm">Content Type</label>
   <select class="form-control form-control-sm" formControlName="contentType" 
         name="contentType">
      <option *ngFor="let contentType of contentTypes" [value]="contentType.name"> 
          {{contentType.displayName}}
      </option>
    </select> 
</div>

在 ts

// if you will give the value to the contentType control it will be selected item
// something like this 
export class ReleaseComponent implements OnInit {

   ngOnInit() {
      this.yourForm.get('contentType').patchValue('TEXT'); 
      // or
      this.yourForm.get('contentType').patchValue(this.contentTypes[0].name); 
   }
}

我希望这会有所帮助

于 2020-03-05T21:15:50.557 回答