0

In my component I pass the following values to the controls. The value I pass are both of type date.

this.form.controls["DepartureDate"].setValue(this.flightChoice.departureDate);
this.form.controls["ReturnDate"].setValue(this.flightChoice.returnDate);

The controls are of type Text because if I use type date the value are not written at all.

<input class="form-control" formControlName="DepartureDate" type="text" id="departureDate" />
<input class="form-control" formControlName="ReturnDate" type="text" id="returnDate" />

Now the result of passing the values is: a date such this: 2018-06-30T00:00:00+02:00 when I would like a date such: 30-06-2018 What can I do to have this kind of value and also why using the input of type date will not accept my values?

Tharindu Lakshan
  • 3,995
  • 6
  • 24
  • 44
user1238784
  • 2,250
  • 3
  • 22
  • 41

1 Answers1

0

Here is your solution

import { Component } from '@angular/core';
import { FormGroup, FormBuilder, } from '@angular/forms';
import moment from 'moment';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular 6';
  dateForm: FormGroup;
  depDate: any;
  retDate: any

  constructor(private fb: FormBuilder) {
    this.createDateForm();
  }

  createDateForm() {
    this.dateForm = this.fb.group({
      DepartureDate: null,
      ReturnDate: null
    });
  }

  chageDepartureDate() {
    this.depDate = moment(this.dateForm.get('DepartureDate').value).format("DD-MM-YYYY");
  }

  changeReturnDate(event) {
    this.retDate = moment(this.dateForm.get('ReturnDate').value).format("DD-MM-YYYY");

  }
});

  }
}

HTML:

<form [formGroup]="dateForm">
    <p>Departure Date</p>
    <input (change)="chageDepartureDate($event)" type="date" formControlName="DepartureDate" placeholder="choose departure date">
    <p>Return Date</p>
    <input (change)="changeReturnDate($event)" type="date" formControlName="ReturnDate" placeholder="choose departure date">
</form>

<p>Departure Date = {{depDate}}</p>
<p>Return Date = {{retDate}}</p>
Akj
  • 7,038
  • 3
  • 28
  • 40