Angular: how to set input of time type to current time on initialization

久未见 提交于 2019-12-11 16:02:32

问题


I have created time and date input form with FormBuilder and created working html interface

(create.component.html):

<form [formGroup]="createForm" class="create-form">
  <mat-form-field class="field-full-width">
      <input matInput type="time" placeholder="Time of activity" formControlName="time" #time/>
  </mat-form-field>
  <mat-form-field class="field-full-width">
    <input matInput [matDatepicker]="dp" formControlName="date" #date>
    <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
    <mat-datepicker #dp></mat-datepicker>
  </mat-form-field>
  (...)

I've tried to set date here (create.component.ts):

createForm: FormGroup;

constructor(private entryService: EntryService, private fb: FormBuilder, private router: Router) {
this.createForm = this.fb.group({
  time: ['', Validators.required],
  date: ['', Validators.required],
});
}
ngOnInit() {
  this.createForm.patchValue({
    date: new Date(),
    time: new Date()
  });
}

With good result in DatePicker but not in time input:

How can I set and display current time on initialization of form?


回答1:


The desired format is string like HH:mm therefore input of time type is set this way:

ngOnInit() {
  this.createForm.patchValue({
    date: new Date(),
    time: new Date().getHours() + ':' + new Date().getMinutes()
  });
}


来源:https://stackoverflow.com/questions/51483479/angular-how-to-set-input-of-time-type-to-current-time-on-initialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!