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)?
2 Answers
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.
FormControl, give it null value. It should work.