Home > Blockchain >  Angular form - field validation
Angular form - field validation

Time:10-13

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

CodePudding user response:

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"

CodePudding user response:

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.

  • Related