Mark
Mark

Reputation: 4950

Angular form - field validation

I have this code:

form [formGroup]="form">
  <input formControlName="name">
  <span *ngIf="form.controls.name.invalid">1234</span>
  <button #myButton></button>
</form>

and Component:

import { Component, Inject, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { DOCUMENT } from '@angular/common';


@Component({
   selector: 'my-app',
   templateUrl: './app.component.html',
   styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  constructor(
   @Inject(DOCUMENT) private document: Document) {

}
form = new FormGroup({
  name: new FormControl('', [Validators.required])
});


ngOnInit() {    
  document.getElementById('myButton').focus();
}
}

Sample

I am getting validation error eventhough I am not even setting a focus on that field.

Any idea?

Thanks

Upvotes: 0

Views: 38

Answers (2)

Volodymyr Herchuk
Volodymyr Herchuk

Reputation: 46

Field is required and it's not filled, therefor it's invalid, so you see an error. to achieve result that you want (I presume display error only after focus) you can do smth like:

*ngIf="form.controls.name.invalid && form.touched"

Upvotes: 2

Tanner
Tanner

Reputation: 2411

The field is invalid; it has no value and you've specified that it's required.

If you only want to show the error when it's invalid and touched, add && form.controls.name.touched to your ngIf.

Upvotes: 1

Related Questions