FormControl - empty string to null

Viewed 2660

is there a possibility to convert a empty string (equals "") to null?

I've an input field to override a value in the DB. If i change the value there, it will be stored in the DB - which is great. But if I edit the value (input field) again and remove the text from it, it sends an empty string (eg "") to the DB. But it should send null that the source value will be displayed.

app.component.ts

  readonly titleCtrl = new FormControl()
  readonly descriptionCtrl = new FormControl()
  readonly ageCtrl = new FormControl()

  readonly formGroup = new FormGroup({
    title: this.titleCtrl,
    description: this.descriptionCtrl,
    age: this.ageCtrl,
  })


private fillForm(item: Item): void {
  this.formGroup.setValue(
    {
      title: item.title.overrideValue,
      description: item.description.overrideValue,
      age: item.age.overrideValue,
    },
    { emitEvent: false },
  )
}

So what I'd like to reach is if I change something in title, and delete it again, it should be null instead "".

Is there something possible with valueChanges?

1 Answers
sanitizeDataBeforeSendToServer(): void {
    const control = this.form.get('nameControl');    
    
    if ((control.value as string)?.trim() === '') {
        control.setValue(null);
    }
}
    
save(): void {
    this.sanitizeDataBeforeSendToServer();
    ....
}
Related