【问题标题】:2-way data binding in select component using of the reactive form使用反应形式的选择组件中的2路数据绑定
【发布时间】:2019-04-21 11:41:19
【问题描述】:

我正在使用select 组件来显示一些countries 及其关联的stateslanguages,如下所示:

这里我需要进行2路数据绑定,我想根据Country中的选择更改stateslanguages下拉列表。

我知道这是 QUESTION 的副本,这里他们使用 模板驱动表单,但我想为 反应式表单 执行它。

Stackcblitz DEMO

【问题讨论】:

  • 您能否更新一些代码以便更好地理解?喜欢那些下拉列表的 JSON

标签: angular angular-material


【解决方案1】:

试试看:

import {Component} from '@angular/core';

export interface Country {
  value: string;
  viewValue: string;
}
export interface State {
  country: string;
  value: string;
  viewValue: string;
}
export interface Language {
  state: string;
  value: string;
  viewValue: string;
}
/**
 * @title Basic select
 */
@Component({
  selector: 'select-overview-example',
  templateUrl: 'select-overview-example.html',
  styleUrls: ['select-overview-example.css'],
})
export class SelectOverviewExample {
  public selCountry;
  public selState;
  countries: Country[] = [
    {value: 'IND', viewValue: 'India'},
    {value: 'AUS', viewValue: 'Austarlia'},
    {value: 'ENG', viewValue: 'England'}
  ];

   states: State[] = [
    {country: 'IND', value: 'KAR', viewValue: 'Karnataka'},
    {country: 'IND', value: 'TEL', viewValue: 'Telangana'},
    {country: 'AUS', value: 'KL', viewValue: 'Kerala'}
  ];
    languages: Language[] = [
    {state: 'KL', value: 'KN', viewValue: 'Kannada'},
    {state: 'KAR', value: 'TL', viewValue: 'Telugu'},
    {state: 'TEL', value: 'ML', viewValue: 'Malayalam'}
  ];
  getStates() {
    return this.states.filter(item => {
return item.country == this.selCountry;
    });
  }
  getLanguages() {
    return this.languages.filter(item => {
return item.state == this.selState;
    });
  }
}


<mat-form-field>
  <mat-select placeholder="Country" [(ngModel)]="selCountry">
    <mat-option *ngFor="let country of countries" [value]="country.value">
      {{country.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field>
  <mat-select placeholder="States" [(ngModel)]="selState">
    <mat-option *ngFor="let state of getStates()" [value]="state.value">
      {{state.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field>
  <mat-select placeholder="Language">
    <mat-option *ngFor="let language of getLanguages()" [value]="language.value">
      {{language.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

【讨论】:

  • 感谢您的回答。现在我可以根据选定的country从列表中看到stateslanguages。但我希望显示stateslanguage,而不是从list中选择。跨度>
  • @PrashanthGH 哦,你可以尝试添加(更改)事件。像&lt;country (change)="onCountryChange()"&gt;onCountryChange(){let states=this.getStates();if (states.length) this.selState=states[0].value;this.onStateChange();} onStateChange 功能与国家相同。
猜你喜欢
  • 2019-04-01
  • 2020-04-22
  • 1970-01-01
  • 2019-10-25
  • 1970-01-01
  • 2017-08-04
  • 2019-03-26
  • 2017-06-05
  • 2017-09-02
相关资源
最近更新 更多