Angular 6 cannot automatically select/bind dropdown list value from supplied object

狂风中的少年 提交于 2019-12-01 12:26:19

Angular uses object identity to select option and also provides special input property to customize the default option comparison algorithm: compareWith:

html

<mat-select ... formControlName="countryBorn" [compareWith]="compareFn">
                                              ^^^^^^^^^^^^^^^^^^^^^^^^^   

ts

compareFn(c1: Country, c2: Country) {
  return c1.id === c2.id;
}            

Ng-run Example

Either Set resp.personalDetails.countryBorn to the actual object from list before assigning it to form (since object comparison {...}==={...} is always false, Angular won't be able to match and select on it)

resp.personalDetails.countryBorn = this.countries.find(country=> resp.personalDetails.countryBorn.id);

or set id alone as value

<mat-option *ngFor="let country of countries" [value]="country.id">{{country.name}}</mat-option>

The data would have only country ID not whole object.

{ "surname": "Oliver", "givenName": "Bert", "gender": "M", "countryBorn": "1201", "name": "New Zealand", "displayOrder": "160" }, "birthdate": "1990-04-21" }

or else you may need to define your own comparison function using compareWith: https://angular.io/api/forms/SelectControlValueAccessor#caveat-option-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!