angular - 从下拉列表中过滤数据并在另一个组件中显示相关数据
问题描述
我有一个标题组件,它有一个显示公司的下拉列表,还有一个显示所有分支数据的组件。我只想在从标题组件中选择公司时显示数据。当数据位于同一组件中时,我只能使用下拉列表过滤数据。下面的代码在分支组件中工作。
头组件.ts
companyData: [] = [];
companyId;
getCompany() {
this.companyService.getCompanies().subscribe(x => {
Object.assign(this.companyData, x);
});
}
changeCompany(companyId) {
this.companyId = companyId;
console.log(companyId);
}
header.html
<li class="navbar-form">
<div class="from-group">
<select class="dropdown-item" (change)="changeCompany($event.target.value)">
<option value="" disabled selected>Select Company</option>
<option *ngFor="let comp of companyData" [value]="comp.Id">
{{comp.Name}}
</option>
</select>
</div>
</li>
分支组件.ts
getBranches(companyId) {
this.branchService.getBranches().subscribe(b => {
Object.assign(this.branchData, b);
this.branchData = this.branchData.filter(b => b.CompanyId == companyId);
});
}
selectedCompany(company) {
this.companyId = company;
this.getBranches(company);
}
解决方案
您应该阅读有关在组件之间共享数据的更多信息:https ://angular.io/guide/inputs-outputs
首先,您应该将 companyId 传递给branch.component.ts ,例如:
<branch [companyId]="companyId"></branch>
然后,当 angular 检测到 Input companyId 的变化时,您应该触发getBrunches()。
brunch.component.ts应该是这样的:
export class BrunchComponent implements OnChanges{
@Input() companyId: any;
constructor(){
// some logic
}
ngOnChanges(changes: SimpleChanges){
if('companyId' in changes){
this.getBranches(this.companyId);
}
getBranches(companyId) {
this.branchService.getBranches().subscribe(b => {
Object.assign(this.branchData, b);
this.branchData = this.branchData.filter(b => b.CompanyId == companyId);
});
}
}
推荐阅读
- reactjs - 是否可以将 React 高阶组件应用于一般 div?
- javascript - Angular 4+ 中特定路由的 HTTP_INTERCEPTOR
- perl - 如何使用sed在模式之后插入一行并在pattern1中第一次出现单词之前插入另一行?
- arrays - JSP 中的会话数组
- javascript - 如何从作为 CVE 报告存储库的 MongoDB 进行查询?
- configuration - SharePoint 2013 新服务器加入场
- c - MPI_Bcast 所有进程发送到所有其余进程
- java - JAR:无法找到或加载主类
- list - 如何在python中将整数集合转换为列表数据类型?
- php - CRUD 方法的全局范围