How to set Validator to required if visible?
In your case, you would create a global validator. Something like this:
this.form = this._formBuilder.group({
user: ['', Validators.required],
role: ['']
}, { validator: (group) => {
if (group.controls.user.value !== 'Admin') {
return Validators.required((group.controls.role);
}
return null;
}});
In this case, the form is valid (this.form.valid === true) in the following case:
- user is not empty, is different of
Admin
and the role isn't empty - user is
Admin
See this plunkr: https://plnkr.co/edit/UKyRiq?p=preview.
See this question for more details:
- Cross field validation in Angular2
You can use the disable()
and enable()
functions. When a form control is disabled, validation is not applied to that control.
this.form.controls.user.disable();
this.form.controls.role.disable();
with in template it can be done this way -
<input [(ngModel)]="page.headerImageWidth" [required]="page.isHeaderAvailable">