0

I am trying to write a pager.

I would like to not put the <li> element to the dom if number=-1.

I could not write ngIf inside an ngFor so if anyone could show me the way I would appreciate it.

Here is what I'd like to improve:

<li *ngFor="let number of pagerArray" class="page-item">
  <a class="page-link" href="#">{{number}}</a>
</li>
Supamiu
  • 8,501
  • 7
  • 42
  • 76
rematnarab
  • 1,277
  • 4
  • 22
  • 42
  • 1
    Possible duplicate of [\*ngIf and \*ngFor on same element causing error](https://stackoverflow.com/questions/34657821/ngif-and-ngfor-on-same-element-causing-error) – David G. Aug 07 '17 at 13:41
  • @DavidG. I don't think that this question is a duplicate because the problem is not the same, the quesiton you linked is a problem with ngFor inside ngIf, here it's the opposite: ngIf inside ngFor. – Supamiu Aug 07 '17 at 13:59

3 Answers3

4

Using the ng-container:

is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.

<ng-container *ngFor="let number of pagerArray">
    <li *ngIf="number != -1"  class="page-item">
        <a class="page-link" href="#">{{number}}</a>
    </li>
</ng-container>
Ploppy
  • 14,810
  • 6
  • 41
  • 58
1

You can use array.filter() for that:

In your component:

getPagerArray(){
    return this.pagerArray.filter((num) => {
        return num >= 0;
    });
}

in your template:

<li *ngFor="let number of getPagerArray()" class="page-item">
    <a class="page-link" href="#">{{number}}</a>
</li>
Supamiu
  • 8,501
  • 7
  • 42
  • 76
  • It will be executing the filter function in every change detection cycle, not much safe for performance solution. – Daniel Kucal Aug 07 '17 at 13:47
  • It would be the same for a pipe or a ngIf (ngIf wont use filter but it'll still check the condition). So I don't think that the performance loss is that fat, but I agree, the best solution would involve modfying the change detection strategy for an `OnPush` one to reduce the filter calls. – Supamiu Aug 07 '17 at 13:56
1

there is many ways you can implemented with.
one way you can set the *ngIf on the a tag

<li *ngFor="let number of pagerArray" class="page-item">
    <a class="page-link" href="#" *ngIf='number != -1'>
        {{number}}
    </a>
</li>

another way you can do it is by adding your own filter as follow

<li *ngFor="let number of pagerArray | yourFilter" class="page-item">
    <a class="page-link" href="#">
        {{number}}
    </a>
</li>
Raed Khalaf
  • 1,997
  • 2
  • 13
  • 29