我想将日期列格式化为Angular 2 NGX Datatable中的短日期。
以下是HTML:
<ngx-datatable
[rows]="toDos"
[columns]="columns">
</ngx-datatable>
以下是组件TypeScript
import { Component, OnInit } from '@angular/core';
import { IToDo } from '../shared/todo';
import { ToDoService } from '../shared/todo.service';
@Component({
selector: 'app-todo-list',
templateUrl: './todo-list.component.html',
styleUrls: ['./todo-list.component.css']
})
export class TodoListComponent implements OnInit {
toDos: IToDo[];
columns = [
{ prop: 'toDoId' },
{ name: 'To Do', prop: 'name' },
{ prop: 'priority' },
{ prop: 'dueDate' },
{ prop: 'completed' }
];
constructor(private _toDoService: ToDoService) {
}
ngOnInit() {
this.toDos = this._toDoService.getToDos();
}
}
我在HTML中尝试了这个但是它提供了模板解析错误:
<ngx-datatable
[rows]="toDos"
[columns]="columns"
<ngx-datatable-column prop="dueDate">
<ng-template let-value="value" ngx-datatable-cell-template>
{{value | date[:shortDate]}}
</ng-template>
</ngx-datatable-column>
>
</ngx-datatable>
答案 0 :(得分:2)
constructor(
private fb: FormBuilder,
private _currencyPipe: CurrencyPipe,
private _datePipe: DatePipe
) {
this.rows = [
{from: Date().toString(), to: Date(), amount: 100, verified: false},
{from: Date(), to: Date(), amount: 100, verified: true},
];
}
ngOnInit() {
this.columns = [
{ name: 'FROM', prop: 'from', pipe: this.datePipe()},
{ name: 'TO', prop: 'to', pipe: this.datePipe()},
{ name: 'AMOUNT', prop: 'amount', width: 85, pipe: this._currencyPipe},
{ name: 'CONFIRM | DELETE', cellTemplate: this.editCell, width: 155}
];
this.buildForm();
}
datePipe () {
return {transform: (value) => this._datePipe.transform(value, 'MM/dd/yyyy')};
}
您始终可以使用程序化方法来应用管道,实际上您可以使用此方法创建自定义管道。
ngx-dataTable中的管道@Input
需要具有以下转换的Pipelike结构:Function。您可以使任何函数返回转换函数并根据需要操纵数据。
答案 1 :(得分:1)
希望这对您有帮助
<ng-template #dateColumn let-row="row" let-value="value" let-i="index">
{{value | date:'dd-MM-yyyy'}}
</ng-template>
export class CvbankListComponent implements OnInit {
@ViewChild('dateColumn') dateColumn: TemplateRef<any>;
.
.
.
this.columns = [
.
.
{ name: 'Date', prop: 'Date', cellTemplate: this.dateColumn },
];
答案 2 :(得分:1)
我认为在列配置上使用 pipe
属性的这种方式非常干净(不确定 Angular 2 是否能够像 OP 要求的那样处理这个问题,但 Angular 10 可以)
class DateOnlyPipe extends DatePipe {
public transform(value): any {
return super.transform(value, 'MM/dd/y');
}
}
const columns = [{
name: 'Date',
prop: 'dateReported',
pipe: new DateOnlyPipe('en-US')
}];
来源:https://github.com/swimlane/ngx-datatable/issues/401#issuecomment-311635384
答案 3 :(得分:0)
您只需使用date pipe
格式化值。
{{value | date:'shortDate'}}
相当于{{value | date:'ymd'}}
,其输出日期如下:22/08/2017
答案 4 :(得分:0)
您的HTML错误。它应该如下所示。
<ngx-datatable
[rows]="toDos"
[columns]="columns">
<ngx-datatable-column name="dueDate">
<ng-template let-row="row" ngx-datatable-cell-template>
{{row.dueDate | date:'shortDate'}}
</ng-template>
</ngx-datatable-column>
</ngx-datatable>
请在此处找到示例代码:https://github.com/swimlane/ngx-datatable/blob/master/demo/sorting/sorting-default.component.ts