"Enhance the existing control in an Angular 2 FormGroup by adding validators based on the

My form is built using the FormGroup method.

I need to add validators to specific controls that have data after the user inputs information and clicks on the 'check' button.

Here's what I attempted:

this.fg.controls['someKey'].setValidators([Validators.required]);

followed by

this.fg.controls['someKey'].updateValueAndValidity();

However, this approach ends up clearing the data in the control. Any suggestions?

Answer №1

you have the ability to define validators in this manner. give it a try

formBuilder

this.fg = this.formBuilder.group(
     exampleGroup: this.formBuilder.group({
                        checkboxInput: [false],
                        textinput: [''],
                    }, {validator: this.requiredIfChecked}),   
    }

custom validators function

requiredIfChecked(control: AbstractControl): void {
            const input = control.get('textInput').value;
            const inputCheckbox = control.get('checkboxInput').value;
            control.get('textinput').setValidators([]);
            if (inputCheckbox) {
                if (input === '' || input === null) {
                  control.get('textInput').setValidators([Validators.required]);
                }
            }
        }

alternatively, you can explore another method in this DEMO

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

Angular 4 allows for dynamically applying the active class to a clicked button, enhancing interactivity

Issue: <button *ngFor="let button of buttons" [ngClass]="{'active': isClicked}" (click)="isClicked = !isClicked" Description: A total of 10 buttons are displayed on the screen. When I click on button number 1, each button receives the clas ...

The inner map function isn't being executed in Rxjs

I have written some code that utilizes two pipes to load a product instance along with its playlist. In case there is an error while loading the playlist, the property is set to null: getProduct(productId: number): Observable<ProductDTO> { retur ...

Unlocking Transloco Locale: A guide to integrating custom date filters

I've been exploring ways to enhance the default date filters provided by the transloco locale with additional filters that align with our customer's needs. Unfortunately, the documentation lacks examples and clear explanations on how to do this. ...

Highchart in ionic 2 not displaying

https://i.sstatic.net/q2CPR.png I inserted code for a highchart on my webpage, but it's not appearing I followed instructions from this video tutorial https://www.youtube.com/watch?v=FSg8n5_uaWs Can anyone help me troubleshoot this issue? This is ...

Employ an asynchronous immediately-invoked function expression within the callback

Can an asynchronous IIFE be used inside the callback function to avoid the error message "Promise returned in function argument where a void return was expected"? You can find an example here. signIn(email: string, password: string, course?: ICourse): ...

The Angular router-outlet is refusing to display any content

I am new to Angular and currently learning through a lecture with hands-on practice. I have written the code below as instructed by my teacher, but it's not displaying anything on the screen. Can someone please assist me? app.module.ts : @NgModule({ ...

Interactions between Bootstrap 5 and Angular 12 are hindered when using JavaScript to obtain or create Bootstrap instances, causing issues with elements like the navbar and

Everything was functioning perfectly, from the navbar to the dropdown, until I attempted to create bootstrap instances in the .ts files. However, upon inserting the get/create instance js code, I encountered issues - the nav-menu could not collapse after b ...

Setting a default value dynamically in a `select` control can be done by using JavaScript to

Upon subscribing to the HTTP server for data retrieval, my select control in Angular framework gets loaded with the received data. My objective is to set a default value that comprises three values from the server object separated by slashes ("/"), which r ...

Create a custom sorting pipe in Angular 10 that allows for a specific value hierarchy to be passed, without adhering

I am attempting to sort a list of form objects in angular 10 using a custom pipe. The goal is to order them based on a specific property with the following priority: [{VALID: 1}, {INVALID: 2}, {DISABLED: 3}]. I have defined this order as an argument for th ...

``Changing the value of a class variable in Angular 2 does not result in the

I am facing an issue with a component that contains a variable called myName export class ConversationComponent implements OnInit { private myName: string; showNames(name) { this.myName=name; } } The value is assigned using the showNames() m ...

The UI-Grid feature in Angular, when set to right-to-left (RTL) mode, incorrectly displays data in the opposite order compared to the

In my _Layout.cshtml file, I have a CSS that sets all UI controls to right-to-left direction using the following code: * { direction: rtl; } Currently, I am working with Angular's UI-Grid, and in RTL Localization, the ...

How the addition of a type union allows it to be assigned to AnyAction

Struggling with Redux code, I've encountered a peculiar behavior regarding type assignment that has left me puzzled. In the following code snippet, it's clear that you cannot assign anyaction to iaction. Yet, surprisingly, assigning anyaction to ...

The type mismatch issue occurs when using keyof with Typescript generics

One of the challenges I am facing is related to an interface that stores a key of another interface (modelKey) and the corresponding value of that key (value): interface ValueHolder<T, H extends keyof T> { modelKey: H; value: T[H]; } My objectiv ...

The data type 'string' cannot be assigned to the data type 'Position'

Currently, I am in the process of converting React js to typescript. The component being used is a Class Component. I would like to obtain CSS settings through props and apply them to an element. How can I resolve this issue? render(){return( <span st ...

Create an Angular directive input using backticks to input AsciiMath code which can be rendered using MathJ

I recently implemented MathJax in my Angular app following this guide: here. I was successful in getting it to work with asciimath format. However, I encountered an issue when trying to input a literal value into the field. When it's working: app.ts ...

The scrolling on the image listing webpage is not as fluid as desired

I'm currently working on building a website for displaying images in Angular, similar to Google Photos. The site includes a custom scrollbar that displays the month and year. I want the image list to scroll when the user moves the scrollbar thumb. Her ...

A conditional type used with an array to return either an Error object or a generic type when the array is destructured

Within my Typescript project, I've implemented a Result type to be returned from functions, containing either an error or some data. This can take the form of [Error, null], or [null, Data]. Here's an example: type Result<Data> = [ Error | ...

Techniques for simulating functions in Jest

I have a pair of basic components that I'm currently creating tests for using jest. My goal is to verify that when I click on a currencyItem, the corresponding array gets added to the select state. To achieve this, I am passing the handleCurrencyToggl ...

String Compression - Number of Elements

Suppose I define a specific type: type SomeType = 'a' | 'b' | 'c' Is there a TypeScript function available that can calculate the number of unique values a variable of type SomeType can hold? assertEq(countUniqueValues(SomeTy ...

Using Typescript for the factory design pattern

My goal is to develop a factory for generating instances of MainType. To achieve this, I want to reuse existing types (specifically the same instance) which are stored in the ItemFactory. class BaseType { } class MainType extends BaseType { } class It ...