In this tutorial, we are going to build something more advanced. It will be a multi-field data filter which will include simple inputs as well as selects. Let’s get started.
Let’s create a new project
ng new angular-data-filters
cd angular-data-filters
We also need to install a Bootstrap.
npm install bootstrap
To make it work in an Angular project, we need to add:
"node_modules/bootstrap/dist/css/bootstrap.min.css",
inside the style section of the Angular.json file.
We need to create a filter pipe in the first place. The pipe is a simple way to transform values in an Angulartemplate.
ng generate pipe filter
After adding a couple of lines, we get our pipe to look like this:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter',
})
export class FilterPipe implements PipeTransform {
transform(items: any[], value: string, prop: string): any[] {
if (!items) return [];
if (!value) return items;
return items.filter(singleItem =>
singleItem[prop].toLowerCase().startsWith(value.toLowerCase())
);
}
}
It’s important to note that if all fields are empty the data should not be filtered.
To get started, use the below command:
ng generate component search
Let’s create a simple form that will include inputs for the first name, last name, job title, gender, and age from and age to fields. The last two fields will be used to create an age range.
export class SearchComponent implements OnInit {
form: FormGroup;
@Output() autoSearch: EventEmitter<string> = new EventEmitter<string>();
@Output() groupFilters: EventEmitter<any> = new EventEmitter<any>();
searchText: string = '';
constructor(private fb: FormBuilder,
private userService: UserService) {}
ngOnInit(): void {
this.buildForm();
}
buildForm(): void {
this.form = this.fb.group({
firstName: new FormControl(''),
lastName: new FormControl(''),
jobTitle: new FormControl(''),
gender: new FormControl(''),
agefrom: new FormControl(''),
ageto: new FormControl('')
});
}
#angular #angular-js #html5 #html #web-development