mat-option(onSelectionChange) - 该值未正确显示

时间:2018-02-16 09:05:31

标签: angular typescript autocomplete angular-material

当我第一次在其下拉列表中选择城市时,该值不会显示。当我在第二个下拉列表中选择国家/地区时,将显示第一个下拉列表中的第一个值,并且不会显示第二个下拉列表中的第二个值。关于我的代码中存在什么问题的任何建议?

Code.ts

  updateForm(event: MatOptionSelectionChange , city: City, country_id: Country, region_id: Region) {
        if (event.source.selected) {
        this.Myform['controls']['country_id'].patchValue(this.country_id.value);
          this.Myform['controls']['city'].patchValue(this.city.value);
        }
    }

code.html

    <input formControlName="country_id" id="country_id" matInput placeholder="Select Region*" aria-label="State" [matAutocomplete]="auto"
      autoActiveFirstOption [formControl]="country_id">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option (onSelectionChange)="updateForm($event,country.id,'country_id')" id="country_id" *ngFor="let country of filteredOptionsCountry | async" [value]="country.name">
        {{ country.name }}
      </mat-option>
    </mat-autocomplete> 

   <input formControlName="city" id="city" matInput placeholder="Select City*" aria-label="State" [matAutocomplete]="auto1"
      autoActiveFirstOption [formControl]="city">
    <mat-autocomplete #auto1="matAutocomplete">
      <mat-option (onSelectionChange)="updateForm($event,city.id,'city')" *ngFor="let city of filteredOptionsCity | async" [value]="city.name">
        {{ city.name }}
      </mat-option>
    </mat-autocomplete> 

谢谢!

1 个答案:

答案 0 :(得分:0)

好的是,您在第一次通话时修补了您的价值。但是在您的第一个电话中,您将此 this.country_id.value 称为未设置,因此未定义。在第二次通话中 this.country_id.value 设置并将被添加。

这可能有助于您理解:

updateForm(event: MatOptionSelectionChange , city: any, country_id: any, region_id: any) {
   if (country_id !== ''){
      this.Myform['controls'['country_id'].patchValue(country_id);
   }
   if (city !== '') {
      this.Myform['controls']['city'].patchValue(city);
   }
}

在HTML中:

(onSelectionChange)="updateForm($event, city.id, '', '')"

(onSelectionChange)="updateForm($event, '', country.id, '')"