Tips on establishing validators for deeply nested form controls within form groups in Angular 6 reactive forms

In my form array (experiencesArray), I have nested nested nested form controls (companyname), as shown below.

this.personalFormGroup = this._formBuilder.group({
  professionalInfo: this._formBuilder.group({
    totalexpyears: ['', Validators.required],
  }),
  experiencesArray: this._formBuilder.array([this.experiences()])
})

The form group for experiences is outlined below:

experiences(): FormGroup {
  return this._formBuilder.group({
    companyName: [''],
  })
}

I need to set validators based on the value of totalexpyears in the professional form group. If the value is greater than 0, the companyName field should be required; otherwise, it should not. I'm using the following method to set validators:

workExperience(value){
  const expValidation = <FormControl>this.personalFormGroup.get('professionalInfo').get('experiencesArray.expDesignation');
  this.personalFormGroup.get('professionalInfo').get('totalexpyears').valueChanges.subscribe((value)=>{
    console.log("Inside value", value);
    if(value > 0){
      this.totalExpYearsValue = true;
      console.log("Inside value greater than 0", this.totalExpYearsValue);
      expValidation.setValidators([Validators.required]);
    }
    if(value == 0){
      this.totalExpYearsValue = false;
      console.log("Inside value lesser than 0", this.totalExpYearsValue);
      expValidation.clearValidators();
    }
    expValidation.updateValueAndValidity();
  });
}

Additionally, the totalexpyears field is a material dropdown and the template code is shown below:

<form [formGroup]="personalFormGroup">
  <div formGroupName="professionalInfo">

    <mat-form-field>
      <mat-select (selectionChange)="workExperience($event.value)" formControlName="totalexpyears" placeholder="Total Exp yrs *" class="select">
        <mat-option *ngFor="let exp of experience" [value]="exp">
          {{exp}}
        </mat-option>
      </mat-select>
      <mat-error *ngIf="(personalFormGroup.get('professionalInfo').get('totalexpyears').errors)">
        <mat-error *ngIf="(personalFormGroup.get('professionalInfo').get('totalexpyears').errors.required && personalFormGroup.get('professionalInfo').get('totalexpyears').touched)">
          Experience is required
        </mat-error>
      </mat-error>
    </mat-form-field>  

   <div class="design" *ngIf="this.totalExpYearsValue">
     <!-- Experience section -->
   </div>
  </div>
</form>

An error I encountered is displayed below:

ERROR TypeError: Cannot read property 'setValidators' of null
at steppar.component.ts:590
    ...

The focus is on setting validators based on experience value. Please disregard other aspects such as syntax errors or HTML structure.

Answer №1

      experienceOne(value) {
        const totalExperienceYears = this.personalFormGroup.controls['professionalInfo'].get('totalExpYears').value;
        const experienceValidation = <FormArray>this.personalFormGroup.get('professionalInfo.experiencesArray');
        if (value > 0 ) {
         this.totalExpMonthValue = true;

         console.log("selected month value", value);
         experienceValidation.at(0).get('expCompanyName').setValidators([Validators.required]);

       }
        if(value == 0 ){
                 this.totalExpMonthValue = false; 
                 this.totalExpYearsValue = false; 
                 experienceValidation.at(0).get('expCompanyName').clearValidators();
    }
 experienceValidation.at(0).get('expCompanyName').updateValueAndValidity();
}

The code above is functioning perfectly.

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

The image is not displaying on the page

Slider Section (Gray Part) We verified after loading, and the data was spot on. In development mode (F12), we can inspect object information (ImgURL, Text, etc.). However, it is not being displayed. Below is the template code and script code. Thank you. ...

The Issue of Horizontal Scrolling - None of the elements are out of

I am facing an issue with an unwanted horizontal scroll on my website and I can't seem to identify the cause. The header of my site is quite simple, utilizing display: flex, justify-content: center, marin-top: 5vh, along with some padding on the logo ...

What is the best way to trigger an AJAX function every 15 seconds?

As part of my web application, I have implemented a JavaScript function that is triggered by the <body onload> event. Within this function, there is a while loop that continuously iterates until it receives the desired response from a PHP page. Unfo ...

Display the status in the textbox once a dropdown value has been selected

I have a function that allows me to add shops. Within this function, I am able to select whether the shop is OPEN or CLOSED. The goal is for the status of the shop, either OPEN or CLOSED, to appear in a textbox on another modal. When creating a user and ...

