首页 > 解决方案 > 使用反应形式的选择组件中的2路数据绑定

问题描述

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

在此处输入图像描述

这里我需要执行 2-way 数据绑定,我stateslanguages根据Country.

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

Stackcblitz演示

标签: angularangular-material

解决方案


试试看:

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>

推荐阅读