Angular 4: Store pipe output variable for use outs

2019-05-31 03:10发布

问题:

I am aware I can alias pipe output in angular 4 but this is only useful inside the template where it is aliased.

Example

<div *ngIf="race | async as raceModel">
    <h2>{{ raceModel.name }}</h2>
    <small>{{ raceModel.date }}</small>
</div>

Here raceModel cannot be referenced outside of the ngIf. In my case, I am ordering and filtering a collection with pipes and want to get a hold of the length of the returned collection after filtering so I can update my NgbPagination.

My code:

<tr *ngFor="let cust of customers | filterBy: searchFilters: true | orderBy: order: reverse: true: start: end as collection">
                        <td>{{cust.id}}</td>
                    </tr>
                    </tbody>
                </table>
                <ngb-pagination *ngIf="customers"
                                (pageChange)="pageChange($event)"
                                [collectionSize]="collection.length"
                                [(page)]="page"
                                [(pageSize)]="pageSize"
                                [maxSize]="5"
                                [rotate]="true"
                                [ellipses]="true"
                                [boundaryLinks]="true">
                </ngb-pagination>

I don't want to drag the pipes into the view model if I can avoid it. Any tips on how to secure a variable from a pipe for later use in the view?

回答1:

For the time being I have resulted to doing the following:

<ngb-pagination *ngIf="customers"
 (pageChange)="pageChange($event)"
 [collectionSize]="(customers | filterBy: searchFilters: true: true)"
 [(page)]="page"
 [(pageSize)]="pageSize"
 [maxSize]="5"
 [rotate]="true"
 [ellipses]="true"
 [boundaryLinks]="true">
</ngb-pagination>

Where the second true param for the filter pipe returns the length of the filtered array instead of the filtered array itself. Hacky but works just fine.