Issue
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();
}
}
I am getting validation error eventhough I am not even setting a focus on that field.
Any idea?
Thanks
Solution
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.
Answered By - Tanner
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.