PrimeNG DataTable自定义排序或过滤(角度2)
我在PrimeNg数据表的排序/过滤日期列中遇到问题.因为我正在显示日期"dd/mm/yyyy"字符串.
I am facing issue in sorting/Filtering date column in PrimeNg Datatable.As i am displaying date "dd/mm/yyyy" string .
- 如果使用模板显示"dd/mm/yyyy",则过滤器不起作用,因为该过滤器对日期为ISO格式的实际数据绑定起作用.
- 如果从后端将数据转换为字符串格式,则排序不正确,因为它是按字符串而不是日期进行排序.
我使用moment.js解决了此问题,因为它更容易,更快捷,但是如果您想在没有任何框架的情况下进行操作,则始终可以对代码进行一些自定义(如果条件和字符串转换,我希望再多一些
I solved this issue using moment.js, because it's easier and faster, but always code can be customized a little bit if You want to do it without any frameworks (i hope few more if conditions, and string conversions)
因此,您必须将moment.js添加到您的项目中: a)通过从此站点将src链接添加到您的主要html索引文件(主要的角度选择器,polyfills等)中 http://momentjs.com/docs/这里还有其他可能性.
So You have to add moment.js to Your project: a) by adding src link to your main html index file (where is main angular selector, polyfills etc.) from this site https://cdnjs.com/libraries/moment.js/ b) but if it's production i recommend to add it via npm. http://momentjs.com/docs/ here are other possibilities.
然后,您必须在import语句下和@Component批注上方声明moment变量
Then you must declare moment variable under import statements and above @Component annotation
declare var moment;
然后,如果您已经在项目中添加了primeng模块,则在primeng的p-dataTable标签内的html文件中有p-column标签,在此标签内,我们需要添加sortable ="custom"和(sortFunction)=这样的"mysort($ event)":
then if u already have primeng module added to Your project, in the html file within primeng's p-dataTable tag there is p-column tag and here within this tag we need to add sortable="custom" and (sortFunction)="mysort($event)" like so:
<p-column field="date" header="Data" sortable="custom" (sortFunction)="mysort($event)"></p-column>
带有p列标记的显示日期为DD.MM.YYYY字符串格式,例如:2017年3月1日
Date displayed with p-column tag is in DD.MM.YYYY string format like e.g: 03.01.2017
在此之后,在我们将数据提取并推入数组的组件中,该组件用于在表中显示数据,在我的名为约会的示例中,我们需要添加名为mysort的函数(因为我们在html p-中调用了此函数,列标签)
After that in component where we are fetching and pushing data to array, which is used to display data in a table, in my example named appointments we need to add function named mysort (because we are calling this function in html p-column tag)
mysort(event) {
let comparer = function (a, b): number {
let formatedA = moment(a.date, "DD.MM.YYYY").format('YYYY-MM-DD');
let formatedB = moment(b.date, "DD.MM.YYYY").format('YYYY-MM-DD');
let result: number = -1;
if (moment(formatedB).isBefore(formatedA, 'day')) result = 1;
return result * event.order;
};
this.appointments.sort(comparer);
}
在我的示例中,
a.date和b.date是类似"21.12.2016"的字符串,我们需要将其格式化为YYYY-MM-DD.然后我们只是比较日期.
in my example a.date and b.date is a string like "21.12.2016" that we need to format to YYYY-MM-DD. Then we just are comparing dates.
仅此而已,我检查了此代码,即可正常工作. 我希望它能对某人有所帮助,请原谅,如果解释是以教程形式编写的,但这是我的第一个答案,我想以正确的方式做到这一点:)
And just it, i checked this code and it works. I hope it will help someone, and excuse me if explanation was written in tutorial style but this is my first answer and i wanted to do it in the right way :)