Issue
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: Angular Search
Here is my API call:
@Component({
selector: 'players',
templateUrl: './players.component.html',
styleUrls: ['./players.component.css']
})
export class PlayersComponent {
ngOnInit() {
this.subscriptions.push(this.webService.getPlayers().subscribe((response: any) => {
this.player_list = response;
}));
}
}
This returns an array like:
As the tutorial states, I first created the search bar:
<!-- Search Bar -->
<input type="search" class="searchBar" [(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:
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?
Solution
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;
}));
}
}
Answered By - Devang Patel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.