angular - Angular 6:基于其他下拉值的下拉显示选项
问题描述
我有 2 个下拉菜单,一个用于选择state,另一个用于service agent。为服务机构显示的选项取决于所选的州值。
服务机构和州下拉菜单的数据来自profile.service.ts
.
问题:当用户选择状态时,如何使服务代理中的值显示发生变化。
profile.component.html
<mat-form-field>
<mat-select placeholder="Service Agency" required formControlName="serviceAgency">
<mat-option value="option">Option</mat-option>
<mat-option value="{{item.id}}" *ngFor="let item of service_agency$">
{{item.name}}
</mat-option>
</mat-select>
</mat-form-field>
profile.component.ts
//get state
get_state(){
this.profileService.get_state().subscribe(data => {
this.state$ = data;
});
}
//get service center base on state id
onChange(state) {
this.service_agency$ = this.profileService.get_service_agency()
.pipe(filter((item)=> item == state.value));
console.log(this.service_agency$);
}
配置文件.service.ts
get_state() {
return this.http.get(url)
.pipe(map(data => {
return data;
}));
}
get_service_agency() {
return this.http.get(url)
.pipe(map(data => {
return data;
}));
}
解决方案
在 angular 中,当您更新任何数据时,它也会在 html 中反映该数据。
我猜当你改变 state 的值时,你调用 API 并获取service agency
.
当您获得新列表时,您只需将该新列表绑定到变量中。Angular 会自动将该新列表绑定到 html 中。
<option *ngFor="let item of service_agency$" value=[item.name]>
{{item.name}}
</option>
更改状态值时:
onChange(state) { // Get the ref of selected state
// Now hear you need to call API and pass state id and get new list of agency
this.profileService.get_service_agency().subscribe((data) => {
// Clear all data from array and then bind new fresh data
this.service_agency$ = []; // Clear
this.service_agency$.push(...data); // Bind fresh data
// Check data is bind in array properly or not ...
console.log("New service list data is ::: " , this.service_agency$);
})
}
绑定新数据后,新列表会自动显示在HTML
页面中。
推荐阅读
- ubuntu - Zerotier cli 命令在 ubuntu 中给出错误“缺少端口和 zerotier-one.port”
- devops - 如何使用 AWS CDK Pipelines 构建不同语言的 lambda
- node.js - Jest 检测到以下 1 个可能阻止 Jest 退出的打开句柄,指向 mongoose 的 openUri
- python - 如何在 Python 中正确使用“not()”运算符
- javascript - 如何将数据从 React 应用程序传递到 Alan Studio 并在 Alan Studio 中接收该数据?
- html - 下载部分网站以供离线使用 - 交互式图表
- django - 在 django 中上传和操作 xml 和图像文件
- spring-boot - 如何使用 Kotlin Spring Boot 获取列注释
- kotlin - 如何在潘多拉导航中传递参数?
- java - 如何获得最接近我的颜色变量的颜色?