Angular's reactive form feature does not have built-in support for ngIf

I am facing an issue with a form group where I need to display one of the required inputs using ngIf. However, even if this input does not exist, the form control still checks it and returns that the form is not valid. Here is my code: HTML:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <label>mobile</label>
  <input type="text" formControlName="mobile" />

  <div *ngIf="!hasInfo">
    <label>firstName</label>
    <input type="text" formControlName="firstName" />
    <label>lastName</label>
    <input type="text" formControlName="lastName" />
  </div>
  <button type="submit">Submit</button>
</form>

TypeScript:

constructor(){
 this.formBuilder();
}

ngOnInit() {
    if (accountResponse.length > 0) this.hasInfo= true;
}

formBuilder() {
    this.myForm= new FormGroup({
      mobile: new FormControl(null, Validator.required()),
      firstName: new FormControl(null, Validator.required()),
      lastName: new FormControl(null, Validator.required()),
    });
 }

onSubmit(){
  if(this.myForm.valid){
    console.log("valid")
  }else{
    console.log("not valid")
  }
}

If hasInfo is true and not showing firstName and lastName, my form should return as valid. However, it always shows up as not valid.

Answer №1

Conditional validators can be incorporated during form initialization.

ngOnInit() {
  if (userData.length > 0) this.hasData= true;
  this.buildForm();
}

buildForm() {
  const mandatory = this.hasData ? Validator.required : null;

  this.userForm = new FormGroup({
    username: new FormControl(null, Validator.required),
    email: new FormControl(null, mandatory),
    phoneNumber: new FormControl(null, mandatory),
  });
}

Answer №3

ngIf simply controls the rendering of your div in the html file without affecting the reactive form validation in your .ts file. To achieve your goal, consider implementing the following:

.ts:

ngOnInit() {
    if (accountResponse.length > 0) { 
      this.hasInfo= true;
      updateValidations();
    }
}

updateValidations() {
 if( this.hasInfo ) {
  this.myForm.get("firstName").clearValidators();
  this.myForm.get("firstName").updateValueAndValidity();
  this.myForm.get("lastName").clearValidators();
  this.myForm.get("lastName").updateValueAndValidity();
 }
}

Invoke the updateValidations function whenever this.hasInfo changes.

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

Mastering Firebase pagination with RxJS - the ultimate solution

I came across this helpful post on Cloud Firestore pagination with RXJS at Cloud Firestore - How to paginate data with RXJS While it is exactly what I need, I am struggling to understand how to implement the following code snippet: import { UsersService } ...

Is there a way to invoke an Angular2 function from within a Google Map infowindow?

I am currently working on integrating Google Maps using javascript in a project, and I'm facing a challenge. I want to call an Angular2 function inside an infowindow as shown in the code snippet below. Pay attention to the infoContent variable that co ...

The term "Exports" has not been defined

I'm currently facing a challenge trying to develop an Angular application based on my initial app. The process is not as smooth as I had hoped. Here's the current setup: index.html <!DOCTYPE html> <html> <head> <base h ...

The inclusion of an XSRF-TOKEN using an HTTP Interceptor results in a 400 Error Request

Implementing XSRF-TOKEN to enhance security and prevent XSRF attacks as I pass a JWT through a cookie for my Angular application. Below is the structure of my HttpInterceptor. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEv ...

Unraveling the art of utilizing the map operator in ES6 with condition

I need to implement a condition within the map function where I prepend zeros for single digit values (00.00 to 09.30), while leaving remaining values unchanged. Currently, it is prepending zeros for all values. Here is the code: export class SelectOver ...

Is there a way for me to access the names of the controls in my form directly from the .html file?

I have a list where I am storing the names of my form controls. In order to validate these form controls, I need to combine their names with my code in the HTML file. How can I achieve this? Below is my code: .ts file this.form = this.formBuilder.group({ ...

Tips for sorting and categorizing information within Angular version 14

When I press "All," I want to see the status of P and step 01, along with its type. Thank you very much. This is in HTML: <mat-form-field appearance="outline"> <mat-select (selectionChange)="onChange($event)"> ...

Utilizing Typeface Styles in SCSS with the Latest Webpack Version 4

My Angular 6 SPA utilizes Webpack 4 for bundling, and I have encountered an issue while trying to import external fonts into the project. The project is based on the repository found at; AngularWebpackVisualStudio Example Repo After inspecting the webpac ...

ngFor is failing to show the array data, which is being fetched from Firebase

Hi there, I understand that this question has been asked frequently, but the regular solutions are not working for me. ts handleChangeFormType(formType) { this.serverData.getData('questionnaire/' + formType) .subscribe( (response: Respons ...

Angular Rxjs repeatWhen: when none of the statuses are COMPLETED

If the status in my Angular Service file is not 'COMPLETED' for all data, I need to retry hitting the same URL up to 5 times with a delay of 5 seconds. [ { "data": [ //SET OF OBJECTS ], "status": ...

Angular 8 delivers an observable as a result following a series of asynchronous requests

I am working on a simple function that executes 3 asynchronous functions in sequence: fetchData() { this.fetchUsers('2') .pipe( flatMap((data: any) => { return this.fetchPosts(data.id); }), fl ...

Ngx-Chips: Autocomplete feature fails to refresh list upon receiving response

I have integrated the ngx-chips plugin into my project from ngx-chips. The dropdown list is currently being populated using an HTTP call to the server. Although the myContactList data in the view is getting updated, I am facing an issue where the dropdow ...

What sets [NgClass] apart from [class] in Angular JS2?

Consider a view element with the following three attributes: class="red" [class]="isGreen ? green : cyan" [ngClass]="'blue'" Does Angular merge the output of these attributes or does one override the others? If we have: [class]="getElementCla ...

Angular 4 CanActivateChild fails to function

I'm attempting to limit access to my route system by using the CanActivateChild feature. However, I've encountered an issue where the RouteGuard only works with the CanActivate function and not CanActivateChild. Here's a snippet of my routin ...

Simultaneously accessing multiple APIs

I am currently facing an issue with calling two API requests sequentially, which is causing unnecessary delays. Can someone please advise me on how to call both APIs simultaneously in order to save time? this.data = await this.processService.workflowAPI1(& ...

The 'Access-Control-Allow-Origin' header can be found on the resource that was requested

I'm facing an issue while trying to connect my .net core API to an Angular application. Whenever I attempt to do so, I encounter the following error: Access to XMLHttpRequest at 'https://localhost:44378/api/recloadprime' from origin 'h ...

Determine the overall sum of all items

Utilizing data fetched from my SQLite database, I'm utilizing *ngFor to display a comprehensive list of items with their respective names, prices, amounts, and totals. How can I calculate the grand total and display it at the bottom of the list? chec ...

Obtain pictures from MongoDB for a website using Angular6

I'm currently in the process of developing my website and I want to showcase an image from my database on the header. Each customer is assigned a unique logo based on their ID, but I'm unsure how to use Angular to display it. Below is my code s ...

Top approach for Constructing Angular Front-End Forms with User Input

Greetings to all who happen upon this message, thank you for taking the time to potentially offer assistance! In my past experiences working with Wordpress (PHP), I utilized a plugin called Advanced Custom Fields from advancedcustomfields.com. This plugin ...

What is the process for connecting a form to a model in Angular 6 using reactive forms?

In the time before angular 6, my approach involved utilizing [(ngModel)] to establish a direct binding between my form field and the model. However, this method is now considered deprecated (unusable with reactive forms) and I find myself at a loss on how ...