在页面加载时将下拉选择选项设置为默认值

时间:2019-11-14 13:11:24

标签: angular

下面是我的代码。我希望“选择文档类型”在最初加载表单时显示。因此,我将第一个设置为此,第二个是从后端获取日期。 Dropdownlist

<select class="custom-select" name="documentType" [(ngModel)]="myDocument.documentType.id"
                       #documentType="ngModel" [ngClass]="{'alert-border': documentType.errors?.emptyField}">
                 <option value="0" >Select the type of document</option>
                 <option [value]="documentType.id" *ngFor="let documentType of docTypes">{{documentType.denomination}}</option>
               </select>

我尝试过:

<option value="0" selected= "selected">Select the type of document</option>

没有运气。

3 个答案:

答案 0 :(得分:0)

您可以在TS文件中设置:

myDocument.documentType.id = "defaultValue"

答案 1 :(得分:0)

尝试下面,

将ngModel属性更改为[(ngModel)] =“ selectedDocumentTypeId”

<select class="custom-select" name="documentType" [(ngModel)]="selectedDocumentTypeId"
   #documentType="ngModel" [ngClass]="{'alert-border': documentType.errors?.emptyField}">
     <option value="0" >Select the type of document</option>
     <option [value]="documentType.id" *ngFor="let documentType of docTypes">{{documentType.denomination}}</option>
</select>

在您的ts文件中

selectedDocumentTypeId: string = '';

ngOnInit() { 
  this.selectedDocumentTypeId  = docTypes[0].id; /* Hoping docTypes array exist before this statement*/
}

答案 2 :(得分:0)

<option [ngValue]="0">Select the type of document</option>

*确保myDocument.documentType.id的初始值为0