如何在Angular HTML页面判断布尔值并仅显示一次通知组件
Fix Duplicate Notification Component in Angular
Hey there! I see the issue you're facing—your current setup uses *ngFor to loop through every item, so every isUpdate: true entry renders a separate notification component. Let's fix that so the notification only shows once if there's at least one item with isUpdate: true.
Solution 1: Add a Calculated Property in Your Component Class
This is the cleanest approach, keeping your template logic minimal.
In your app.component.ts, add a getter property that checks if any item needs an update:
// app.component.ts get hasPendingUpdates(): boolean { // The some() method returns true as soon as it finds the first matching item return this.items.some(item => item.isUpdate); }
Then update your app.component.html to use this property instead of looping:
<!-- app.component.html --> <notification *ngIf="hasPendingUpdates"></notification>
Solution 2: Directly Use Array.some() in the Template
If you prefer not to add code to your component class, you can call the some() method directly in the template:
<!-- app.component.html --> <notification *ngIf="items.some(item => item.isUpdate)"></notification>
Why This Works
- The
Array.some()method checks if at least one element in the array passes the test (here,item.isUpdate === true). It stops searching as soon as it finds a match, which is efficient. - Unlike your original
*ngForapproach, this only runs a single check instead of looping through every item and rendering a notification for each match.
内容的提问来源于stack exchange,提问作者Sleepyhead
相关产品推荐
相关产品推荐

