在Angular2上搜索和填充

时间:2017-11-06 04:57:25

标签: angular

我在angular2应用程序中从firebase中的div中提取了一组数据。数据包括名字,出生日期和姓氏。 我创建了一个SEARCH输入框。现在我想用匹配该搜索框的数据填充div,并使用名称。我尝试使用 Search Filter Pipe ,但无法成功。有人可以帮忙吗? 以下是我的代码:

member.service.ts:
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, 
              AngularFirestoreDocument } from 'angularfire2/firestore';
import { AngularFireDatabase, FirebaseListObservable } from 
    'angularfire2/database-deprecated';

import { Observable } from 'rxjs/Observable';

import { Member } from '../models/Member';


@Injectable()
 export class MemberService{
 membersCollection: AngularFirestoreCollection<Member>;
 members: Observable<Member[]>;
 memberDoc: AngularFirestoreDocument<Member>;

constructor(
 public afs: AngularFirestore,
 public afd: AngularFireDatabase) { 


 this.members = this.afs.collection('members').snapshotChanges().map(changes 
                  =>{ return changes.map(a => {
    const data = a.payload.doc.data() as Member;
    data.id = a.payload.doc.id;
    return data;
        });
    });
  }

 getMembers(){
   return this.members;
   }
 }


 member.ts
 export interface Member{
        id?: string;
        name?: string;
        birthdate?: string;
        lastname?: string;
      }

  members.component.ts
  import { Component, OnInit} from '@angular/core';
  import { MemberService } from '../../services/member.service';
  import { Member } from '../../models/Member';

   @Component({
    selector: 'app-members',
    templateUrl: './members.component.html',
    styleUrls: ['./members.component.css']
    })
  export class MembersComponent implements OnInit{
     members: Member[];

 constructor(private memberService: MemberService) { }

  ngOnInit() {
    this.memberService.getMembers().subscribe(members => {
//  console.log(members);
  this.members = members;
});
}
}


 members.component.html
 <input #txtMember placeholder="Search members..."/>
 <div *ngIf="members?.length > 0;else noMembers">
  <ul *ngFor="let member of members" class="collection">
    <li class="collection-item"><strong>{{member.name:}}</strong> 
                             {{member.birthdate}}{{member.lastname}}></li>
  </ul>
  </div>

1 个答案:

答案 0 :(得分:0)

在搜索输入框中使用ng model并传递此模型以过滤数据

html文件如下。

<input type="text" [(ngModel)]="input"/>
<table>
  <tr>
  <th>First Name</th>
  <th>Last Name</th>
  </tr>
  <tbody>
  <tr *ngFor="let item of data | searchPipe: input">
    <td>{{item.firstName}}</td>
    <td>{{item.lastName}}</td>
  </tr>
  </tbody>
</table>

搜索管道如下。

 transform (data, str: string): any {
    if (str === undefined || str == null || str == '')
      return data;

    return data.filter(function (obj) {
      return Object.keys(obj).some(function (key) {
        return obj[key].toString().toLowerCase().includes(str.toLowerCase());
      });
    });
  }

如果搜索输入框为空,它将返回相同的数据。当您在搜索框中键入时,它会将搜索框中的输入传递给搜索管道,过滤数据并返回过滤后的数据。

你可以在这里查看工作示例。

working example