angularangular-daterangepickerangular-bootstrap-calendar

Angular TypeScript how to assign Date


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>

Solution

  • 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);
      }
    }