Home > database >  How to use *ngIf and conditional required together in angular?
How to use *ngIf and conditional required together in angular?

Time:10-07

<div class="p-field-checkbox">
    <p-checkbox formControlName="passwordUpdate" binary="false" name="passwordUpdate" inputId="passwordUpdate"></p-checkbox>
    <label for="passwordUpdate">Update Password</label>
</div>

<div class="input-group" *ngIf="form.get('passwordUpdate').value">
    <label class="required" for="password">Password</label>
    <input formControlName="password" type="password" name="password" placeholder="Password" id="password" class="input input-m" [required]="form.get('passwordUpdate').value">
</div>

if the condition is 'true', the password field appears. When the submit button is clicked the password field is validated for required.

then the condition is turned to 'false' but the required validation is not removed so the form is not able to get submitted. Kindly help me to sort this. Thanks in advance.

CodePudding user response:

You can disable the FormControl 'password' when the 'password Update' is false so that it is not involved in the validation of the form

you can add the below code in ngOnInit()

this.form.get('passwordUpdate').valuechange()
.subscrip(res => {
   if(res===true){
     this.form.get('password').enable();
   } else{
     this.form.get('password').disable();
   }
});

CodePudding user response:

As you are using ReactiveForms, we can add and remove validations based on the status of our "passwordUpdate"

<form [formGroup]="contactForm">
  <div>
    <label>Update Password</label>
    <input type="checkbox" formControlName="resetPassword" (change)="onCheckboxChange()" />
  </div>
  <div *ngIf="contactForm.get('resetPassword')?.value">
    <label for="last-name">Password: </label>
    <input type="text" formControlName="password">
    Required: {{ contactForm.get('password')?.hasError('required') }}
  </div>
  <div>
    <button type="submit">Submit</button>
    Valid Form : {{ contactForm.valid }}
  </div>
</form>

I have added "change" function which triggers a function in .ts file which resets the validation of "password" fields.

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  contactForm!: FormGroup;
  constructor(private formBuilder: FormBuilder) {
    this.createContactForm();
  }

  createContactForm() {
    this.contactForm = this.formBuilder.group({
      resetPassword: [],
      password: [],
    });
  }

  onCheckboxChange(): void {
    if (this.contactForm.controls['resetPassword'].value) {
      this.contactForm.get('password')?.setValidators([Validators.required]);
      this.contactForm.get('password')?.updateValueAndValidity();
    } else {
      this.contactForm.controls['password'].clearValidators();
      this.contactForm.get('password')?.updateValueAndValidity();
    }
  }
}

I have created a mock project of the same on stackblitz. please check it for reference.

  • Related