首页 > 解决方案 > Angular ngBootstrap:使用下拉列表过滤表中的值

问题描述

在根据所选过滤器过滤表值时需要帮助

这是我想用作过滤器的 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>

部门.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);
            }
        );

  }

}

为 response.departments 打印出什么 console.log

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

标签: angularngx-bootstrap

解决方案


将管道添加到您的模块

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">

如果公司属性是虚假的,它将返回所有部门,一旦公司有一个值,它将按公司过滤部门。

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


推荐阅读