1
嗨我試圖創建一個簡單的搜索過濾器,過濾員工數組並返回其名稱包含搜索框中鍵入的字母的僱員數組。我已經導入了過濾器管道,並在提供程序下聲明瞭它。我沒有得到任何錯誤,但它也沒有做任何事情..任何想法?Angular2自定義搜索過濾器不工作
我已經創造了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!';
}
和它被過濾在我的員工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 { }
該列表根本沒有被過濾。我不明白爲什麼它不工作... 任何幫助將不勝感激!謝謝!
非常感謝它的工作!我在[(ngModel)] =「term」中使用了雙向數據綁定,所以我認爲這足以在組件周圍調用!非常感謝。 – Kimmiekim