I am diving into Angular 11 and exploring the world of Observables and Subjects as a beginner.
Within my application, I have a mat-autocomplete
component that organizes its results into categories. One of these categories is dedicated to articles, and I'm using the following code snippet to display them:
Snippet from the component file:
private readonly searchResultArticles = new Subject<Article[]>();
get searchResultArticles$(): Observable<Article[]> {
return this.searchResultArticles;
}
In the template:
<mat-optgroup label="Articles">
<mat-option *ngFor="let article of searchResultArticles$ | async" [value]="article">
<img class="example-option-img" aria-hidden [src]="getArticleThumbnail(article.profile_dir,article.title)" height="25" />
<span class="cocktail_name_search_result" *ngIf="article.title" [innerHTML]="article.title | highlight : autoCompleteInput.value : 1"></span>
-
<span class="cocktail_desc_search_result" *ngIf="article.desc" [innerHTML]="article.desc | highlight : autoCompleteInput.value : 1"></span>
</mat-option>
</mat-optgroup>
Currently, the mat-optgroup
displaying articles remains visible even when there are no items in the searchResultARticles$
Observable. I want to find an elegant way to hide it when empty.
I initially considered utilizing:
<mat-optgroup label="Articles" *ngIf="(searchResultArticles$ | async).length>0">
However, this implementation had some unexpected behavior where items intermittently failed to appear. It seems like I may need to deepen my understanding of how to use async operations effectively.
If you have any suggestions on a more graceful solution to this challenge, they would be greatly appreciated.
Thank you!