Angular 7 Forms: Implementing Conditional "Required" Validation with Reactive Forms

Before I get into it, I won't be able to share the actual code I'm working on due to confidentiality reasons. However, I can provide a simplified version of the code...

I am working with Angular 7 and Reactive Forms. In my form, I have a radio button that is always visible. When the user selects "yes", another radio button should appear below it. If "no" is selected, the additional radio button should either disappear or be removed from the DOM (using ngIf*).

What I'm aiming to achieve is something like this:

    field: ['', { validators: () => { if (this.isElementShown('blah')) { return Validators.required }}}]

Below is the method "isElementShown" that I am using:

  isElementShown(id: string) {
    var element = document.getElementById(id);
       if (document.body.contains(element)) {
          return true;
       }
    return false;
  }

Additionally, when the form is submitted, I am checking and logging all invalid fields like this:

  const invalid = [];
  const controls = this.form.controls;
  for (const name in controls) {
    if (controls[name].invalid) {
      invalid.push(name);
    }
  }
  console.log(invalid);

The issue I am facing is that initially, the field does not show as invalid when the page loads. However, when I select "yes" and the second radio button appears, it is marked as invalid. This is the expected behavior. But when I switch back to "no" for the first radio button, it still appears as "invalid" in the console even though the second radio button is removed from the DOM.

Any suggestions on how to resolve this issue? I feel like I'm close to a solution but I'm stuck at the moment. Thank you for any help!

Answer №1

Conditional Requirements can be implemented using the required validator from the @rxweb/reactive-form-validator library.

To apply a condition, simply specify it within the required validator.

 second:['',RxwebValidators.required({conditionalExpression:(x)=> {
return x.first == 'yes'
  }})]

Full TypeScript Code

this.userFormGroup = this.formBuilder.group({
  first:[''],
  second:['',RxwebValidators.required({conditionalExpression:(x)=> {
return x.first == 'yes'
  }})]
})

I have imported the 'RxReactiveFormsModule' in the main module of the application.

See the example 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

The input in the schema fails validation against the Angular 7 schema with the following data: {"name":"testng7"}

After updating the Angular CLI to the latest version on my Mac OS, I encountered an issue when trying to create a new project using the command ng new testng7. The error message displayed was: Schematic input does not validate against the Schema: {"na ...

I am encountering a CORS error in Nest.js despite having CORS enabled

I'm currently working on a project using next.js for the frontend and nest.js for the backend. Despite having CORS enabled in my main.ts file of nest.js, I keep encountering CORS errors. Below is an excerpt from my main.ts file: import { NestFac ...

Should we rethink our approach to styling components in this way?

Is this approach using styled-components, nextjs, typescript, and react flawed or potentially problematic in terms of performance? The goal was to create a component that is initially unstyled but can receive CSS styles for each HTML element within the com ...

Filtering an observable using criteria from another source

I'm currently facing a challenge where I need to map observables by filtering them based on events emitted from other observables. The main question at hand is: Is there a way to pass a property of an event to a filter function? In the following exa ...

React with TypeScript is throwing an error that says: "The type 'string' does not have any properties in common with the type 'CSSProperties'."

Currently encountering a challenge while using Typescript in conjunction with React. https://i.sstatic.net/tHkoJ.png ...

Troubleshooting the Issue with Angular Material Dialog Imports

Hey there, I'm trying to utilize the Angular Material dialog, but I'm encountering issues with the imports and I can't seem to figure out what's wrong. I have an Angular Material module where I imported MatDialog, and I made sure to i ...

Encountered an error while trying to load a resource on ionic emulate

After successful testing in the browser, my app encounters an issue when emulating on an android emulator. It seems to be unable to load resources from the json-server hosted in my localhost, resulting in a "Failed to load resource" error message. To addr ...

Data types for keys and values in TypeScript

interface A { a?: number }; interface B { a?: string }; function replicate< Source extends object, Destination extends { [key in keyof Source]?: (1) } >( source: Source, key: keyof Source, destination: Destination, converter: ...

NeedValidation.required, Validation.emailCheck

When creating a form in TypeScript, I encountered an issue: private _createForm() { this.addForm = this._formBuilder.group({ login: [ null, Validators.required ], name: [ null, Validators.required ], surname: [ null, Validators ...

Ngrx optimized reducer with ahead-of-time compilation

I've been attempting to implement this reducer from the ReduxJs website using NgRx and Angular Cli: function createFilteredReducer(reducerFunction, reducerPredicate) { return (state, action) => { const isInitializationCall = state === ...

Bring in jspm libraries to your project via typescript

While researching how to import jspm packages into typescript, I noticed that most examples assumed the use of SystemJS for loading and interpreting them in the browser. However, I prefer using tsc to compile commonjs modules and only import the js code, a ...

The CORS policy has blocked access to 'http://localhost:8080/BeginSignup' from 'http://localhost:4200'

I'm having trouble with a CORS policy error when sending a fetch POST request to my Golang AppEngine API. Although I don't understand why this error is occurring. Below is the code I'm using: Below is the Angular code calling the API: priva ...

What factors play a role in determining how modules are mapped to components in Angular 2?

What is the distribution method for modules on components? What benefits does this innovative concept offer compared to traditional folder organization? Choices: One module assigned to each component? One module designated per page. Other ... ...

Is Typescript the Ultimate Replacement for propTypes in React Development?

After diving into Typescript for the first time and exploring related articles, it appears that when using Typescript with React, propTypes definitions may no longer be necessary. However, upon examining some of the most popular React Component Libraries: ...

Extracting ZoneAwarePromise from Firebase snapshot data

I'm having an issue where I call a function from a service provider in my component. When I call a get function from Firebase, the console outputs a ZoneAwarePromise. What could be causing this problem? Here is the code from xx.component.ts: constru ...

Efficiently Parsing FormData in React with TypeScript for Improved Data Formatting

Recently, I've started working with React and Typescript and one of the challenges I'm facing is managing an editable table with default values that can be updated and submitted. The data format for the parameters is crucial as the fields and va ...

Why does the CSHTML button containing a JavaScript onclick function only function intermittently?

I've implemented a download button on a webpage that dynamically assigns an ID based on the number of questions posted. Below is the code for the button: <input data-bind="attr: { id: $index() }" type="button" value="Downlo ...

The method toLowerCase is not found on this data type in TypeScript

I am currently working on creating a filter for autocomplete material. Here is an example of my model: export class Country { country_id: number; name: string; } When calling the web method ws: this.ws.AllCountry().subscribe( ...

Issue: Unable to find solutions for all parameters in NoteService: (?)

After following a tutorial on Angular 2 from , I encountered the mentioned error when running my API. The browser indicates that there are unresolved parameters in the following service: import {Injectable} from '@angular/core'; import { ApiSe ...

Why is it that retrieving the same class data from two separate TypeScript files yields varying results in TypeScript? What steps can be taken to resolve this issue

I have created 3 TypeScript files named dataService.ts, init.ts, and interest.ts. The dataService.ts file is a common file used to store and retrieve data from the other 2 files. Within the dataService.ts file: export default class DataService { priv ...