I was wondering if there is an easy way to count dom elements using Angular 2. For example having the following code:
<div *ngFor="let user of users" [ngClass]="{'special': isSpecial(user)}">
{{ user.name }}
</div>
Is there an easy way to get the total number of rows containing the special class without creating pipes or functions?
With Jquery it would be as easy as running:
$( ".special" ).length;
Steps:Use template reference and ViewChildren() to get HTML element. Inject Renderer and ElementRef into the constructor. Use the removeChild() method of the renderer to remove the child component. To get the host element, we need to use ElementRef.
We can access the DOM in Angular using different reference types like ElementRef , TemplateRef , ViewRef , ComponentRef and ViewContainerRef . These reference types can be queried from templates using @ViewChild and @ContentChild . Browser's native DOM element can be accessed via ElementRef .
DOM stands for Document Object Model. AngularJS's directives are used to bind application data to the attributes of HTML DOM elements.
You can use normal DOM APIs to do what you would've previously done via jQuery eg:
document.querySelectorAll('.special').length
However, unless the isSpecial(user) function is extremely expensive to run, why would querying the DOM be any more performant than just filtering the users array in code?
users.filter(u => isSpecial(u)).length
I'd caution against worrying about performance in this scenario too much without actually running some performance tests first to verify your assumptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With