0

I have an Angular Reactive Form with an optional input. If the user enters nothing into the field and submits the field, the form sends '' (empty string) to the database. Is there a default Angular way to send 'null' to the database as the value of this field rather than an empty string (assuming there is no value entered in the field)?

1
  • 2
    when you are initializing your FormControl, give it null value. It should work. Commented Sep 16, 2022 at 6:04

2 Answers 2

1

I had a similar problem where in I had a textbox which when is empty had to be sent has null rather than empty string. I decided to create a directive in angular in which I used hostlistener to check if the value is empty string then reset it to null.

@Directive({
  selector: '[appEmptyToNull]'
})
export class EmptyToNullDirective {
  constructor(@Self() private ngControl: NgControl) { }

  @HostListener('keyup', ['$event']) onKeyDowns(event: KeyboardEvent) {
    if (this.ngControl.value?.trim() === '') {
      this.ngControl.reset(null);
    }
  }
}

And this in HTML you can use the directive like this

<input type="text" appEmptyToNull formControlName="firstname" />

This is can also be done using valueChanges property in Reactive form. You can check if the value of the form field is empty then reset it to null

this.form.get("firstname").valueChanges.subscribe((response: string)=> {
      console.log("valuechanges -> ",response)
      if (response?.length == 0) {
        this.form.get("firstname").setValue(null)
      }
    })

I don't know if this are right way to achieve it but these are 2 possible ways to do it.

Sign up to request clarification or add additional context in comments.

Comments

1

You can set a field value to null

this.someForm = this.fb.group({isbn: new FormControl(null, Validators.pattern(/^\d{10}$|^\d{13}$/)) })

If you dont want to send an empty string.

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.