Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count dom elements in Angular2

Tags:

angular

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;
like image 772
Ander Avatar asked Mar 03 '17 20:03

Ander


People also ask

How do you read the DOM element in angular 6?

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.

How does the angular identify the DOM elements?

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 .

What is a DOM element in angular?

DOM stands for Document Object Model. AngularJS's directives are used to bind application data to the attributes of HTML DOM elements.


1 Answers

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.

like image 97
snorkpete Avatar answered Oct 13 '22 14:10

snorkpete