JavaScript design not aligning

I'm currently attempting to find a pattern that includes the pipe (|) operator. Here is the code I've used to match the pattern: var format = /[ \\|]/; // This is the pattern for matching the pipe pattern if ("Near raghavendra temple ...

What methods are available to adjust the header color on various pages?

I have a solution that works for one location, but I need to add red color to multiple locations. How can I achieve this? import { useRouter } from "next/router"; function Header() { const router = useRouter(); return ( <> & ...

The Transform feature doesn't seem to be functioning as expected within the Bootstrap

I was experimenting with creating a simple transform transition animation using css and js, so I wrote the following code: (test page) <!DOCTYPE html> <html> <head> <style type="text/css"> *{ ...

Formulate a CANNON entity utilizing the THREE.Mesh technique

I have a THREE.js plane where the points are manipulated using Perlin noise to create terrain. I now need to implement physics for the camera to prevent it from falling through the plane. My goal is to develop a function that can extract the vertices and ...

Differentiate the values in ng-repeat within angularjs

I have a table where I am populating data using ng-repeat. The table structure is as follows: <table class="table table-bordered table-hover"> <thead> <tr> <th> Sr. no. </th> &l ...

Issue identified: Upgrading package (buefy) causes disruptions in project functionality (filegator) - potential import conflicts(?

I am currently working on enhancing features for the self-hosted file storage system called filegator. (The project utilizes single-file components for organization, which is important to note.) (It is built on Vue.js and operates as a Node.js server ...

Creating a PDF from dynamic HTML and transferring it to an AWS S3 bucket without the need to download the PDF

We have created a web application using React JS where we attempted to generate a PDF. Instead of downloading or opening the PDF in a new window, our goal is to directly upload it to an AWS S3 bucket. We have researched and tried various samples but have n ...

What is the best way to manually decrease the speed of an object's rotation using javascript?

Can anyone assist me with slowing down the mouse-controlled rotation of a 3D object in javascript? The current rotation is too sensitive and difficult to control manually. Below is the code I am using: <html> <head> <script src="js/thr ...

Retrieve the exact value of a key within a string

This is my unique text: let x = "Learning new things every day!"; I am utilizing the substring() method to extract a specific part of it: console.log(x.substring(9, 12)); Instead of the entire string, I only want the word 'new'. let x = "l ...

Accessing html form elements using jQuery

I'm having trouble extracting a form using jQuery and haven't been able to find a solution. I've tried several examples, but none of them display the form tags along with their attributes. Here is a sample fiddle that I've created: Sam ...

Utilizing Regular Expressions in AngularJS to validate name, a 10-digit mobile number, and a 12-digit number through the ng-blur event and match

I am struggling to validate the three inputs mentioned above and having trouble using the right functions. Can someone please assist me with this? Here is the HTML code for the 3 inputs: <input id="name" ng-model="user.name" ng-blur="checkIfNameIsVali ...

Is there a way to delete specific information from a JSON response?

Received the service response in the following format: Temp([ { XXX: "2", YYY: "3", ZZZ: "4" }, { XXX: "5", YYY: "6", ZZZ: "7" }, { XXX: "1", YYY: "2", ZZZ: "3" } ]); I need to manipulate this response in J ...

Unable to reach the build on the Linux server

After deploying my react project on a Linux server and creating a production build using "sudo npm run build," I am encountering issues accessing the project. When I run the build file "serve -s build" and attempt to access the app via the remote URL provi ...

Passing arguments to EJS view with Express

As a newcomer to Node.js/Express/EJS, I've made an interesting observation. I've realized that if I pass arguments from an Express request handler to an EJS view without specifying the argument name, it automatically assigns a name based on the v ...

Displaying a loading animation to keep users engaged while AJAX calls retrieve data from the server

My issue was outlined in a recent discussion on Stack Overflow. In essence, my goal is to display a loading indicator before server-side processes complete: [Loader] -> [Target page]. However, the HTML content loads after the server-side tasks, resultin ...

Rendering sibling components on Multiple Select Material UI in React

Here is my current challenge: I am trying to implement a multiple select feature with checkboxes in React using Material UI. The desired outcome should resemble the image linked below: https://i.stack.imgur.com/TJl8L.png I have structured my data in an a ...