Home > OS >  how to get date from form control
how to get date from form control

Time:10-28

html

<form [formGroup]="searchForm" (ngSubmit)="search()">
  <div >
    <div >
      <input type="date"  formControlName="startDate" >
    </div>
    <div >
      <input type="date"  formControlName="endDate" >
    </div>
    <div >
      <button type="submit" >Submit</button>
    </div>
  </div>
</form>

ts.

  searchForm = new FormGroup({
      startDate: new FormControl(),
      endDate: new FormControl(),
    }
  );

i want this date ex. '2022-12-31'

but this output is

console.log(this.searchForm.value.startDate) Output : 2022-12-31

i try startDate = new Date(this.searchForm.value.startDate)
but Output is 1970-01-01T00:00:00

CodePudding user response:

You get YYYY-MM-DD string or empty string from the input with type date. See <input type="date">

For the empty string it will default to January 1, 1970, 00:00:00 UTC (the ECMAScript epoch). See Date() constructor

const dateEmpty = new Date(“”);
const dateFromString = new Date(“2022-12-31”);
   
console.log(dateEmpty);
console.log(dateFromString);

How to handle the case when user hasn’t put a date is up to you. For example you could force input via validation Validators.required and prevent user from submitting form until they have done so or alternatively you could map to a Date | null TypeScript type where null signifies not provided.

CodePudding user response:

As a input type date return an string (and is feed by a string) you can use two functions

formatDate(date:any):string|null{
  if (date)
     return date.getFullYear() '-' 
            ('00' (date.getMonth() 1)).slice(-2) '-' 
            ('00' date.getDate()).slice(-2)
  return null
}
parseDate(value:string|null):any{
  if (value)
     return new Date(value)
  return null;
}

Then, instead use formControl we can use ngModel and ngModelChange

<form [formGroup]="searchForm" (ngSubmit)="search()">
      <input type="date"  
          [ngModel]="formatDate(searchForm.get('startDate').value)"
          (ngModelChange)="searchForm.get('startDate').setValue(parseDate($event))"
         [ngModelOptions]="{standalone:true}"
 >
 ...
</form>

a stackblitz

  • Related