2

I've a bunch of textareas being generated by a loop, and while I can set the initial values to null, if a user types text then deletes it, the value reverts back to an empty string.

My html:

<form #reviewForm="ngForm" (ngSubmit)="onReviewFormSubmit(reviewForm.value)">
...
  <textarea (input)="value = $event.target.value"
            [name]="comments" [ngModel]="defaultValue"
            id="{{'comments-'+i}}"
            placeholder="Comments"></textarea>
...
</form>

My component:

defaultValue: string = null;

The json object requires either a string value for the comments or else null. I set it to null initially with defaultValue, when a user types I get a string value, but once they empty out the textarea it reverts back to "".

How would I go about setting the empty string state to null?

3 Answers 3

1

You could try something like the following, calling a function on input event.

Though it might be easier to catch the values when you submit the form?

<textarea (input)="value = calculateValue($event.target.value)"  
          [name]="comments" [ngModel]="defaultValue"
          id="{{'comments-'+i}}"
          placeholder="Comments"></textarea>
calculateValue(e) {
    if(e == '') {
        return null
    } 
    return e
}
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work unfortunately. I still get an empty string.
To clarify, it does set the value to null, but as it's part of a loop of textareas in a form the form submit doesn't know the value has been set. How would I assign this null value back to the textarea for my form to later catch and submit?
1

The value null represents the intentional absence of any object value.

[ngModel] don't differentiate between null and blank while posting.

See you bind the control with nulll and post, it returns blank ''

Same thing will happen when you bind with blank, because it return the string.

Another example, you bind with some text say 'example' but user delete that and post the page, what will you expect to get, obviously blank.

If you want to handle blank to null then you need to see this

Comments

1

I think, you can just reset a value to null right before sending a form. In your onReviewFormSubmit method, you could add an if, which checks if value is an empty string and if it is, set this specific value to null.

 if (value.name === '') {
     value.name = null;
 }

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.