Angular2排序数组,用于在HTML中的* ngFor中显示 [英] Angular2 sorting array for displaying in *ngFor in html

查看:84
本文介绍了Angular2排序数组,用于在HTML中的* ngFor中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览所有帖子

<li *ngFor="let post of posts">

当我显示每个帖子的日期时,

When displaying the date for each post I do:

{{post.date | date:'yyyy-MM-dd HH:mm:ss'}}

我想做的是按照最新的顺序显示所有帖子.

What I want to do is display all the posts in order of newest first.

我曾尝试使用类似以下的管道:

I have tried using a pipe like:

<li *ngFor="let post of posts | order-by-pipe">


import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
 name: 'order-by-pipe'
})
export class OrderByPipe implements PipeTransform{

 transform(array: Array<string>, args: string): Array<string> {

  if(!array || array === undefined || array.length === 0) return null;

    array.sort((a: any, b: any) => {
      if (a.date < b.date) {
        return -1;
      } else if (a.date > b.date) {
        return 1;
      } else {
        return 0;
      }
    });
    return array;
  }

}

但是它不起作用.我收到错误消息:

But it does not work. I get the error:

TypeError: Cannot read property 'toUpperCase' of undefined ("
[ERROR ->]*ngFor="let post of posts | order-by-pipe">

任何帮助都将受到欢迎,谢谢

Any help would be welcome, thanks

推荐答案

当您使用order-by-pipe作为选择器时,它试图查找变量order bypipe,并且谁知道它们的作用呢?

When you use order-by-pipe as the selector it is attempting to find the variables order by and pipe and do who knows what with them.

将管道中的name:更改为orderByPipe可解决此问题.

Changing the name: in your pipe to orderByPipe resolves the issue.

那很奇怪.

这是具有相同代码,不同名称的演示: http://plnkr.co/edit/BXkrPqeMYuJMhkx94i6M?p =预览

Here's a demo of the same code, different name: http://plnkr.co/edit/BXkrPqeMYuJMhkx94i6M?p=preview

这篇关于Angular2排序数组,用于在HTML中的* ngFor中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