select2 angular2+ 将第一个值设置为默认值

select2 angular2+ setting 1st value as default

<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" 已经选择了数据 太多尝试了很多方法 none 其中有效。

在组件中做

this.companycountryValue="some default country.name value"

请注意,默认值必须分配给隐藏在 country.name 下的任何内容,因此带有此 [value] 的选项将被选中

奖金: 你不想这样做吗?

 <option *ngFor="let country of countrydata" [value]="country.value">{{ country.name}}</option>

有两种方法可以解决您的问题

Step1: // picking up the index of the option and setting it in html attributes like this:

    <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: Setting up from the component to the select

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>