【问题标题】:mat-option (onSelectionChange) -- the value does not appear correctlymat-option (onSelectionChange) -- 值没有正确显示
【发布时间】:2018-07-27 03:45:56
【问题描述】:

当我第一次在其下拉列表中选择城市时,该值不会出现。当我在第二个下拉列表中选择国家时,第一个下拉列表中的第一个值出现,第二个下拉列表中的第二个值不出现。关于我的代码中的问题有什么建议吗?

代码.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> 

谢谢!

【问题讨论】:

    标签: angular typescript autocomplete angular-material


    【解决方案1】:

    好吧,你会在第一次调用时修补你的值。但是在您的第一次通话中,您将此 this.country_id.value 称为 not set,因此未定义。在您的第二次通话中,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, '')"
    

    【讨论】:

    • 我改成这样:updateForm(event: any, city: any, country_id: any, region_id: any) { if (event.isUserInput) { this.Myform['controls']['country_id '].patchValue(country_id); this.Myform['controls']['city'].patchValue(city); this.Myform['controls']['region_id'].patchValue(region_id); } }
    • 和 html: {{ country.name }}
    猜你喜欢
    • 2019-03-26
    • 1970-01-01
    • 2019-01-28
    • 2019-04-24
    • 2010-12-09
    • 2021-01-23
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    相关资源
    最近更新 更多