I'm new to Stackoverflow and to Angular. I'm writing a frontend app (an ecommerce) in Angular. I binded a click event to a button of a mat-menu in order to have the following behavior: when I click on the button I want to display the products of the category that has been clicked. For example, if I click the button "Make-up" I want that all the products with category "Make-up" will be displayed. The problem is that when I click on the button nothing is displayed on the browser, but I suppose that the logic of the app works because if I open the console of the browser the producs of the selected category are printed out.
product.component.html:
<mat-menu #menu="matMenu">
<button mat-menu-item (click)="categoryFilter('Make-up')"> Make-up</button>
...
</mat-menu>
product.component.ts:
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css'] })
export class ProductComponent implements OnInit {
public products: Product[] = [];
public product!: Product;
constructor(private productService: ProductService) { }
ngOnInit() {
this.getProducts();
}
public getProducts(): void{
this.productService.getProducts().subscribe(
(response: Product[]) => {
this.products= response;
},
(error: HttpErrorResponse) => {
alert(error.message);
}
);
}
public categoryFilter(category: string): void{
this.productService.getProductsByCategory(category).subscribe(
(response: void) => {
console.log(response);
},
(error. HttpErrorResponse)=>{
alert(error.message);
}
)
} }
I think you have missed binding the response to a property, and then using that property to display the data on your browser.
I don't know the response type, for demo purposes let's say it's a string.
First, you'll need to create a property just like you created public product!: Product;
we'll call it categoryName: string
In the click event, you'll have to bind this property with your response, hence it should look something like this:
public categoryFilter(category: string): void{
this.productService.getProductsByCategory(category).subscribe(
(response: string) => {
this.categoryName = response;
console.log(response);
},
(error. HttpErrorResponse)=>{
alert(error.message);
}
)
}
Now You'll have to bind that categoryName
in your HTML so that it can be displayed. You can use Angular's text interpolation which uses curly brackets {{}} to display string values in the HTML.
Hence your HTML will look like this:
<mat-menu #menu="matMenu">
<button mat-menu-item (click)="categoryFilter('Make-up')"> {{ categoryName }} </button>
...
</mat-menu>
I advise you to read Angular's Guide as you proceed further.
Angular's text interpolation: https://angular.io/guide/interpolation