My project written in Angular 10. I have a component that has a simple form with 3 inputs: name, email, phone number.
I need to check the input of the forms for this purpose I use Angular reactive forms.
Here the template (for simplicity I removed email and phone number sections):
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()" class="myForm">
<div class="contact-container">
<div class="field">
<div class="field">
<p class="control has-icons-left has-icons-right">
<input class="input" type="text" placeholder="Full Name" formControlName="name">
<span class="icon is-small is-left">
<i class="fas fa-user"></i>
</span>
</p>
<span *ngIf="(name.dirty || name.touched) && name.invalid && name.errors.required" class="error">
*Name is required.
</span>
<span *ngIf="(name.dirty || name.touched ) && name.errors.minlength" class="error">
*Name must be greater than 2 characters.
</span>
</div>
<input class="send-button" type="button" [disabled]="!contactForm.valid" [ngClass]="{'notClickable': !contactForm.valid}" value="send">
</div>
</form>
And here is TypeScript for the component:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-contact-form',
templateUrl: './contact-form.component.html',
styleUrls: ['./contact-form.component.scss']
})
export class ContactFormComponent implements OnInit {
constructor() {
this.contactForm = this.createFormGroup();
}
get name() {
return this.contactForm.get('name');
}
get phone() {
return this.contactForm.get('phone');
}
get email() {
return this.contactForm.get('email');
}
contactForm: FormGroup;
ngOnInit(): void {}
createFormGroup() {
return new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(2)]),
email: new FormControl('', [Validators.required, Validators.email]),
phone: new FormControl('', [Validators.required])
});
}
onSubmit() {}
}
When I start to print the name and the first character added in the input box the message is showed:
Name must be greater than 2 characters
and that is OK.
But when the second and third characters added the message is not hidden. Because of the Validators.minLength(2)
I expect that after the second character is added to the input box the message will be hidden.
Any idea why message does not hide when the second character added to the input box?
Aucun commentaire:
Enregistrer un commentaire