Last active
October 27, 2019 08:06
-
-
Save xErik/026729b70099d824e959d8695b8d914f to your computer and use it in GitHub Desktop.
Filter Observable AngularFire results by multiple attributes dynamically with a Form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
getCourses(): Observable<Course[]> { | |
return this.db | |
.collection<Course>(this.path) | |
.valueChanges({ idField: 'id' }); // id field is nice to have, only | |
} | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core'; | |
import { FormBuilder, FormGroup } from '@angular/forms'; | |
import { Course } from '../../shared/course'; | |
import { CourseManagerService } from '../../shared/course-manager.service'; | |
@Component({ | |
selector: 'app-course-read-all', | |
templateUrl: './course-read-all.component.html', | |
styleUrls: ['./course-read-all.component.scss'] | |
}) | |
export class CourseReadAllComponent implements OnInit { | |
private form: FormGroup; | |
courses: Course[]; | |
coursesFiltered: Course[]; | |
showSpinner = true; | |
constructor( | |
private manager: CourseManagerService, | |
private formBuilder: FormBuilder | |
) {} | |
ngOnInit() { | |
this.resetForm(); | |
this.resetList(); | |
} | |
resetForm() { | |
this.form = this.formBuilder.group({ | |
term: [''], | |
language: [''], | |
category: [''] | |
}); | |
this.form.valueChanges.subscribe(() => this.performFilter()); | |
} | |
resetList() { | |
// Get typed-array from Observable-array | |
this.manager.getCourses().subscribe(data => { | |
this.courses = data; | |
this.coursesFiltered = this.courses; | |
this.showSpinner = false; | |
}); | |
} | |
performFilter() { | |
const filterBy = this.form.get('term').value.toLocaleLowerCase(); | |
const filterByLang = this.form.get('language').value.toLocaleLowerCase(); | |
const filterByCat = this.form.get('category').value.toLocaleLowerCase(); | |
this.coursesFiltered = this.courses.filter( | |
(course: Course) => | |
(filterBy === '' || | |
(course.name.toLocaleLowerCase().indexOf(filterBy) !== -1 || | |
course.description.toLocaleLowerCase().indexOf(filterBy) !== -1 || | |
course.tags.toLocaleLowerCase().indexOf(filterBy) !== -1)) && | |
(filterByCat === '' || | |
course.category.toLocaleLowerCase() === filterByCat) && | |
(filterByLang === '' || | |
course.language.toLocaleLowerCase() === filterByLang) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment