Angular ngBootstrap:使用下拉列表过滤表中的值

时间:2019-09-17 03:05:52

标签: angular ngx-bootstrap

需要基于所选过滤器来过滤表值的帮助

这是我想用作过滤器的ngbDropdown。

如果我选择公司A,该表将仅显示公司A。

不太清楚如何链接它。我得到了显示所有可用公司的过滤器,但还不能在表上应用该过滤器。

更新表的HTML代码

<select [(ngModel)]="company">
    <option [ngValue]="undefined">Please Select</option>
    <!-- List of all the companies -->
    <option *ngFor="let department of departments">{{department.company.companyName}}</option>
  </select>
  <div *ngFor="let department of departments | companyFilter: company">
    {{department.departmentName}} {{department.company.companyName}}
  </div>

department.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SessionService } from '../session.service';
import { DepartmentService } from '../department.service';
import { Department } from '../department';
import { Pipe, PipeTransform } from '@angular/core';
import { CompanyFilterPipe } from './company-filter.pipe';


@Component({
  selector: 'app-department',
  templateUrl: './department.component.html',
  styleUrls: ['./department.component.css']
})


export class DepartmentComponent implements OnInit {


  departments: Department[];

    constructor(private router: Router,
        private activatedRoute: ActivatedRoute,
        public sessionService: SessionService,
        private departmentService: DepartmentService) { 

    }

  ngOnInit() {

    this.departmentService.getDepartments().subscribe(
            response => {
        this.departments = response.departments;
        console.log(response.departments);
        console.log(response);
            },
            error => {
                alert("You have encountered an error : " + error);
            }
        );

  }

}

什么console.log打印出来以用于response.departments

Object
departments: Array(4)
0:
company: {companyAddress: "Brisbane 21", companyCode: "199305085M", companyId: 1, companyName: "Company A", companyNumber: 9999999, …}
departmentId: 1
departmentName: "Brand Management"

我已经更新了appmodule.ts,但似乎找不到companyFilter

1 个答案:

答案 0 :(得分:1)

将管道添加到您的模块

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'companyFilter'
})
export class CompanyFilterPipe implements PipeTransform {
  transform(departments, company) {
    return company ? departments.filter(department => department.company === company) : departments;
  }
}

然后在您的模板中

<tr *ngFor="let department of departments | companyFilter: company">

如果公司财产为假,它将返回所有部门,一旦公司具有价值,就会按公司对部门进行过滤。

有关示例https://stackblitz.com/edit/angular-3x9lfm,请参见StackBlitz