Reputation: 27
I'm developing a blog site which has a menu where I need to be able filter my blogs from a blog genre that the user selects. I am currently trying to use a filter pipe and when the user picks a genre from the sub-menu the list of blogs get filtered according to the genre.
I've used a filter pipe once before with a text input field and it worked but this time I need it to filter according to the button value selected by the user and I can't get it to work.
I am trying to set the value of the searchTerm of the filter to the genre that I need to filter by when the button is clicked as below:
<mat-toolbar>
<ul [(ngModel)]="searchWord">
<li>
<button mat-button (click)="searchWord = 'Business and Economy'">Business and Economy</button>
</li>
<li>
<button mat-button (click)="searchWord = 'Law and Social Justice'">Law and Social Justice</button>
</li>
<li>
<button mat-button (click)="searchWord = 'Global Health'">Global Health</button>
</li>
<li>
<button mat-button (click)="searchWord = 'Foreign Affairs'">Foreign Affairs</button>
</li>
</ul>
</mat-toolbar>
<mat-divider></mat-divider>
<ng-container class="ng-container" *ngIf="blogs.length > 0">
<h2>Featured Blogs</h2>
<div class="blog-card-div" *ngFor="let blog of blogs | blogFilter:searchWord">
<mat-card class="mat-elevation-z8" id="card-div" >
This is my code for my filter pipe below:
import { PipeTransform, Pipe } from '@angular/core';
import { Blog } from '../blog.model';
@Pipe({
name: 'blogFilter'
})
export class BlogFilterPipe implements PipeTransform {
// first arg might need to be the string of songs
transform(blogs: Blog[], searchTerm: any): Blog[] {
if (!blogs || !searchTerm) {
return blogs;
}
// filters applied to the song array
return blogs.filter(blog =>
(blog.genre.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1));
}
}
Currently my filter doesn't work, am I doing something wrong or can you just not filter according to a button selection?
Upvotes: 0
Views: 647
Reputation: 31125
I don't understand the need for two-way binding to the ngModel
directive. Try without it
<mat-toolbar>
<ul> <!-- no use for `ngModel` here -->
<li>
<button mat-button (click)="searchWord = 'Business and Economy'">Business and Economy</button>
</li>
<li>
<button mat-button (click)="searchWord = 'Law and Social Justice'">Law and Social Justice</button>
</li>
<li>
<button mat-button (click)="searchWord = 'Global Health'">Global Health</button>
</li>
<li>
<button mat-button (click)="searchWord = 'Foreign Affairs'">Foreign Affairs</button>
</li>
</ul>
</mat-toolbar>
Upvotes: 1