Issue
in reactive form hasValidator functions does not work when use with Validators.compose
I want to display "*" if the formcontroller is required
import { Component, VERSION } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
constructor(private fb: FormBuilder) {}
profileForm = this.fb.group({
firstName: [
'',
Validators.compose([Validators.required, Validators.max(3)]),
],
lastName: [''],
});
isFieldMandatory(name: string) {
return (
this.profileForm.get(name)?.hasValidator(Validators.required) ?? false
);
}
}
<fieldset>
<form [formGroup]="profileForm">
<label for="first-name"
>First Name: <span *ngIf="isFieldMandatory('firstName')">*</span></label
>
<input id="first-name" type="text" formControlName="firstName" />
<span>
{{ profileForm.get('firstName').errors | json }}
</span>
<br />
<label for="last-name"
>Last Name: <span *ngIf="isFieldMandatory('lastName')">*</span>
</label>
<input id="last-name" type="text" formControlName="lastName" />
<span>
{{ profileForm.get('lastName').errors | json }}
</span>
</form>
</fieldset>
<p>Form Status: {{ profileForm.status }}</p>
Solution
Validators.compose() Compose multiple validators into a single function that returns the union of the individual error maps for the provided control
so validation array should change as follows
profileForm = this.fb.group({
firstName: [
'',
[Validators.required, Validators.max(3)],
],
lastName: [''],
});
if you really want to use Validators.compose()
isFieldMandatory(name: string) {
return this.profileForm.get(name)?.errors?.required ?? false;
}
Answered By - Indrakumara
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.