<select class="example-full-width js-example-basic-single" #country name="country" [(ngModel)]="companycountryValue" required>
<option *ngFor="let country of countrydata" [value]="country.name">{{ country.value }}</option>
</select>
如何将第一个选项选择为默认选项? [(ngModel)] =“ companycountryValue”已经选择了数据,但也尝试了许多方法都无法使用。
答案 0 :(得分:0)
只需在组件中做
this.companycountryValue="some default country.name value"
仅建议将默认值分配给country.name
下隐藏的任何内容,因此将选择带有此[value]
的选项
奖金: 您不想这样做吗?
<option *ngFor="let country of countrydata" [value]="country.value">{{ country.name}}</option>
答案 1 :(得分:0)
有两种方法可以解决问题
Step1://获取选项的索引并将其设置为html 像这样的属性:
<select class="example-full-width js-example-basic-single" #country name="country" [(ngModel)]="companycountryValue" required>
<option *ngFor="let country of countrydata; let i = index" [value]="country.name" [selected]="i == 0 ? true : null" >{{ country.value }}</option>
</select>
Step2:从组件设置到选择
ngOnit(){
this.companycountryValue=countrydata[0];
}
并且在html中可以设置为
<select class="example-full-width js-example-basic-single" #country name="country" [(ngModel)]="companycountryValue" required>
<option *ngFor="let country of countrydata" [value]="country.name">{{ country.value }}</option>
</select>