在我的 EventCreate 的 TypeScript 类中,我有 startDateTime
和 endDateTime
属性,数据类型为 Date
。 HTML5 使用输入类型 time
来获取时间。我只是想问:如何使输入类型 time
与 TypeScript 和 Angular2 一起使用?
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { EventCreate } from './eventCreate';
@Component({
selector: 'add-Event',
templateUrl: './event-add.component.html',
})
export class EventAddComponent {
title: string;
description: string;
locationId: number;
locationDetails: string;
categoryId: number;
isRegistrationRequired: boolean;
eventDate: Date;
startDateTime: Date;
endDateTime: Date;
maximumRegistrants: number;
newEvent: EventCreate;
constructor(private router: Router) { }
createNewEvent() {
console.log('new Event Created');
this.newEvent = new EventCreate(
this.title,
this.description,
this.locationId,
this.locationDetails,
this.categoryId,
this.isRegistrationRequired,
this.eventDate,
this.startDateTime,
this.endDateTime,
this.maximumRegistrants
);
console.log(this.newEvent);
//call service
//call route to go to Home page
this.router.navigate(['/home']);
}
cancel() {
this.router.navigate(['/home']);
}
}
export class EventCreate {
constructor(
public title: string,
public description: string,
public locationId: number,
public locationDetails: string,
public categoryId: number,
public isRegistrationRequired: boolean,
public eventDate: Date,
public startDateTime: Date,
public endDateTime: Date,
public maximumRegistrants: number,
) { }
}
<form>
<div class="form-group">
<label>Start Time:</label>
<input type="time" name="startDateTime" [(ngModel)]="startDateTime">
</div>
<div class="form-group">
<label>End Time:</label>
<input type="time" name="endDateTime" [(ngModel)]="endDateTime">
</div>
</form>
最佳答案
我知道有点晚了,但无论如何它可以帮助别人。输入类型“时间”输出您输入的时间的字符串表示形式。如果您的目标是从这个“时间”字符串中获取 typescript 日期对象(出于某些原因),我建议您查看输入类型 datetime-local然后将其值转换为 typescript Date 对象,如 new Date(your_input_value)
。
这是一个示例代码(我使用 react 形式和 Angular Material ):
<form [formGroup]="meetingForm" novalidate autocomplete="off">
.............. other input fields .....................
<input matInput
type="datetime-local"
placeholder="Start Time"
formControlName="meetingStartTime">
....................................
</form>
然后组件类的一部分将类似于此
.........other codes................
constructor(formBuilder:FormBuilder, ...){}
...............................
let meetingStartTimeFormControl = this.meetingForm.get('meetingStartTime') as FormControl;
this.startDateTime = new Date(this.meetingStartTimeFormControl.value);
console.log(this.startDateTime)
关于javascript - 让输入类型时间与 TypeScript 和 Angular2 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43742531/