Angular ng-required

7.2k Views Asked by At

I've got my FormGroup with some FormControles and all of them are required but I want two of my FormControles only to be required if a boolean in my component.ts is true I tried ng-required="myboolean" but this didnt work. Is there a way to do this or a Workaround?

//edit

onButtonClick()
  {
    this.passwordFormControl = !this.passwordFormControl;

    if(this.passwordFormControl)
    {
      this.passwortButton = "Cancle change Password";
      this.benutzerAnlageForm.get('password').setValidators(Validators.required);
    }
    else
    {
      this.passwortButton = "Change password";
      this.benutzerAnlageForm.get('password').clearValidators();
    }
  }

 <form [formGroup]="MyForm" (ngSubmit)="onMyForm()">

  <div *ngIf="passwordFormControl" class = "form-group">
      <label for="password">Password</label>
      <input formControlName="password" type="password" id="password" 

 <-- Some more Form Controles that are always required -->

  <button type="submit" [disabled]="!MyForm.valid" class ="btn btn-primary">Save</button>
  <button *ngIf="edit" type="button" class="btn btn-primary" (click)="onButtonClick()">{{passwortButton}}</button>
  </form>

The Password FormControl is the Control I dont always want to be required. The Problem is if I remove the required from the password FormControl the Form itself and the Button doesnt seem to recognize that the form is now valid again.

2

There are 2 best solutions below

6
On BEST ANSWER

ng-required is for AngularJs that is 1.x. For Angular or Angular 2+ You can do this:

<input [required]="myboolean">

You can also do it dynamically in your component.ts when your boolean value changes, like this:

this.form.get('control-name').setValidators(Validators.required);
this.form.get('control-name').updateValueAndValidity();

To remove:

this.form.get('control-name').clearValidators();
this.form.get('control-name').setValidators(/*Rest of the validators if required*/);
this.form.get('control-name').updateValueAndValidity();
0
On
// To add validation     
   this.myForm.controls.controlName.setValidators(Validators.required);

// To clear validation
   this.updateForm.controls.controlName.clearValidators();

// In either case, call this method
   this.updateForm.controls.controlName.updateValueAndValidity();