Quantcast
Channel: Jose Luis Monteagudo
Viewing all articles
Browse latest Browse all 13

Filtering lists in Angular with RxJs

$
0
0

Suppose that you have an observable that contains a list of elements and you have a text input control. You want that when the user types something in the input control your list is filtered automatically (take into account that this filter is applied in the client side, not in the server side). You can use the operator combineLatest to filter your list:

@Component({
  selector: 'article-list',
  template: `
	<div>

	  <mat-form-field>
		<input matInput placeholder="Filter by article title" [formControl]="filter">
	  </mat-form-field>

	  <article-table [articles]="filteredArticles$ | async"></article-table>

	</div>
  `,
  styleUrls: []
})
export class ArticleListComponent {

  filteredArticles$: Observable<Article[]>;
  filter: FormControl = new FormControl('');

  constructor(private articleService: ArticleService) {

    this.filteredArticles$ = combineLatest(
        this.articleService.findAllArticles(),
        this.filter.valueChanges.pipe(startWith(''))
      ).pipe(
        map(([articles, filterString]) => articles.filter(article => article.title.indexOf(filterString) !== -1))
      );

  }

}

Viewing all articles
Browse latest Browse all 13

Trending Articles