1

I have the following field in an angular2 page (I am not using forms).

<input id="firstname" name="firstname" class="field-input field-validation-input" [(ngModel)]="firstname"
                    placeholder="First name" spellcheck="false" required #firstNameField>

Now I want to display a message at the bottom of the field if it is invalid, in this scenario if it is empty. What is the best way to do this, I can use firstNameField.className but as you can see there are a number of classes here and trying to filter for ng-invalid might be a problem

2 Answers 2

4

Use

#firstNameField="ngModel"

so that this template variable references the NgModel directive, and thus have access to all its properties and methods:

<div *ngIf="!firstNameField.valid">Houston, we have a problem</div>

or

<div *ngIf="firstNameField.hasError('required')">The first name is required</div>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for this.
0

Why not use a form and Angular's built in validation features?

Without forms, you could write some code in the setter for the firstname field that performs the validation and sets the message. You could then add the elements to display the message if the message is set.

In the component:

   message: string;
   _firstName: string;
   get firstName(): string {
      return this._firstName;
   }
   set firstName(value: string) {
      this._firstName = value;
      // Validation here
      // If validation does not pass
      {
         message = "Please enter a valid value";
      }
   }

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.