I am facing a challenge with my child component (filters.component.ts) as I attempt to emit a string to the parent component. Previously, I successfully achieved this with another component, but Angular seems to be hesitant when implementing an *ngFor loop through a string array to pass the category string to the method. Despite adding a console log to the onShowCategory() method in home.component.ts, no string values seem to get logged, indicating that the values are not being passed to the parent upon activation of the click event. Here is the modified code snippet (the arrows inserted for clarity purposes point to the lines of relevance):
filters.component.html:
<mat-expansion-panel *ngIf="categories">
<mat-expansion-panel-header>
<mat-panel-title>CATEGORIES</mat-panel-title>
</mat-expansion-panel-header>
<mat-selection-list [multiple]="false">
<mat-list-option *ngFor="let category of categories" [value]="category"> <--------
<button (click)="onShowCategory(category)">{{ category }}</button> <--------
</mat-list-option>
</mat-selection-list>
</mat-expansion-panel>
filters.component.ts:
@Component({
selector: 'app-filters',
templateUrl: './filters.component.html',
styleUrls: []
})
export class FiltersComponent {
@Output() showCategory = new EventEmitter<string>() <-------
categories: string[] = ['shoes', 'sports']; <-------
onShowCategory(category: string): void { <-------
this.showCategory.emit(category); <-------
}
}
home.component.html:
<mat-drawer-container [autosize]="true" class="min-h-full max-w-7xl mx-auto border-x">
<mat-drawer mode="side" class="p-6" opened>
<app-filters (showCategory)="onShowCategory($event)"></app-filters> <-------
</mat-drawer>
<mat-drawer-content class="p-6">
<app-products-header (columnsCountChange)="onColumnsCountChange($event)"></app-products-header>
{{ category }} <----- should display the category when selected
</mat-drawer-content>
</mat-drawer-container>
home.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: []
})
export class HomeComponent {
cols = 3;
category: string | undefined; <-------
onColumnsCountChange(colsNumber: number): void {
this.cols = colsNumber
}
onShowCategory(newCategory: string): void { <-------
this.category = newCategory; <-------
}
}
I have meticulously reviewed and traced the variables multiple times but continue to struggle. When passing the category from the child component template to the onShowCategory method and emitting it to the parent, I call the EventEmitter from the parent component using the $event variable which ideally should update the value of the category property in the home component. Spelling has been double-checked and tag positions adjusted, yet a console.log added to the method does not produce any output in the console, and the string fails to appear on the home template. What mistake might I be making?