Angular 4: Store pipe output variable for use outside of template

廉价感情. 提交于 2019-12-08 05:00:56

问题


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.



来源:https://stackoverflow.com/questions/47057352/angular-4-store-pipe-output-variable-for-use-outside-of-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!