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

帅比萌擦擦* 提交于 2019-12-01 10:20:45

问题


I get a country object from a service and bind it to a form that has a dropdown list of countries. The country doesn't appear selected after retrieving it from the service but all the other data is shown OK including a string gender field which is bound to a dropdown list. I can manually select the country from the list though. How can I automatically show the country as selected?

personal-details.component.html

    <form [formGroup]="form" (submit)="doSave(form.values)">
        <mat-card class="main-card">

            <mat-card-content>
                <p>Personal Details</p>
                <mat-form-field class="full-width-input">
                  <input matInput placeholder="Given name" formControlName="givenName" >
                </mat-form-field>
                <mat-form-field class="full-width-input">
                  <input matInput placeholder="Surname" formControlName="surname" required>
                </mat-form-field>
                <mat-form-field class="full-width-input">
                    <mat-select placeholder="Select gender" formControlName="gender" required>
                        <mat-option *ngFor="let g of genders" [value]="g">{{g}}</mat-option>
                    </mat-select>      
                </mat-form-field>
                <mat-form-field class="full-width-input">
                    <mat-select placeholder="Select country of birth" formControlName="countryBorn" required>
                      <mat-option *ngFor="let country of countries" [value]="country">{{country.name}}</mat-option>
                    </mat-select>      
                </mat-form-field>
            </mat-card-content>

        </mat-card>
    </form>

personal-details.component.ts

  countries = [
    new Country('1100', 'Australia', '1'),
    new Country('1201', 'New Zealand', '160'),
    new Country('3105', 'Malta', '140')
  ];
  genders = ['F', 'M'];

  ngOnInit() {
    this.form = this.fb.group({
      givenName: ['', Validators.required],
      surname: ['', Validators.required],
      gender: ['', Validators.required],
      countryBorn: ''
    });

    this.response = this.applicantService.getDetails()
      .pipe(take(1), tap(resp => {
        this.form.patchValue(resp.personalDetails);
      }));

  }

domains:

export class PersonalDetails {
  givenName: string;
  surname: string;
  gender: string;
  countryBorn: Country;

  constructor(givenName?: string, surname?: string, gender?: string, countryBorn?: string) {
    this.id = id;
    this.surname = surname;
    this.gender = gender;
    this.countryBorn = countryBorn;
  }
}  

export class Country {
  id: string;
  name: string;
  displayOrder: string;

  constructor(id?: string, name?: string, displayOrder?: string) {
    this.id = id;
    this.name = name;
    this.displayOrder = displayOrder;
  }
}

data:

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

Form value on load ({{form.value | json }}) =  { "givenName": "Bert", "surname": "Oliver", "gender": "M", "countryBorn": { "id": "1201", "name": "New Zealand", "displayOrder": "160" }

Thanks


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/50903716/angular-6-cannot-automatically-select-bind-dropdown-list-value-from-supplied-obj

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