Created
February 8, 2019 09:52
-
-
Save AmirTugi/3fdeba9315469ffdcface02cc367dc97 to your computer and use it in GitHub Desktop.
This file contains hidden or 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, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges } from '@angular/core'; | |
import { CategoryModel } from './category/model'; | |
import { Observable } from 'rxjs'; | |
import { CategoryQuery } from './category/store.query'; | |
import { CategoryStoreService } from './category/store.service'; | |
export type SearchEvent = { searchTerm: string, selectedCategory: CategoryModel}; | |
@Component({ | |
selector: 'app-search', | |
template: ` | |
<form (submit)="search.emit({ searchTerm: searchTerm, selectedCategory: selectedCategory })"> | |
<mat-card class="search-container"> | |
<mat-card-title>Search</mat-card-title> | |
<mat-card-content> | |
<mat-form-field class="search-term-input-container"> | |
<input matInput type="text" placeholder="term" [(ngModel)]="searchTerm" name="search-term" /> | |
</mat-form-field> | |
<mat-form-field> | |
<mat-select placeholder="category" [compareWith]="compareWith" [(ngModel)]="selectedCategory" name="category"> | |
<mat-option *ngFor="let category of (categories$ | async)" [value]="category">{{category.name}}</mat-option> | |
</mat-select> | |
</mat-form-field> | |
</mat-card-content> | |
<mat-card-actions><button mat-raised-button color="primary" type="submit">Search</button></mat-card-actions> | |
</mat-card> | |
</form> | |
`, | |
styles: [`...`] | |
}) | |
export class SearchComponent implements OnInit, OnChanges { | |
@Input() searchTerm: string; | |
@Input() selectedCategoryId: number; | |
@Output() search = new EventEmitter<SearchEvent>(); | |
selectedCategory: CategoryModel; | |
categories$: Observable<CategoryModel[]>; // Will hold the selector for all the categories, and emits new value when the store changes. | |
constructor(private categoryStoreService: CategoryStoreService, private categoryQuery: CategoryQuery) {} | |
ngOnInit() { | |
this.fetchCategories(); | |
this.categories$ = this.categoryQuery.selectAll(); | |
} | |
ngOnChanges(changes: SimpleChanges) { | |
if (changes.selectedCategoryId && changes.selectedCategoryId.currentValue !== null) { | |
this.selectedCategory = this.categoryQuery.getEntity(changes.selectedCategoryId.currentValue); | |
} | |
} | |
private fetchCategories() { | |
this.categoryStoreService.search().subscribe(); | |
} | |
private compareWith(category1: CategoryModel, category2: CategoryModel) { | |
return category2 && category1.id === category2.id; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment