angular - 使用反应形式的选择组件中的2路数据绑定
问题描述
我正在使用select
组件来显示一些countries
及其相关联的内容states
,languages
如下所示:
这里我需要执行 2-way 数据绑定,我states
想languages
根据Country
.
我知道这是这个 问题的副本,这里他们使用模板驱动的表单,但我想为反应式表单执行它。
Stackcblitz演示
解决方案
试试看:
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>
推荐阅读
- ios - 错误构建 Xcode - 真实设备上的颤振项目
- sql - 计算最大日期和选定日期之间的差异
- node.js - docker-compose - NODE_ENV 不适用
- flutter - 使用 FlutterEngineCxnRegistry 添加 TFLite 结果
- flutter - Flutter Changenotifier 类总是需要在我的函数中传递
- rabbitmq - 我使用 ESP32 (pubsubclient) 它经常重新连接:将终止,因为对等关闭 TCP 连接
- php - 在 WooCommerce 中更改产品尺寸标签的长度
- javascript - 检查 URL 是否存在并链接到音频文件
- kibana - 运行 Kibana 会给出“version_conflict_engine_exception”
- python - DNN 中的错误:层序贯_10 的输入 0 与层不兼容