您好我正在尝试创建一个简单的搜索过滤器,用于过滤员工数组并返回一组员工,其名称包含在搜索框中键入的字母。我已导入过滤器管道,并在提供程序下声明它。我没有得到任何错误,但它也没有做任何事情......任何想法?
我在filter.pipe.ts中创建了自定义过滤器管道:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter',
pure: false
})
export class FilterPipe implements PipeTransform {
transform(employees: any, term: any): any {
//check if search term is undefined
if (term === undefined) return employees;
//return updated employees array
return employees.filter(function(employee){
return employee.name.toLowerCase().includes(term.toLowerCase());
})
}
}
我是"术语" app.component.ts中搜索输入中的变量:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: `
<div class="col-sm-12 col-md-12">
Search By:
<div class=navbar-form role="search">
<div class="input-group">
<input type="text" [(ngModel)]="term" class="form-control" placeholder="Last name, First name">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><span class="glyphicon glyphicon-search"></span></button>
</div>
</div>
<div class="row" *ngIf="term">
<h3>You searched for: {{term}}</h3>
</div>
</div>
</div>
<app-employee></app-employee>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
}
它正在我的employee-list.component.ts中过滤:
import { Component, OnInit } from '@angular/core';
import { IEmployee } from './shared/interface';
import { SharedService } from './shared/shared.service';
import { EMPLOYEES } from './mock-employees';
import { FilterPipe } from './filter.pipe';
// import {Observable, Subject} from '@reactivex/rxjs';
@Component({
selector: 'app-employee',
templateUrl: `
<p>
Emoloyee List:
</p>
<ul *ngFor = 'let employee of employees | filter:term'>
<li>{{employee.name}}</li>
<li>{{employee.city}}</li>
</ul>
`,
styles: [],
})
export class EmployeeListComponent implements OnInit {
employees: IEmployee[] = [
{"name":"Sarah", "city": "Barcelona"},
{"name": "Lauren", "city": "Milan"},
{"name": "Jenny", "city": "Toronto"}
];
constructor( private sharedService: SharedService ) { }
ngOnInit(): void{
}
}
和我的app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { EmployeeListComponent } from './employee-list.component';
import { SharedService } from './shared/shared.service';
import { FilterPipe } from './filter.pipe';
@NgModule({
declarations: [
AppComponent,
EmployeeListComponent,
FilterPipe
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [ SharedService, FilterPipe ],
bootstrap: [AppComponent],
})
export class AppModule { }
该列表根本没有被过滤。我不明白为什么它不工作...... 任何帮助将非常感激!谢谢!
答案 0 :(得分:1)
确定它不起作用,因为term
从未在EmployeeListComponent
内定义。只需在EmployeeListComponent
:
@Input('search-term')
public term: string = null;
修改您的应用组件HTML以传入搜索字词:
<app-employee [search-term]="term"></app-employee>