Utilizing Angular 7 for Dynamic Validations: Enabling and Setting Validators Based on Triggered Flags from Changes

After a long break from my last Angular project, during which I worked with VueJS, I have returned and successfully implemented a reactive form with conditional fields in Angular 7. However, I feel that my current solution is overly lengthy and not very intuitive. It requires disabling a field in order to disable validators, which may not be immediately apparent to others looking at the code. I am hoping for guidance from an expert in Angular/TypeScript to help me optimize this code or suggest a better approach.

onChangeType(scope: string) {
    console.log(scope);
    this.myForm.get('riskType').disable();
    this.myForm.get('chancheType').disable();

    if (scope === 'local') {
    this.flags.isScopeLocal = true;
    this.flags.isScopeTemplate = false;
    this.flags.isScopeGlobal = false;
    this.myForm.get('chancheType').enable();
    this.myForm.get('chancheType').setValidators(Validators.required);
    } else if (scope === 'template') {
    this.flags.isScopeTemplate = true;
    this.flags.isScopeLocal = false;
    this.flags.isScopeGlobal = false;
    this.myForm.get('riskType').enable();
    this.myForm.get('riskType').setValidators(Validators.required);
    } else {
    // global
    this.flags.isScopeLocal = false;
    this.flags.isScopeTemplate = false;
    this.flags.isScopeGlobal = true;
    this.myForm.get('riskType').disable();
    this.myForm.get('chancheType').disable();
    }
} 

In brief, when the scope is set to local or template, a new required field appears. If the scope is changed to global, this field disappears and its validator is deactivated.

Answer №1

Expanding upon my response using a specific directive How to enable editing for a disabled reactive form in Angular2

Instead of manually changing validators with setValidators, the directive can handle enabling/disabling the controls. This approach is easier to understand and maintain.

<input formControlName="riskType" [enabledControl]="scope=='local'">
<input formControlName="chancheType" [enabledControl]="scope=='template'">

myForm=this.fb.group({
     riskType:['',Validators.required],
     cacheType:['',Validators.required],

})

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

Issue with NPM installation of node module

My angular project includes a package.json file with all the necessary dependencies listed. However, whenever I run "npm install" in the terminal, the packages seem to download correctly and a node module folder is created in my root directory. Strangely ...

Intellisense not working with express

After using the command npm install --save @types/express to install, I imported in my ts file as follows: import * as express from "express"; var app = express(); Despite this setup, I am not able to get intelisense on the app variable. Additionally ...

Tips on inserting a URL into an email message so that it automatically opens in Google Chrome

In the midst of my C#/Angular project, I've encountered an issue with certain third party controls preventing some website features from functioning properly on Internet Explorer. An email is sent out containing a link to a specific page, but when I c ...

combination of Vue methods from a separate file

Having some trouble sharing a method in Vue across files. Despite trying various suggestions found through research, I haven't been able to make it work. I did manage to get mixins working within the same file, but couldn't figure out how to impo ...

How to access a nested child within a child in JSON using jQuery/JS?

I am curious to know if it is possible to loop through the nested elements in this JSON structure: [ { "name": "Hello", "views": 10, "subMovie": [ { "name": "World", "views": 10, "subMovie": [ { ...

How can JavaScript Regular Expressions be used for Form Validation?

For my registration form, I am including fields such as userid, name, email, password, confirm password, and affiliation. Using regular expressions in JavaScript, I am validating these fields. I am attempting to display any validation errors within the for ...

What is the best way to include a check mark icon using MUI or Tailwind CSS for every item selected in a dropdown menu?

I need help with adding a small check/tick icon next to the selected value, for example: Operations ✓ when the user chooses operations in the TopicList dropdown list. The TopicList is a class component used to retrieve data from the database which incl ...

Several features - Second function malfunctioning

The initial inquiry is effective. However, the subsequent one is encountering issues as it is failing to confirm if an email contains the "@" symbol. My attempted solution involved reordering the functions related to email validation. <body onload="ch ...

Creating dynamic arrays in Angular2 is essential for flexible and scalable programming

I am facing a challenge in Angular 2 where I need to initialize Array variables from another Array. Here is the scenario: Upon loading my page, I receive an Array of strings from the server (let's call it initialArray). I want to create and initialize ...

Angular 2/JS - Date expression functions exclusively in the Chrome browser

Today, I decided to test my app using my FireFox browser instead of Chrome like usual, and I was surprised to find that my app isn't functioning properly. After some investigation, I discovered that the code snippet below is causing the issue by disp ...

The clientWidth and scrollWidth properties will constantly be the same

I am currently utilizing Vuetify text-fields and aiming to exhibit a tooltip showcasing the content only if it exceeds the field width (requiring user scroll). The tooltip should solely be visible on hover, as per default behavior. My initial approach ensu ...

Converting a string to a double in Angular: A handy guide

My application is integrated with a payments API, and I need to convert the invoice value from type number to currency. signature.invoice.amount: 10500 (Number) I attempted to use a currency pipe {{ signature.invoice.amount | currency: 'BRL': t ...

Display content in .innerHTML continuously with Javascript and a while loop

I'm currently learning how to implement while loops in my code. I understand the concept quite well, but I'm facing some difficulty in using a while loop to write text repeatedly to an HTML element. var userText = prompt("Enter the text you wa ...

Is it possible to submit a form prior to the complete loading of the DOM?

I have been contemplating the idea of loading a jQuery reference on a webpage after the DOM has fully loaded (document.onload) in order to enhance the page load speed, especially on pages containing forms. It is my belief that the DOM may finish rendering ...

Implement a feature in React that allows for the copying of values from one input field to another when a

Within my form, I have implemented two address field groups - one for shipping and another for billing. I am looking to enhance user experience by providing them with the option to copy values from the shipping address group to the billing address group wh ...

ES6 syntax causes import class function to malfunction

I'm having an issue while trying to import and initialize a class in ES6. When I run the code, the console displays an error message stating 'undefined property hej'. Work.js class Work { constructor() { } hej() { al ...

Refresh the table following deletion of a row from firebase

I have developed an application where I display data from a firebase object in a table. However, I have encountered an issue where I need to manually refresh the page every time I remove a row from the table. Is there a way to automate this process? The sa ...

Determining if data from two separate lists in Vue.js matches in order to display in the template

I need to compare two sets of data - one fetched from the server and the other being default data. Data retrieved from the server: [ { "id": 7, "day": "14 April 2017", "time_list": [ { "id": 25, "time": "11:00 AM", ...

Inserting a file read using Node.js into a MongoDB database

Recently, I came across a text file that contains the following data: title: A, alert: notice, desc: Starting title: B, alert: notice, desc: Process Step 1 and 2 Step 1 - Execute Step 2 - Log title: C, alert: notice, desc: "Ending" My goal is to insert ...

Issues with onclick event functionality in asp.net

Hello friends, I'm facing an issue with a button where the click event is not working properly. <asp:Button ID="btnfirstnext" runat="server" Text="Next" class="next1 action-button" OnClick="btnfirstnext_Click" OnClientClick="return false;" /> ...