Issue
Is there an easier way to get the count of actual displayed results in an ngFor that has a nested ngIf without?
<div *ngFor="let stuff of things">
<ng-container *ngIf="stuff.key === 'value'">
**I'd like an easier way to get the result of this *ngIf .length and use it elsewhere**
</ng-container>
</div>
I tried to use @ViewChildren and hoped for;
@ViewChildren('myContainerRef') containerRef: QueryList<any>
<label>Count {{ myContainerRef.length }}</label>
<div #myRef *ngFor="let stuff of things">
</div>
but get undefined result. Is my last resort doing a filter on the incoming array to get the count and assign it public vars? Or is there an easier way to get the count of an ngfor results that match a condition / are displayed?
Solution
You can use ViewChildren in AfterViewInit
at the earliest. You can search for ng-container
but would be better to search the elements you're after with #myRef
so it would count only the ones you are interested in.
<div *ngFor="let stuff of things">
<ng-container #myRef>
{{ stuff }} **I'd like an easier way to get the result of this *ngIf .length
and use it elsewhere**
</ng-container>
</div>
<br />
TotalContainers: {{ containersCount }}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements AfterContentChecked {
@ViewChildren('myRef') containers: QueryList<ElementRef>;
things = Array.from(Array(10).keys());
containersCount: number;
constructor() {}
ngAfterContentChecked() {
this.containersCount = this.containers?.length;
}
}
Working example: https://stackblitz.com/edit/angular-ivy-vpq5n4?file=src%2Fapp%2Fapp.component.ts
Answered By - Joosep.P
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.