Angular TypeScript how to assign Date

2.5k Views Asked by At

How can i bind date to date selector?

const TodayDate = "19-11-2020";
ngOnInit() {
  this._MyregisterForm = this.formBuilder.group({
    today_Date:[this.TodayDate, [Validators.required]]
  });
}

HTML

<form [formGroup]="_MyregisterForm" (ngSubmit)="onSubmit()">
  <input type="date" formControlName="today_Date" value="{{TodayDate}}">
</form>
5

There are 5 best solutions below

3
Krishna Rathore On BEST ANSWER

No need to put value attribute in input when are using formControlName

Stackblitz Demo

component.html

<form [formGroup]="_MyregisterForm" (ngSubmit)="onSubmit()">
    <input type="date" formControlName="today_Date">
    <button type="submit">Submit</button>
</form>

component.ts

import { Component, VERSION } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { DatePipe } from "@angular/common";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
  providers: [DatePipe]
})
export class AppComponent {
  _MyregisterForm: FormGroup;
  TodayDate = "19-11-2020";

  constructor(private formBuilder: FormBuilder, private datePipe: DatePipe) {
    this._MyregisterForm = this.formBuilder.group({
      today_Date: [this.getTransformedDate(this.TodayDate), Validators.required]
    });
  }

  private getTransformedDate(date) {
    let date1 = date.split("-");
    let newDate = date1[2] + "-" + date1[1] + "-" + date1[0];
    return newDate;
  }

  onSubmit() {
    const date = this.datePipe.transform(
      this._MyregisterForm.get("today_Date").value,
      "dd-MM-yyyy"
    );
    alert(date);
  }
}
1
elzoy On

Remove value="{{TodayDate }}" You're binding a control with TodayDate value and that's enough.

0
Leon Radley On

I would try to keep the dates as javascript dates in your app. It will make it easier to format them differently and use them with angular materials date picker.

use the library date-fns to parse the string into a date.

https://date-fns.org/v2.16.1/docs/parse

Then pass that date into the formBuilder.

0
Emilien On

I provide a Stackblitz just here.

The date format is not good, you need to use International format. Moreover, like everyone said, you don't need to bind a value.

_MyregisterForm: FormGroup;
TodayDate = "2020-12-10";

constructor(private formBuilder: FormBuilder) {
  this._MyregisterForm = this.formBuilder.group({
    today_Date: [this.TodayDate, Validators.required]
  });
}
<form [formGroup]="_MyregisterForm">
    <input type="date" formControlName="today_Date">
</form>
<pre>{{ _MyregisterForm.value | json }}</pre>
0
tozlu On

TodayDate should be;

TodayDate = new Date();

and remove value attribute from input