Applying a setvalidator to a FormControl doesn't automatically mark the form as invalid

HTML code

<div>
    <label for=""
      >No additional information flag:</label>
    <rca-checkbox formControlName="noAdditionalInfoCheckbox"  (checkboxChecked)="onCheckboxChecked($event)"></rca-checkbox>
</div>
<div>
    <label >No additional information reasons:</label>
    <textarea
      formControlName="noAdditionalInformationReasons"
      id=""
      class="form-control"
    ></textarea>
</div>

TS file

onCheckboxChecked(isChecked): void {
 
  const noAdditionalInfoReasonsControl = this.addNewRequestFormForIndividual.get('noAdditionalInformationReasons');
  if (isChecked){
     
      noAdditionalInfoReasonsControl.setValidators(Validators.required);
      this.noAddInfoReasonsErrorMessage = "give reason";
  }
  else {
     
      
    noAdditionalInfoReasonsControl.clearValidators;
    this.noAddInfoReasonsErrorMessage = '';
  }
    
  noAdditionalInfoReasonsControl.updateValueAndValidity;
    
  console.log(this.addNewRequestFormForIndividual.valid);
  
}

If the checkbox is checked, a required validator will be added to the second FormControl and the Add button over the form will be disabled if the form is not valid.

An issue arises where the last console prints true even after setting validators above, and the Add button remains enabled. Additionally, modifying the required field causes the validation state of the form to change - entering and then deleting content from the required field leads to the Add button being disabled and the form becoming invalid.

Even when unchecking the checkbox, the form stays invalid. The use of updateValueAndValidity does not resolve this issue, prompting further investigation into why this behavior persists.

Answer â„–1

clearValidators and updateValueAndValidity represent the methods available. It is important not to forget the () when using these methods, as they will not be executed otherwise. Inserting () is necessary to properly call the method like so:

noAdditionalInfoReasonsControl.clearValidators();
noAdditionalInfoReasonsControl.updateValueAndValidity();

Check out a demo on StackBlitz

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

Discovering the RootState type dynamically within redux toolkit using the makeStore function

I am currently working on obtaining the type of my redux store to define the RootState type. Previously, I was just creating and exporting a store instance following the instructions in the redux toolkit documentation without encountering any issues. Howev ...

The listener for @ok is not being activated when using jest-test-utils with b-modal in vue-bootstrap

I have implemented the vue-bootstrap b-modal feature with the @ok="save" hook Here is a snippet of mycomponent.vue: <template> <div> <b-button @click="add">open modal</b-button> <b-modal static lazy id="modal-detail" ...

Exploring the use of .pipe with Angular Jest for testing

Currently, I am trying to test the following .ts file: create(entityResourceID, params: any): Observable <any>{ const url = `${this.apiUrl}/${entityResourceID}/assignee`; return this.http.post(url, params).pipe( map(() ...

Is it possible to expand the Angular Material Data Table Header Row to align with the width of the row content?

Issue with Angular Material Data Table Layout Link to relevant feature request on GitHub On this StackBlitz demo, the issue of rows bleeding through the header when scrolling to the right and the row lines not expanding past viewport width is evident. Ho ...

Error message possibly undefined when attempting to apply fill gradient to Highcharts area-spline chart

Currently working with angular 12 and utilizing highcharts. I've been attempting to fill the area spline color with a gradient, but have encountered an error in the process. Any suggestions on how to resolve this issue or what step may be causing the ...

Issues encountered with the `npm install` command in Azure build pipelines for a simple Angular application

Transferred the GitHub Repository mentioned in this link to Azure Repository. Established the Build Pipeline using Classic Editor, and you can find the YAML Code below: trigger: branches: include: - refs/heads/master jobs: - job: Job_1 display ...

Angular Material - Data Table Kit

Struggling with setting custom styling for a mat-table in Angular Material. I want to adjust the border radius of the table and change the spacing inside to "space-between". The design I'm aiming for is shown here: Design Any tips or suggestions woul ...

Printing values of an object in an Angular/HTML script is proving to be quite challenging for me

In my Angular project, I have created a service and component for listing objects. The list is functioning correctly as I have tested it with 'console.log()'. However, when I try to display the list on localhost:4200, nothing appears. <table&g ...

Issues with TypeScript: outFile in tsconfig not functioning as expected

Currently, I am utilizing Atom as my primary development environment for a project involving AngularJs 2 and typescript. To support typescript, I have integrated the atom-typescript plugin into Atom. However, I noticed that Atom is generating separate .js ...

Querying specific documents with Angular Firebase reference is a breeze

I'm currently encountering an issue when attempting to query documents in one collection with a reference to another document in a separate collection. Here is the scenario I am dealing with: There are two collections: "posts" and "users". Every "pos ...

Issues detected with the functionality of Angular HttpInterceptor in conjunction with forkJoin

I have a Service that retrieves a token using Observable and an HttpInterceptor to inject the token into every http request. It works seamlessly with a single request, but when using forkJoin, no response is received. Here is the code for the interceptor: ...

What could be causing Typescript to inaccurately infer the type of an array element?

My issue revolves around the object named RollingStockSelectorParams, which includes arrays. I am attempting to have TypeScript automatically determine the type of elements within the specified array additionalRsParams[title]. The main question: why does ...

Is it possible for Angular's `HttpClient` to use complex property types in the `.get()` generics aside from just `string` or `number`?

After spending an entire day researching the topic, I've hit a dead end. All my efforts have only led me to discover one thing—omission. None of the information I've come across mentions whether you can utilize non-simple types (such as string ...

Angular protection filter

Every time I used Angular CLI to generate a new component, it would create the component with standard parameters: @Component({ selector: 'app-test1', templateUrl: './test1.component.html', styleUrls: ['./test1.component.css ...

Can you provide details on the capabilities of Appium for webviews on Android devices?

I attempted to utilize the following capabilities { maxInstances: 1, browserName: '', appiumVersion: '1.18.2', platformName: 'android', platformVersion: '10.0', deviceName: 'd ...

Ways to categorize items retrieved from an HTTP request to the backend in Angular

When making a call to the backend using this http request: this.StudentEnrollment.getRecordsById(list.value.split(/[\r\n]+/)).subscribe(values => { this.studentObject = values; }); The studentObject is structured as shown below: { recor ...

Angular 13 encounters issues loading Bootstrap and JS files whenever the route button is clicked

As a beginner in Angular, I am currently working on converting HTML templates to Angular for the purpose of learning. However, I have encountered an issue when navigating to the signup page from the home's router link. The bootstrap and JS files are n ...

NGXS: Issue with passing objects to "setState" occurs when any of the patched inner fields is nullable or undefined

In my Angular components, I have created a class that is responsible for storing the state: export class MyStateModel { subState1: SubStateModel1; substate2: SubStateModel2; } This class has simple subclasses: export class SubStateModel1 { someField ...

Checkbox fails to display as checked

I am currently working on implementing checkbox inputs in React JS. I have encountered an issue where the checkboxes do not visually show as checked when clicked, but I am still able to retrieve the value of the checkbox. Here is my code: Simple Checkbox I ...

Angular 2 doesn't reflect changes in component variables in the view until mouseover happens

Since updating from angular2-alpha to the latest version, I've noticed that when a boolean value changes in my *ngIf directive, it doesn't reflect in the view until certain actions are taken. Here is the specific component code: declare var CKE ...