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

Categories

0 votes
1.5k 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...