Angular2 - 在反应形式上设置日期字段 [英] Angular2 - Setting date field on reactive form
问题描述
我有一个使用两个日期字段的组件,一个开始日期 &和结束日期.
I have a component that uses two date fields, a start date & and end date.
默认情况下,我禁用了结束日期字段,并在他们选择开始日期时切换它.
By default, I have my end date field disabled and I toggle it when they select a start date.
this.transitionForm = this.fb.group({
effectiveEndDate: [{ value: '', disabled: true }]
.....
});
我正在尝试在我的代码中设置此结束日期字段的值.
I am trying to set the value of this end date field within my code.
this.transitionForm.controls['effectiveEndDate'].setValue(this.utils.currentDate());
实用功能:
/**
* Returns the current date
*/
currentDate() {
const currentDate = new Date();
const day = currentDate.getDate();
const month = currentDate.getMonth() + 1;
const year = currentDate.getFullYear();
return month + "/" + day + "/" + year;
}
HTML:
<input type="date" class="form-control input-sm" id="effectiveEndDate" name="effectiveEndDate" placeholder="Required" formControlName="effectiveEndDate">
由于某种原因,该字段并未更新.
For some reason, the field is not getting updated though.
我也尝试过使用 PatchValue
并且也没有设置它.
I have also tried to use PatchValue
and that wasn't setting it either.
我错过了什么?
推荐答案
当您在 Chrome(其他浏览器未测试)中运行此代码时,它会向控制台记录错误:
When you run this code in Chrome (other browsers not tested) it logs an error to console:
指定的值7/26/2017"不符合要求的格式yyyy-MM-dd".
The specified value "7/26/2017" does not conform to the required format, "yyyy-MM-dd".
我认为这很好地描述了问题
Which I think describes the problem pretty well
您可以通过将 currentDate()
方法更改为以下内容来修复它:
You can fix it by changing your currentDate()
method to something like:
currentDate() {
const currentDate = new Date();
return currentDate.toISOString().substring(0,10);
}
虽然这确实解决了问题@JGFMK的答案显示了更好的方法使用 DatePipe
While this does fix the problem the answer from @JGFMK shows a better way of converting the date using a DatePipe
这篇关于Angular2 - 在反应形式上设置日期字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!