问题描述
限时送ChatGPT账号..我正在尝试随时间设置 datepicker 控件的值.无法完成
尝试转换为所需格式
appponent.html
:
appponent.ts
:
ngOnInit() {this.loginForm = this.formBuilder.group({查询日期 : ['']})让日期=新日期()日期 = date.toLocaleDateString().substring(0,10)this.loginForm.get('requestdate').patchValue(date)}
无法看到转换后的日期
解决方案您在重新分配 date
变量时似乎使用了错误的语法.由于它被初始化为 Date
,它不会接受你提供它的格式的字符串.你必须使用 YYYY-MM-DD
代码> 格式.
试试这个:
import { Component } from '@angular/core';从 '@angular/forms' 导入 { FormBuilder, FormGroup };@成分({选择器:'我的应用',templateUrl: './appponent.html',styleUrls: ['./appponent.css']})导出类 AppComponent {登录表单:表单组;构造函数(私有表单构建器:FormBuilder) { }ngOnInit() {this.loginForm = this.formBuilder.group({查询日期: ['']})this.loginForm.get('requestdate').patchValue(this.formatDate(new Date()));}私人格式日期(日期){const d = 新日期(日期);让月 = '' + (d.getMonth() + 1);让天 = '' + d.getDate();const 年 = d.getFullYear();if (month.length <2) 月 = '0' + 月;if (day.length <2) day = '0' + day;return [年、月、日].join('-');}}
不要忘记将 input
字段包裹在 form
标记周围,并将 formGroup
属性设置为 loginForm
:
<小时><块引用>
这是一个工作示例 StackBlitz 供您参考.
I'm trying to set the value of the datepicker control with time. Not able to accomplish
Tried converting to desired format
appponent.html
:
<input id="requestdate" type="date" class="form-control" formControlName="requestdate"
appponent.ts
:
ngOnInit() {
this.loginForm = this.formBuilder.group({
requestdate : ['']
})
let date = new Date()
date = date.toLocaleDateString().substring(0,10)
this.loginForm.get('requestdate').patchValue(date)
}
Not able to see the transformed date
解决方案You seem to have used the wrong syntax while reassigning the date
variable. Since it was initialized as a Date
, it won't accept a string in the format that you're supplying it in. You'll have to use the YYYY-MM-DD
format.
Try this:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './appponent.html',
styleUrls: ['./appponent.css']
})
export class AppComponent {
loginForm: FormGroup;
constructor(
private formBuilder: FormBuilder
) { }
ngOnInit() {
this.loginForm = this.formBuilder.group({
requestdate: ['']
})
this.loginForm.get('requestdate').patchValue(this.formatDate(new Date()));
}
private formatDate(date) {
const d = new Date(date);
let month = '' + (d.getMonth() + 1);
let day = '' + d.getDate();
const year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
}
Don't forget to wrap the input
field around a form
tag with formGroup
attribute set to loginForm
:
<form [formGroup]="loginForm">
<input
id="requestdate"
type="date"
class="form-control"
formControlName="requestdate" />
</form>
Here's a Working Sample StackBlitz for your ref.
这篇关于如何使用 patchValue 以角度反应形式设置日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论