0

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>
Waldi
  • 39,242
  • 6
  • 30
  • 78

5 Answers5

0

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

elzoy
  • 5,237
  • 11
  • 40
  • 65
0

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.

Leon Radley
  • 7,596
  • 5
  • 35
  • 54
0

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);
  }
}
Krishna Rathore
  • 9,389
  • 5
  • 24
  • 48
0

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>
Emilien
  • 2,701
  • 4
  • 15
  • 25
0

TodayDate should be;

TodayDate = new Date();

and remove value attribute from input

tozlu
  • 4,667
  • 3
  • 30
  • 44