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.