可以将Date类型的组件属性绑定到类型设置为datetime-local的
HTML5输入?
在我的组件中,我有一个气质:
public filterDateFrom: Date;
在我的模板中,我有一个输入定义为:
<input type="datetime-local" [(ngModel)]="filterDateFrom" />
但绑定不起作用.
Demo Plnkr
您可以使用以下格式绑定日期:yyyy-MM-ddTHH:mm,您还可以从date.toISOString().slice(0,16)(切片在分钟后移除时间部分).
@Component({ selector: 'app',template: `<input type="datetime-local" [value]="date" (change)="date=$event.target.value" /> {{date}}` }) export class AppComponent { date: string; constructor() { this.date = new Date().toISOString().slice(0,16); } }
请记住,date.toISOString()将从本地时间返回一个日期偏移量.您还可以自己构建日期字符串:
private toDateString(date: Date): string { return (date.getFullYear().toString() + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + ("0" + (date.getDate())).slice(-2)) + 'T' + date.toTimeString().slice(0,5); }
如果您想要将选择绑定到Date模型,可以使用它来构建自定义日期组件:
@Component({ selector: 'my-date',events: ['dateChange'],template: `<input type="datetime-local" [value] = "_date" (change) = "onDateChange($event.target.value)" />` }) export class MyDate{ private _date: string; @Input() set date(d: Date) { this._date = this.toDateString(d); } @Output() dateChange: EventEmitter<Date>; constructor() { this.date = new Date(); this.dateChange = new EventEmitter(); } private toDateString(date: Date): string { return (date.getFullYear().toString() + '-' + ("0" + (date.getMonth() + 1)).slice(-2) + '-' + ("0" + (date.getDate())).slice(-2)) + 'T' + date.toTimeString().slice(0,5); } private parseDateString(date:string): Date { date = date.replace('T','-'); var parts = date.split('-'); var timeParts = parts[3].split(':'); // new Date(year,month [,day [,hours[,minutes[,seconds[,ms]]]]]) return new Date(parts[0],parts[1]-1,parts[2],timeParts[0],timeParts[1]); // Note: months are 0-based } private onDateChange(value: string): void { if (value != this._date) { var parsedDate = this.parseDateString(value); // check if date is valid first if (parsedDate.getTime() != NaN) { this._date = value; this.dateChange.emit(parsedDate); } } } }
您的组件的用户将绑定到具有双向模型绑定的Date模型:
@Component({ selector: 'my-app',directives: [MyDate],template: '<my-date [(date)]="date"></my-date> {{date}}' }) export class AppComponent { @Input() date: Date; constructor() { this.date = new Date(); } }
<input type="datetime-local" [(date)]="date" />