the app.component has json data displayed in the view using *ngfor. User can perform search as he/she types in the search box (basically on keyup event).
For future ease, I have made this search.component as a shared component.
I have written a code and want to know if this is the correct approach or even better one exists. Please do help.
Note: Currently, the code has 7 entries, but the actual entries will be minimum 1000.
Here is my sample POC for the application.
search.component.html - On every character entered, calling the method getSearchString()
<input type="text" placeholder="type here to search" (keyup)="getSearchString(text)" #text>
search.component.ts - Using subject _searchText defined in a common service to emit the value.
getSearchString(text) {
this.appService._searchText.next(text.value);
}
app.service.ts - Defining the subject being used.
_searchText = new Subject<string>();
getSearchText$ = this._searchText.asObservable();
app.component.ts - Subscribing on the observable getSearchText$ to search the json.
ngOnInit() {
this.data = [
{
name: 'pranjal',
id: 's1'
}, {
name: 'alini',
id: 's2'
}, {
name: 'nishank',
id: 's3'
}, {
name: 'pranvi',
id: 's3'
}, {
name: 'mayuri',
id: 's4'
}, {
name: 'malya',
id: 's5'
}, {
name: 'pravi',
id: 's5'
}
];
this.filteredData = JSON.parse(JSON.stringify(this.data));
this.appService.getSearchText$.subscribe((searchText) => {
this.filteredData = this.searchData(this.data, searchText);
});
}
searchData(data, searchText) {
let newData = [];
if (!searchText) {
newData = this.data;
} else {
newData = data.filter((obj) => {
return obj.name.includes(searchText);
});
}
return newData;
}