Job
Job

Reputation: 485

Delay when updating form values with Angular 6

I've noticed that when I try to update a couple values in my FormBuilder right before submitting it with HTTPclient my values aren't updated. When I run the submit a 2nd time these values are updated.

private mergeDates(dateValue: string, timeValue: string): string {
  const returnValue = dateValue.toString().replace(' 00:00', ` ${timeValue}`);
  return returnValue;
}

private submitVacancy() {
  if (this.vacancyForm.invalid) {
    return;
  }
  const fValue = this.vacancyForm.value;
  const fControls = this.vacancyForm.controls;
  fControls['beginDateTime'].setValue(
    this.mergeDates(fValue['beginDate'], fValue['beginTime']),
  );
  fControls['endDateTime'].setValue(
    this.mergeDates(fValue['beginDate'], fValue['endTime']),
  );
  alert(JSON.stringify(fValue));
  this.http.post(`${this.apiUri}/addvacancy`, JSON.stringify(fValue));
}

Upvotes: 0

Views: 1263

Answers (1)

Job
Job

Reputation: 485

I added the following line to my code like Mateusz suggested and it now works fine. My code now looks like this.

private mergeDates(dateValue: string, timeValue: string): string {
  const returnValue = dateValue.toString().replace(' 00:00', ` ${timeValue}`);
  return returnValue;
}
private submitVacancy() {
  if (this.vacancyForm.invalid) {
    return;
  }

  const fControls = this.vacancyForm.controls;
  let fValue = this.vacancyForm.value;

  fControls['beginDateTime'].setValue(
    this.mergeDates(fValue['beginDate'], fValue['beginTime']),
  );

  fControls['endDateTime'].setValue(
    this.mergeDates(fValue['beginDate'], fValue['endTime']),
  );

  fValue = this.vacancyForm.value;
  alert(JSON.stringify(fValue));
  console.log(JSON.stringify(fValue));
  this.http.post(`${this.apiUri}/vacancy`, JSON.stringify(fValue));
}

I added fValue = this.vacancyForm.value; right after I run my setValue().

Upvotes: 1

Related Questions