Home > Blockchain >  How to hook up Angular search with other components?
How to hook up Angular search with other components?

Time:01-04

I am trying to implement a search bar into my Angular app that will filter data coming from an API. I am using the following tutorial: enter image description here

As the tutorial states, I first created the search bar:

<!-- Search Bar -->

<input type="search"  [(ngModel)]="searchText" placeholder="Search for a player...">

I then added the filter into my existing *ngFor:

<!-- Before -->
<div *ngFor="let player of player_list | paginate: config">

<!-- Adding filter -->
<div *ngFor="let player of player_list | paginate: config | filter: searchText">

In my terminal, I then ran:

ng generate pipe filter

And this created 2 new files:

app
 |___ filter.pipe.spec.ts
 |___ filter.pipe.ts

I then added in this code to filter.pipe.ts:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'filter'
})

export class FilterPipe implements PipeTransform {
  transform(items: any[], searchText: string): any[] {

    if (!items) {
      return [];
    }
    if (!searchText) {
      return items;
    }
    searchText = searchText.toLocaleLowerCase();

    return items.filter(it => {
      return it.toLocaleLowerCase().includes(searchText);
    });
  }
}

But when I go back into my browser, I get this error message:

enter image description here

How do I get the players.component.ts to read from filter.pipe.ts. I have tried importing it like:

// players.component.ts file

import { FilterPipe } from './filter.pipe';

...

constructor(public webService: WebService, public filterPipe: FilterPipe) {}

But that didn't work, can someone help please?

CodePudding user response:

It is clearly saying that searchText does not exist on PlayersComponent. You need to define searchText on PlayersComponent.

@Component({
  selector: 'players',
  templateUrl: './players.component.html',
  styleUrls: ['./players.component.css']
})

export class PlayersComponent {

    searchText = '';  // This is missing..

    ngOnInit() {
        this.subscriptions.push(this.webService.getPlayers().subscribe((response: any) => {
        this.player_list = response;
    }));
  }
}
  •  Tags:  
  • Related