Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mreis1/3764dc71d56040811ee80a2f301de956 to your computer and use it in GitHub Desktop.
Save mreis1/3764dc71d56040811ee80a2f301de956 to your computer and use it in GitHub Desktop.
How to update reactive form validators programatically?
emailRequired = false;
ngOnInit() {
this.participantForm = this.formBuilder.group({
firstName: '',
lastName: '',
email: ['', [Validators.email, Validators.required]],
sms: null,
places: 1,
shareCode: '',
});
}
toggleRequire(toggleOn: boolean) {
this.emailRequired = toggleOn;
const email = this.participantForm
.get('email');
email.setValidators(
this.emailRequired
? [Validators.email, Validators.required]
: [Validators.email]
);
email.updateValueAndValidity(); // Propagate the form validity to "this.participantForm.invalid "
}
<ion-input
class="form__control participant__form__input"
formControlName="email"
type="text"
ngDefaultControl
[ngClass]="{
'is-invalid': participantForm.get('email').dirty && participantForm.get('email').errors
}"
>
</ion-input>
<div
*ngIf="participantForm.get('email').dirty && participantForm.get('email').errors"
class="invalid-feedback"
>
<div
*ngIf="participantForm.get('email').errors.required"
>
{{"THIS_FIELD_IS_REQUIRED"|translate}}
</div>
<div *ngIf="participantForm.get('email').errors.email">
{{"INVALID_EMAIL"|translate}}
</div>
</div>
<div>
<button (click)="toggleRequire(!emailRequired)">Toggle required</button>
{{participantForm.invalid | json}}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment