16

I am wondering how I can set the Validator in the following form to Required, only if the form element is present:

<div *ngIf="form.controls.user.value !== 'Admin' && form.controls.user.value ">
        <label>Role:</label>
        <input type="text" ngControl="role">
</div>

And my form is:

       this.form = this._formBuilder.group({
        user: ['',Validators.required],
        role: ['', Validators.required]
    });
uksz
  • 18,239
  • 30
  • 94
  • 161
  • Looks to me like you'd need a custom form validation, maybe this helps you: https://medium.com/@daviddentoom/angular-2-form-validation-9b26f73fcb81#.y3kgieuwd – olsn Mar 17 '16 at 11:21

4 Answers4

20

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();
Unheilig
  • 16,196
  • 193
  • 68
  • 98
Christian
  • 2,676
  • 3
  • 15
  • 25
  • @thierry-templier response is good and general solution for this kind of problem, but this one better and more elegant for this special use case. – Nico Toub Sep 21 '17 at 12:48
  • this answer helped me a lot after struggling with validation problems. thanks a lot! – Kiss Koppány Apr 01 '20 at 16:34
  • Is it possible that validations are automatically disabled when they are within an HTML block which is not shown due to an *ngIf condition? – MikhailRatner Feb 08 '22 at 09:20
15

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:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
1

with in template it can be done this way -

<input [(ngModel)]="page.headerImageWidth" [required]="page.isHeaderAvailable">

Kavi
  • 176
  • 1
  • 12
0

You should do this.

  • In html add isVisible variable in *ngIf property

      <div *ngIf="isVisible && form.controls.user.value !== 'Admin' && form.controls.user.value ">
          <label>Role:</label>
          <input type="text" ngControl="role">
    
  • In .ts

    this.form = this._formBuilder.group({
          user: ['',Validators.required],
          role: ['', Validators.required]
      });
    
    
    
     if(this.form.controls.user.disabled == true){
      this.isVisible = false;
      }
      else {
      this.isVisible = true;
      }
    
Ken
  • 11
  • 3