0

How to bind variable c (count of data items) with variable in component.ts file?

In HTML file:
<tr *ngFor="let entry of data; let c = count>

In component.ts file:

if (c > 5) ... else ...

For the sake of simplicity, let's suppose that data is dynamically generated so we can't use data in our component. Only thing I want to accomplish is to use c in component file.

It's NOT DUPLICATE of this: Gunters solution I want clear data binding, without relying on generated DOM.

UPDATE: Real scenario is more complex, I didn't want to add it in order to keep focus on above question, but because someone asked for it, it's here:

In HTML file:
<tr *ngFor="let entry of data | someFilter; let c = count>

In component.ts:
if (c > 5) ... // c here is the count of data items after data is filtered

Yes, I know I can manually trigger someFilter in component code and then count number of data items, but that's not preferable solution when you have pipes.

milosdju
  • 783
  • 12
  • 27
  • 1
    Can you provide some code showing what you are asking to make things more clear? – Daniel W Strimpel Apr 28 '18 at 00:07
  • @DanielWStrimpel I have edited my question, look after "UPDATED" section. The thing is I am using filter on for loop, so I can't get count of items iterated in component.ts file. – milosdju Apr 28 '18 at 14:09
  • I've never used a regular DOM node, but did you see if you can use `ViewChildren` to get a reference to the `` nodes? Like this `@ViewChildren('tr') tableRows: QueryList`. If that works you can watch for changes to that and get the length that way – Daniel W Strimpel Apr 28 '18 at 14:43

3 Answers3

1

Well, I supouse you can use some like:

<div *ngFor=".......;let i=index;let last=last;">
  <!--put here your data-->
  <ng-container *ngIf="last">
       Total Count {{i+1}}
  </ng-container>
</div>

But I think that is almost "bizarro". I go on thinking that the best approach is have two variables: data and dataFiltered, calculate dataFiltered and make the *ngFor over the dataFilteres.

Eliseo
  • 50,109
  • 4
  • 29
  • 67
0

Just create a varable c in your component.ts

c = arrayName.length;

Or you can do it in html directly too.

<span>Count: {{arrayName.length}}</span> 
Abel Valdez
  • 2,368
  • 1
  • 16
  • 33
0

You can add another pipe after your filtering pipe "someFilter", count elements and store the result in a service. Then it can be accessed from anywhere.

transform(input: Model[]): Model[] {
    if (input && this.myService.count !== input.length) {
        this.myService.count = input.length;
    }

    return input;
}
Yannick
  • 1
  • 1