Ionic DateTime 错误:无法读取未定义的属性“toISOString”
2021-04-30
2545
我想将当前日期显示为默认值,如果我使用 formControlName 则不起作用,但我需要使用 formControlName。
这是我的 HTML 文件
<ion-item>
<ion-label color="primary"> Start date </ion-label>
<ion-datetime [value]="startDate.toISOString()" formControlName="startDate" required></ion-datetime>
</ion-item>
<div id="startDateErrorMessage" *ngIf="newProjForm.controls['startDate'].invalid &(newProjForm.controls['startDate'].dirty || newProjForm.controls['startDate'].touched)">
<span class="error ion-padding" *ngIf="newProjForm.controls['startDate'].errors.required"> Date is required </span>
</div>
这是我的 TS 文件
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
import { AlertController } from '@ionic/angular';
@Component({
selector: 'app-new-project',
templateUrl: './new-project.page.html',
styleUrls: ['./new-project.page.scss'],
})
export class NewProjectPage implements OnInit {
newProjForm: FormGroup;
startDate: Date = new Date();
constructor(private formBuilder: FormBuilder, private alertCtrl: AlertController) { }
ngOnInit() {
this.newProjForm = this.formBuilder.group({
startDate: ['' ,[Validators.required]]
});
}
}
当我编译项目时出现此错误
“ ERROR 错误:未捕获(在承诺中):TypeError:无法读取未定义的属性‘toISOString’ ”
“ TypeError:无法读取未定义的属性‘toISOString’ ”
有人可以指出我正确的方向吗?
2个回答
若要设置表单生成器对象中的初始值,请不要在 html 模板中使用 [value]。您可以将 '' 替换为字段的初始值,例如:
this.newProjForm = this.formBuilder.group({
startDate: [(new Date()).toISOString(), [Validators.required]] –
});
C. Gäking
2021-05-04
由于时间显示不正确而导致的错误。您正在寻找的答案:
// html:
<ion-datetime cancelText="отмена" doneText="Готово" [(ngModel)]="today" displayFormat="D MMM YYYY H:mm"
min="{{min_data}}" max="{{max_data}}" value="2021-11-15T11:00Z" monthShortNames="Январь, Февраль, Март, Апрель, Май, Июнь, Июль, Август, Сентябрь, Октябрь, Ноябрь, Декабрь">
</ion-datetime>
// ts:
today: any
min_data = ''
max_data = ''
pad(s, width, character) {
return new Array(width - s.toString().length + 1).join(character) + s;
}
ngOnInit() {
this.today = new Date()
var numberOfDaysToAdd = 5 // increase by 5 days from today
this.today.setDate(this.today.getDate() + numberOfDaysToAdd)
this.min_data = this.today.getFullYear()+'-'+this.pad(this.today.getMonth() + 1, 2, '0')+'-'+this.pad(this.today.getDate(), 2, '0')
this.max_data = (this.today.getFullYear()+1)+'-'+this.pad(this.today.getMonth() + 1, 2, '0')+'-'+this.pad(this.today.getDate(), 2, '0')
this.today = this.today.getFullYear()+'-'+this.pad(this.today.getMonth() + 1, 2, '0')+'-'+this.pad(this.today.getDate(), 2, '0') + ' 18:00'
}
user391679
2021-10-22