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

What happens when a typed Array in Typescript has an undefined property?

I've encountered an issue with a seemingly simple problem that's causing me quite the headache. The code snippet in question is provided below: interface IFoo{ ReturnFirstBarObject1(): string; FillBarArray(array: Array<Bar>): void; } ...

Setting a binary value for an angular checkbox through user input: a step-by-step guide

As a newcomer to Angular, I am currently in the process of creating a straightforward registration page by following this tutorial. The essential information I need to capture includes the user's email address, username, password, and a binary value i ...

Exploring an array within an object using Typescript and React

As a newcomer to TypeScript and React, I have a project where I need to extract data from a JSON file (back-end) and display it on cards (front-end). I am trying to pass props using cards?.items.map, but I'm uncertain about the correct way to access ...

Merely using Array.isArray check is insufficient to prompt the TypeScript compiler about a potential array value

I have a method where the type can be an array, but I need to verify that it is not an array before accessing the argument. However, despite my check, I am still encountering the following error (excerpt) on line this.setState({ cuisine });: The type &ap ...

What is the process for retrieving information from Sanity?

Having trouble with creating a schema and fetching data from sanity. The console log is showing undefined. Not sure where I went wrong but suspect it's related to the schema creation. Testimonials.tsx interface Props { testimonial: [Testimonial] ...

Execute the eslint loader within the node_modules of a specific directory that is npm linked and has not been compiled

One of the benefits of using webpack 4 is the ability to run eslint across the entire project folder with a specific configuration. { enforce: 'pre', test: /\.js|ts$/, exclude: /node_modules/, loader: 'eslin ...

Tips for incorporating the observer design pattern in REST APIs (Communication between front-end and back-end)

Is it possible to subscribe once to an API and receive multiple responses until I unsubscribe from that event? If so, how can this be achieved? If not, why does this approach not align with the observer pattern's guidelines? I attempted using the yie ...

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...

Creating dummy objects from a specific data type in Typescript for the purpose of testing

I'm exploring ways to streamline the creation of mock data for unit testing within an Angular solution. Currently, I am defining interfaces such as: export interface ReferenceDataItemCommon { codeDescription?: string; code: string; deleted?: boo ...

create an endless loop to animate in angular2

Is there a way to add iterations, or something similar to the ccs3 animation-iteration-count in Angular 2 animations? I've looked but can't find anything related. How can we apply an infinite play to the animation? Where should we include that o ...

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

Tips for utilizing the 'crypto' module within Angular2?

After running the command for module installation: npm install --save crypto I attempted to import it into my component like this: import { createHmac } from "crypto"; However, I encountered the following error: ERROR in -------------- (4,28): Canno ...

Utilizing Angular's *ngIf directive in conjunction with Observables to handle data retrieved from

Utilizing multiple REST services for data retrieval and altering the value of an Observable in my component code has been a challenge. I've attempted to use *ngIf to toggle the visibility of div tags based on the result, however, the Observable's ...

What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief per ...

Switching the Require statement to an Import statement led to an error popping up

Currently, I am exploring the use of Ajv with typescript. import { Ajv } from "ajv"; let ajv = new Ajv({allErrors: true}); I have encountered an error and I'm unsure why it is occurring: [ts] 'Ajv' only refers to a type, but is being u ...

Is there a way to incorporate margins into a React component using TypeScript?

I am currently facing a challenge in passing CSS attributes to a component that I am working with. The reason behind this is that I need to modify the margins to fit a specific space, hence my attempt to directly pass the margins. Does anyone have any sug ...

A guide on how to initiate a click event in Angular 5 using JQuery

I am trying to trigger a click event for each element based on its id, but it doesn't seem to be working. Below is the code I am using: ngOnInit() { this.getProductsLists(); } getProductsLists() { this.supplierService.getProductLists() .sub ...

What is the best way to trigger a function when a button is enabled in Angular 8?

Here is a portion of my sign-in.component.html file. I have created a function in the corresponding sign-in.component.ts file that I want to trigger when the button below becomes enabled. Here is an example of what I am trying to achieve: <div class= ...

send image back to Angular component from server response

I'm extremely close to achieving my goal. The server is successfully returning the image and sending it in the response. Now, the challenge lies in getting my angular component to properly display it. Let me share what I have done so far: Firstly, h ...

Troubleshooting fastify library errors related to ajv validation

Every time I try to build my TypeScript code, I encounter these errors: The following errors are showing up in my TypeScript code: 1. node_modules/@fastify/ajv-compiler/types/index.d.ts(1,10): error TS2305: Module 'ajv' has no exported member ...