2

I have an Angular Material datepicker. I have formatted the date as I wish but now I can't figure out how to send the string which is in the form to the backend.

My html:

<mat-form-field>
    <input matInput [formControl]="date" [matDatepicker]="dp" placeholder="Fill in a date">
    <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
    <mat-datepicker #dp></mat-datepicker>
</mat-form-field>

My ts:

export const MY_FORMATS = {
  parse: {
    dateInput: 'LL',
  },
  display: {
    dateInput: 'YYYY-MM-DD',
    monthYearLabel: 'YYYY',
    dateA11yLabel: 'LL',
    monthYearA11yLabel: 'YYYY',
  },
};


@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss'],
  providers: [
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    {provide: MAT_DATE_FORMATS, useValue: MY_FORMATS, },
  ],
})

export class SearchComponent implements OnInit {

  flightIDInput = new FormControl('WZZ1BW')
  date = new FormControl("");


  constructor(private dataMessageService: DataMessagesService) { }

  ngOnInit() {
  }

  getMessages() {
    console.log(this.date.value);
    });
  }
}

The value in my form is written as 2019-10-18, but when i call it with this.date or this.date.value it returns this massive object. How can I send the string "2019-10-18" to my backend?

9
  • The object has year, month and day attributes. You can extract them with getDay() and so on. Commented Oct 18, 2019 at 11:37
  • I'm not able to find these options. How would I do that? Commented Oct 18, 2019 at 11:44
  • See here stackoverflow.com/questions/37516825/… Commented Oct 18, 2019 at 11:53
  • I'm sorry I don't see how that answers my question Commented Oct 18, 2019 at 11:58
  • Try this.date.getDate(), this.date.getYear(), this.date.getMonth() - does that work? Commented Oct 18, 2019 at 12:06

1 Answer 1

1

You can format your date value by passing it into the below function in TS...

formatDate(date) {
  var d = new Date(date),
  month = '' + (d.getMonth() + 1),
  day = '' + d.getDate(),
  year = d.getFullYear();

if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;

return [year, month, day].join('-');}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.