AliAb
AliAb

Reputation: 569

Adding a counter on html file in Angular

I'm showing the restaurants that are filtered by the name and the address. (if no name or address is given then all restaurants are shown). The problem is that I need to add a counter to count the remaining restaurants after each filter or the count of all restaurants if no filtering is done.

The code I used (works perfectly):

(app-res-tabs is a component that shows the restaurant)

  <div *ngFor="let res of restaurants;">

    <li
      *ngIf="(res.Name.toLowerCase().includes(searchString?.toLowerCase()) 
              || searchLength == false) 
              && (res.Address == printedOption || checked == false)"
      class="nav-item has-treeview menu-open">
      <a class="nav-link active">
        <app-res-tabs [res]="res"></app-res-tabs>
      </a>
    </li>

  </div>

How to add a counter for the restaurants in this code ?

Upvotes: 2

Views: 4921

Answers (3)

StepUp
StepUp

Reputation: 38164

You can add index to the *ngFor:

<div *ngFor="let res of restaurants; let i = index">
    <p> It is index of restaurants {{ i }} </p>
    <p> It is counter of restaurants {{ i + 1 }} </p>
</div>

UPDATE:

You can create a variable counter:

counter = this.restaurants.length;

this.searchForm.controls['str'].valueChanges.subscribe((value) => {
  this.searchString = value;      
  this.counter = this.restaurants.filter(f => 
       f.Name.toLowerCase().includes(value.toLowerCase() 
       || this.searchLength == false) 
       && (f.Address == this.printedOption || this.checked == false)).length;
  if (this.searchString.length > 0) {
    this.searchLength = true;
  }
  else { this.searchLength = false }

});

HTML:

<div *ngFor="let res of restaurants; let k = index;">
    <!-- I want to show the count after this filter 
       (and the number of all restaurants if no filter is done) -->

    <li *ngIf="(res.Name.toLowerCase().includes(searchString?.toLowerCase()) 
        || searchLength == false) 
        &&(res.Address == printedOption || checked == false)"
        class="nav-item has-treeview menu-open">        
    <p>counter: {{ counter }}</p>
        <a class="nav-link active">
            <div>{{res.Name}}</div>
        </a>
    </li>
</div>

A work example at stackblitz.com

Upvotes: 3

YogendraR
YogendraR

Reputation: 2396

You can try to create a function that will return the filtered values.

getData(data){
   return data.filter(item => item.includes(yourSearchString));
}

Update filter function as per your requirement.

<div *ngFor="let res of getData(restaurants);let i = index">
<li
    {{i}}  
</li>
</div>

Upvotes: 0

Gaurang Dhorda
Gaurang Dhorda

Reputation: 3387

You can check this StackBlitz Link

You have to check remaining length of autocomplete results and actual data of length. You can use reactive forms here...

this.remainingResults = this.booksName.length -  data.length;

Go stackblitz link for complete example

Upvotes: 2

Related Questions