首页 > 解决方案 > 从下拉列表中过滤数据并在另一个组件中显示相关数据

问题描述

我有一个标题组件,它有一个显示公司的下拉列表,还有一个显示所有分支数据的组件。我只想在从标题组件中选择公司时显示数据。当数据位于同一组件中时,我只能使用下拉列表过滤数据。下面的代码在分支组件中工作。

头组件.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);
  } 

标签: angulartypescript

解决方案


您应该阅读有关在组件之间共享数据的更多信息: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);
    });
 }
}

推荐阅读