Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

angular - 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());

Utility Function:

/**
 * 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.

I have also tried to use PatchValue and that wasn't setting it either.

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you run this code in Chrome (other browsers not tested) it logs an error to console:

The specified value "7/26/2017" does not conform to the required format, "yyyy-MM-dd".

Which I think describes the problem pretty well

You can fix it by changing your currentDate() method to something like:

currentDate() {
  const currentDate = new Date();
  return currentDate.toISOString().substring(0,10);
}

Live plunker example

While this does fix the problem the answer from @JGFMK shows a better way of converting the date using a DatePipe


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...