Skip to content

Instantly share code, notes, and snippets.

@LayZeeDK
Created December 4, 2018 07:15
Show Gist options
  • Save LayZeeDK/b4dad89870382c642433b7592391959f to your computer and use it in GitHub Desktop.
Save LayZeeDK/b4dad89870382c642433b7592391959f to your computer and use it in GitHub Desktop.
Hero search: Presentational component model with UI behaviour
import {
Component,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output,
} from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged, takeUntil } from 'rxjs/operators';
import { Hero } from '../hero';
@Component({
selector: 'app-hero-search-ui',
templateUrl: './hero-search.component.html',
styleUrls: [ './hero-search.component.css' ]
})
export class HeroSearchComponent implements OnDestroy, OnInit {
private destroy: Subject<void> = new Subject();
private searchTerms: Subject<string> = new Subject();
private searchTerms$: Observable<string> = this.searchTerms.pipe(
// wait 300ms after each keystroke before considering the term
debounceTime(300),
// ignore new term if same as previous term
distinctUntilChanged(),
);
@Input() heroes$: Observable<Hero[]>;
@Input() title: string;
@Output() search: EventEmitter<string> = new EventEmitter();
// Push a search term into the observable stream.
searchFor(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.searchTerms$.pipe(
// complete when component is destroyed
takeUntil(this.destroy),
).subscribe(term => this.search.emit(term));
}
ngOnDestroy(): void {
this.destroy.next();
this.destroy.complete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment