I have a dynamic navigation bar with search functionality on top it
Component.html
<input type="text" class="form-control" placeholder="Navigation search..." [(ngModel)]="searchString">
<li class="nav-item " *ngFor="let dir of directories">
<a href="javascript:;" class="nav-link nav-toggle">
<i class="fa fa-clock-o"></i>
<span class="title">{{ dir.name }}</span>
<span class="arrow"></span>
</a>
<ul class="sub-menu" *ngFor="let file of dir.child">
<li class="nav-item ">
<a href="#" class="nav-link ">
<span class="title">{{file.name}}</span>
</a>
</li>
<navigation-bar [directories]="dir.child"></navigation-bar>
</ul>
</li>
Component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'navigation-bar',
templateUrl: './app/home/navigationBar.component.html',
})
export class NavigationBarComponent {
@Input() directories: Array<Tree>;
}
export class Tree{
directories: any;
constructor()
{
this.directories = [
{
name: 'parent1',
child: [{
name: 'child1',
child: []
},
{
name: 'child2',
child: []
}]
},
{
name: 'parent2',
child: {
name: 'child1',
child: []
}
},
{
name: 'parent2',
child: [{
name: 'child1',
child: []
},
{
name: 'child2',
child: []
}]
}];
}
}
Now I want to search through the nav bar using the search string entered in the text box.
Is there any way to achieve above functionality for every character entered in the text box. It should filter the name property of the JSON object
On your input field:
<input (keyup)="applyFilter($event.target.value);">
On your component:
applyFilter(filter: String) {
this.filteredArray = this.directories.filter(item => {
if (item.name.toString().toLowerCase().indexOf(filter.toLowerCase()) !== -1) {
return true;
}
return false;
}
);
}
filteredArray is the array containing the items matching the filter.
You can create a custom pipe to do this, advantage is that you can pass those keys needs to search. You can update below code for your needs. For example
<li *ngFor="let n of list | FilterPipe: queryString : searchableList ">
{{n.name}} ({{n.age}})
</li>
this.searchableList = ['name','age']
Pipe
@Pipe({
name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
transform(value: any, input: string,searchableList : any) {
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any) {
var isTrue = false;
for(var k in searchableList ){
if(el[searchableList[k]].toLowerCase().indexOf(input) > -1){
isTrue = true;
}
if(isTrue){
return el
}
}
})
}
return value;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.