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屋!