Implementing conditional requirements using *ngIf in Angular: A step-by-step guide

<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 will appear. Upon clicking the submit button, the password field will be validated for being required.

However, once the condition turns false, the required validation remains, preventing the form from being submitted. Can someone please assist me with resolving this issue? Thank you in advance.

Answer №1

Utilizing ReactiveForms allows for the dynamic addition and removal of validations depending on the state of the "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>

A new function called "change" has been incorporated to trigger an action in the .ts file that resets password field validations.

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();
    }
  }
}

To see a demo version of this implementation, visit stackblitz. Take a look for more information.

Answer №2

To ensure that the FormControl 'password' is excluded from form validation when the 'password Update' is false, you can implement the following solution:

Simply insert the provided code snippet within the ngOnInit() method of your component:

this.form.get('passwordUpdate').valueChanges()
.subscribe(result => {
   if(result === true){
     this.form.get('password').enable();
   } else{
     this.form.get('password').disable();
   }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a mechanism in the API to ensure that only positive values greater than or equal to 0 are accepted

My goal is to process the API result and filter out any values less than 0. I've attempted to implement this feature, but so far without success: private handleChart(data: Object): void { const series = []; for (const [key, value] of Object.e ...

Navigating with the router on a different page

My appcomponent contains all the routes, and on the next page I have several links that are supposed to route to the same router outlet. How can I navigate when a link is clicked? I attempted using [routerLink]="['PersonInvolved']", but I encoun ...

The Angular directive ng-if does not function properly when trying to evaluate if array[0] is equal to the string value 'Value'

In my code, I want to ensure that the icon is only visible if the value at array index 0 is equal to 'Value': HTML <ion-icon *ngIf="allFamily[0] === 'Value'" class="checkas" name="checkmark"></ion-icon> TS allFamily = [ ...

I am having trouble getting my angular library published successfully

I'm facing an issue while trying to publish my angular package. I keep encountering this error. https://i.stack.imgur.com/nhYMY.png Here is a screenshot of my package.json file https://i.stack.imgur.com/mWsin.png. ...

Struggling with "Content" not being recognized in Typescript PouchDB transpilation errors?

I have been diligently working on an Ionic app for the past three months with no major issues during development or deployment to mobile devices. However, yesterday I encountered a frustrating NPM dependency problem while trying to deploy to mobile. In an ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

The module 'AnotherModule' in a different file has unexpectedly imported a value 'Module in file'. Make sure to include a @NgModule annotation to resolve this issue

After struggling with this problem for the past four days, I've exhausted all resources on Stack Overflow and Google. Hopefully, someone here can provide some insight. I have two Angular 11 libraries - one core and the other called components. Compone ...

What is the best way to retrieve specific data based on their unique identifier?

Imagine having a table like this, with the following data: Id , Name , IsBillable 1 One 1 2 two 0 3. three 0 I have stored this data in a variable called masterData using the get method, and I am using it to populate a dropdown me ...

The type definition file for 'node' cannot be located

I've encountered some unusual errors after updating angular, webpack, and typescript. Any suggestions on what might be causing this? When I attempt to run the application with npm start, I'm seeing the following errors: [at-loader] Cannot find ...

TypeScript Interfaces: A Guide to Defining and

In my angular2 application, I have created interfaces for various components. One of these interfaces is specifically for products that are fetched from a remote API. Here is the interface: export interface Product { id: number; name: string; } ...

You cannot assign an array of 'Contact' objects to a single 'Contact' parameter

During the development process, I encountered an error while trying to add a new contact. The error message states: Error: src/app/contacts/contacts.component.ts:32:28 - error TS2345: Argument of type 'Contact[]' is not assignable to parameter o ...

The Step-by-Step Guide to Deselecting an Angular Checkbox with a Button

I currently have a situation where I have three checkboxes labeled as parent 1, parent 2, and parent 3. Initially, when the page loads, parent 1 and parent 3 are checked by default, while parent 2 is unchecked. However, when I manually check parent 2 and c ...

The error message "ng2-test-seed cannot be found - file or directory does not exist"

I've been attempting to work with an angular2 seed project, but I'm encountering some challenges. https://github.com/juliemr/ng2-test-seed When I run the command: npm run build I encounter the following error: cp: cannot stat ‘src/{index.h ...

Tips for sending arguments up in Angular2

I need to supply an argument to a function. <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> It's crucial for me, as I have ...

Include the circle.css file in the Angular 4 project by loading it in the head section of the

I am currently working with Angular 4 and would like to incorporate the circle.css styles from cssscript. After downloading the file from the provided link, I placed the circle.css within my something component file. However, when attempting to use &l ...

What sets apart a template reference variable (#) from [(ngModel)]?

While undergoing the tutorials and reviewing the documentation, I encountered the concept of `Template reference variables`. Despite my understanding of `NgModel` for two-way binding, I'm perplexed about the usage of `Template reference variables` in ...

Guide on sending files and data simultaneously from Angular to .NET Core

I'm currently working on an Angular 9 application and I am trying to incorporate a file upload feature. The user needs to input title, description, and upload only one file in .zip format. Upon clicking Submit, I intend to send the form data along wit ...

Testing Angular Components with setInterval FunctionTrying out unit tests in Angular

I'm struggling to figure out how to write unit tests for setInterval in my .component.ts file. Here is the function I have: startTimer() { this.showResend = false; this.otpError = false; this.time = 60; this.interval = setInterval(() => { this.ti ...

Sending additional parameters through an HTTP request in Angular

I've created a service method in Angular 8 with an optional parameter. However, I'm encountering a compile time error that says no overload matches this call. The error seems to be at the return statement. Can anyone help me figure out what' ...

Angular 4 - capturing and resending HTTP requests post-login

My HttpInterceptor is designed to monitor specific JWT token events (token_expired, token_not_provided and token_invalid) that can occur at various stages within the workflow. These events may be triggered when a user switches routes OR when an AJAX reque ...