我想過濾使用輸入表中的數據。對於我已經創建了一個名爲textFilter
定製管如下:過濾管始終日誌未定義
import {Pipe, PipeTransform} from '@angular/core';
import { Person } from '../Models/person';
@Pipe({
name: 'textFilter',
pure: false
})
export class TextFilterPipe implements PipeTransform {
transform(people: Person[], filter: string): any {
if (!people || !filter) {
return people;
}
people.forEach(person => {
console.log(person.firstName); //<-- this line logs undefined
});
console.log(filter);
return people.filter(person => person.firstName.indexOf(filter) !== -1);
}
}
然後我使用它是這樣的:
<div class="container" >
<input type="text" [(ngModel)]="query" (keyup)="0" />
<table>
<thead>
<tr>
<td>First Name</td>
<td>Last Name</td>
</tr>
</thead>
<tbody>
<tr *ngFor="let person of people | textFilter : query">
<td>{{person.firstName}}</td>
<td>{{person.lastName}}</td>
</tr>
</tbody>
</table>
</div>
這裏是我的Component.ts:
import { Component, OnInit } from '@angular/core';
import { Person } from '../../Models/person';
@Component({
selector: 'app-auto-complete',
templateUrl: './auto-complete.component.html',
styleUrls: ['./auto-complete.component.css']
})
export class AutoCompleteComponent implements OnInit{
constructor() {}
query: string;
people: Person[];
ngOnInit() {
this.query = '';
this.people = [
new Person ("Shane", "Watson", "Australia"),
new Person ("David", "Warner", "Australia"),
new Person ("Ricky", "Ponting", "Australia"),
new Person ("Adam", "Gilchrist", "Australia"),
new Person ("Andrew", "Symonds", "Australia"),
new Person ("Sachin", "Tendulkar", "India"),
new Person ("Rahul", "Dravid", "India"),
new Person ("Virender", "Sehwag", "India"),
new Person ("Mahendra", "Dhoni", "India"),
new Person ("Virat", "Kohli", "India"),
new Person ("Gautam", "Gambhir", "India")
];
}
}
這裏是我的人類:
export class Person {
firstName: string;
lastName: string;
country: string;
constructor(firstName: string, lastName: string, country: string) {}
}
爲什麼person.firstName
總是undefined
裏面TextFilterPipe
?
更新:
如果我登錄的person
代替person.firstName
然後我得到
Person {}
印在控制檯
你的過濾器不應該不純,因爲它不會改變任何東西。 –