Angular2 - Reactive Install Date Field

I have a component that uses two date fields, a start date and an end date.

By default, my end date field is disabled, and I switch it when they select the start date.

this.transitionForm = this.fb.group({
 effectiveEndDate: [{ value: '', disabled: true }]
 ..... 
});

I am trying to set the value of this end date field in my code.

this.transitionForm.controls['effectiveEndDate'].setValue(this.utils.currentDate());

Useful feature:

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

I also tried to use PatchValue, and this also did not install.

What am I missing?

+4
source share
2 answers

When this code is run in Chrome (other browsers have not been tested), it logs an error for the console:

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

,

, currentDate() - :

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

Live plunker

@JGFMK DatePipe

+2

FormBuilder.group FormGroup:
https://angular.io/api/forms/FormBuilder#group
https://angular.io/api/forms/FormGroup#setValue

:

  • Angular Typescript .
  • : navigator.language.
  • Angular.
  • Date Pipe docs .

import {DatePipe} from '@angular/common'
...
let dp = new DatePipe(navigator.language);
let p = 'y-MM-dd'; // YYYY-MM-DD
let dtr = dp.transform(new Date(), p);
this.transitionForm.setValue({effectiveEndDate: dtr}); 

Plunker ( reset)

+6

Source: https://habr.com/ru/post/1682324/


All Articles