Last active
December 22, 2020 09:18
-
-
Save mreis1/3764dc71d56040811ee80a2f301de956 to your computer and use it in GitHub Desktop.
How to update reactive form validators programatically?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 " | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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