0

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

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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.

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.