为“角度链”下拉列表设置默认值

时间:2019-08-22 16:27:57

标签: angular dropdown

我的ID中包含JSON国家/地区,我想要的是将defeulat值设置为selected,到目前为止,这里是我的选择代码:

<select (change)="onNationalitySelected($event.target.value)" id="nationality" formControlName="nationality">
                <option value=""> {{'messages.dropdownselect' | translate}} </option>
                <option *ngFor="let country of countries" [value]="country.id" [selected]="country.id == '100'" >
                  {{ country.name }}
                </option>
              </select>

.ts文件

  onNationalitySelected(nationalityId: number) {
    this.customer.coid = nationalityId;
    this.customer.nationality = this.countries.filter(
      c => (c.id == nationalityId)
    )[0].name;

我尝试将国家/地区的默认值设置为100,但是它不起作用,保存到数据库后该值仍然为空。

感谢您的任何评论。

1 个答案:

答案 0 :(得分:1)

ts

// Let's use FormGroup so we can add a control/default
countryForm: FormGroup;

// define our countries data
countries = [{
 id: '100',
 name: 'USA',
 code: 'USD'
},
{
 id: '200',
 name: 'Canada',
 code: 'CAD'
},
{
 id: '300',
 name: 'UK',
 code: 'GBP'
}];

constructor(private fb: FormBuilder) {}

ngOnInit() {
 // set country code 100 as default
 this.countryForm = this.fb.group({
  countryControl: [this.countries[0].id]
 });
}

html

// ngValue allows us to use an object for default value assignment
<option [ngValue]="country.id" *ngFor="let country of countries">{{country.name}}</option>

我对countryControl: [this.countries[0].id]不确定,如果不起作用,请尝试以下方法:countryControl: [this.countries[0]]

让我知道怎么回事!