Nick Hodges
Nick Hodges

Reputation: 17118

How can I tell if a <textarea> is empty in an Angular 8 application?

I have a text area like so:

<div class="form-group">
          <label for="form_message">Message * (Minimum if 15 characters)</label>
          <textarea
            id="form_message"
            required
            class="form-control"
            placeholder="Message *"
            rows="6"
            formControlName="form_message"
          ></textarea>
          <div
            *ngIf="
              form_message.invalid &&
              (form_message.dirty || form_message.touched)
            "
            class="alert alert-danger"
          >
            <div *ngIf="form_message.errors.minlength">
              Message must be at least 15 characters.
            </div>
          </div>
        </div>
      </div>

In the first *ngIf I would like to check to see if the length of the text in the <textarea> is greater than zero to prevent the red box from appearing with no text in it when the <textarea> is dirty, but the user has deleted all the text.

I used to do this with ngModel, but that has been deprecated.

How do I tell that a <textarea> has no text in it?

Upvotes: 0

Views: 1122

Answers (2)

Morlo Mbakop
Morlo Mbakop

Reputation: 3756

You can use ngModel for this use case

Template

<textarea
  id = "form_message"
  required
  class="form-control"
  placeholder = "Message *"
  rows = "6"
  formControlName = "form_message"

  [(ngModel)]="formMessage"
></textarea >

Component

let formMessage;

If you have a big form with many inputs, take a look at angular reactive forms

Upvotes: 2

igor_c
igor_c

Reputation: 1250

I think something like this.FORM_NAME.get('form_message').value.trim().length should do the trick.

Upvotes: 0

Related Questions