【问题标题】:Angular2: Show everything for empty filter pipeAngular2:显示空过滤管的所有内容
【发布时间】:2016-12-01 05:06:40
【问题描述】:

我正在尝试构建一个过滤器管道,其中过滤后的结果显示在文本字段中的用户输入上。它工作正常,除非在过滤器中没有输入任何内容。如果未输入任何内容,则不会显示列表中的任何项目。这不是我想要的,期望的行为应该是应该显示列表中的每个项目。

我怎样才能做到这一点?提前致谢。

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;
  }

}

【问题讨论】:

    标签: angular


    【解决方案1】:

    如下改变你的管道:

    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;
          }
        });
      }
    }
    

    【讨论】:

    猜你喜欢
    • 2015-07-08
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 2023-03-29
    • 2017-05-04
    • 1970-01-01
    相关资源
    最近更新 更多