【发布时间】:2017-04-22 08:26:41
【问题描述】:
我正在尝试使用输入过滤表中的数据。为此,我创建了一个名为 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")
];
}
}
这是我的person类:
export class Person {
firstName: string;
lastName: string;
country: string;
constructor(firstName: string, lastName: string, country: string) {}
}
为什么person.firstName 总是undefined 在TextFilterPipe 中?
更新:
如果我登录 person 而不是 person.firstName 那么我得到 p>
Person {}
在控制台上打印
【问题讨论】:
-
你的过滤器不应该是不纯的,因为它不会改变任何东西。
标签: javascript angular typescript pipe