从下拉列表中过滤数据,并在另一个组件角中显示相关数据



我有一个header组件,它有一个显示公司的下拉菜单,还有另一个组件,它显示所有分支数据。我希望仅在从标题组件中选择公司时才显示数据。我只能在同一组件中使用下拉菜单过滤数据。下面的代码是在分支组件中工作的。

头component.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> 

分支component.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

首先,您应该传递companyIdbranch.component.ts如:
<branch [companyId]="companyId"></branch>
然后,您应该触发getBrunches()当angular检测到InputcompanyId

中的变化时.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);
});
}
}

最新更新