I want to output from the JSON the date in the input field of the mat-datepicker. When I run the output I always get the current year. I am working with ReactiveForms. What am I doing wrong?
My code:
// JSON
{
"success": true,
"mandant": {
"mandantId": 2,
"firm": "Test GmbH",
"street": "Test-Street",
"number": "2",
"zip": "5xxxx",
"city": "Exxxxxxxx",
"country": "Germany",
"financial_year_start": "Jan. 1, 2020" // This is to be output in the input
}
}
// TS
public getFiscalYearStart: string;
ngOnInit() {
// To initialize forms
this.initForm();
// To initialize loadFinancialYearStart
this.loadFinancialYearStart();
}
// Creation of the settingsContentForm
private initForm() {
// General
this.settingsContentForm = this.formBuilder.group({
financial_year_start: new FormControl(moment(this.getFiscalYearStart), Validators.required),
});
}
/**
* Fill the datePicker with data
*/
loadFinancialYearStart() {
this.userAreaService.getCurrentMandantData().subscribe(resp => {
this.getFiscalYearStart = resp.mandant.financial_year_start;
console.log(this.getFiscalYearStart); // Correct year is displayed in the console
});
}
Do it in two steps
1
) parse the string into aDate Object
with the date parse function,2
) then set it to your Date PickerTo parse the string into a date format use the
Date.parse()
helper from MDN with a date format example of what your JSON string will send.Just to be sure, I would check if its in value, or in the object
You can also do it with the date constructor, but first convert that String date into a Date object using the Date constructor: