我正在尝试构建一个过滤管道,其中过滤结果显示在文本字段中的用户输入上。它工作正常,除非在过滤器中没有输入任何内容。如果未输入任何内容,则不会显示列表中的任何项目。这不是我想要的,理想的行为应该是列表中的每个项目都应该显示出来。
我怎样才能做到这一点?提前谢谢。
HTML文件
<input class="form-control" placeholder="Search Your Contacts" type="text" [(ngModel)]="filterFn">
<ul class="list-group">
<li class="list-group-item"><h4>Contacts:</h4>
<app-contact-item class="list-group-item" *ngFor="let contact of contacts | filter: filterFn; let i = index" [contact]="contact" [contactId]="i"></app-contact-item>
</li>
</ul>
<div class="col-xs-12">
<button class="btn btn-primary" (click)="onEdit()">Add New Contact</button>
</div>
TS组件文件
import {Component, OnInit, Input} from "@angular/core";
import {ContactService} from "./contact.service";
import {Contact} from "./contact";
import {Router} from "@angular/router";
@Component({
selector: 'app-contact-list',
templateUrl: './contact-list.component.html',
})
export class ContactListComponent implements OnInit {
@Input() filterFn: string = '';
contacts: Contact[] = [];
constructor(private contactService: ContactService,
private router: Router) {
}
ngOnInit() {
this.contacts = this.contactService.getContacts();
}
onEdit() {
this.router.navigate(['/contacts/new']);
}
}
TS过滤管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(value: any, args?: any): any {
if(args[0] === '') {
return value;
}
if(value.length === 0) {
return value;
}
let filteredArray = [];
for(let item of value) {
if(item['firstName'].match('^.*' + args[0] + '.*$')) {
filteredArray.push(item);
}
}
return filteredArray;
}
}
答案 0 :(得分:0)
更改管道如下:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(value: any, args?: any): any {
return value.filter((item) => {
if (item.hasOwnProperty('firstName')) {
if(args.length) {
return args[0] ? item.firstName.match('^.*' + args[0] + '.*$') : true;
} else {
return true;
}
} else {
return false;
}
});
}
}