我正在使用select
组件来显示一些countries
及其相关的states
和languages
,如下所示:
这里我需要执行2路数据绑定,我想根据states
中的选择更改languages
和Country
下拉列表。
我知道这是此QUESTION的副本,在这里他们使用的是模板驱动的表单,但是我想对反应性表单执行它。 / p>
Stackcblitz DEMO
答案 0 :(得分: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>