Is it beneficial to disable and deactivate Validators in Angular?

Within our Angular framework, we've implemented a form with 10 fields. However, a new requirement has surfaced where certain individuals only require access to specific fields out of the existing 10. To accommodate this, our team is currently addressing these needs by hiding fields and disabling Validators in both the TypeScript form and the HTML layout.

The query at hand is whether this approach aligns with best practices in Angular development. One alternative suggestion involves creating new form builder models that can be seamlessly swapped in and out of components. The concern lies in potentially cluttering the codebase by deactivating validators and toggling elements in the HTML file. Moreover, adding new fields down the line may complicate matters further if each field requires an individual toggle.

We're now questioning if this method adheres to official Angular documentation recommendations or if there exists a more efficient way to manage the situation rather than utilizing 10 boolean variables for each form control.

this.customerForm = this.formBuilder.group({
  'customerName': [null, [Validators.maxLength(50)]],
  'productBought': [null, [Validators.maxLength(50)]],
  'streetNumber': [null, [Validators.required, Validators.maxLength(64)]],
  'streetName': [null, [Validators.maxLength(8)]],
  'city': [null, [Validators.maxLength(32)]],
  'state': [null, [Validators.maxLength(16)]],
  'postalCode': [null, [Validators.maxLength(16)]],
  'postalCodeExtension': [null, [Validators.maxLength(50)]]
 }, 
}


'city': [null, this.cityShow === true ? [Validators.required, Validators.maxLength(50)] : []],


<div class="parent" *ngIf="cityShow">
    City:
     <input formControlName = "city" class = "cityclass"> 
     </input>
</div>

Answer №1

I believe that utilizing different forms would be more appropriate. You can store the necessary fields in an array and utilize addControl function.

For example:

controls=['customerName','streetNumber','postalCode' ]
this.customerForm = new FormGroup({})
if (controls.indexOf('customerName')>=0)
   this.customerForm.addControl('customerName',new FormControl(null,Validators.maxLength(50))
if (controls.indexOf('productBought')>=0)
   this.customerForm.addControl('productBought',new FormControl(null,Validators.maxLength(50))
if (controls.indexOf('streetName')>=0)
   this.customerForm.addControl('streetName',new FormControl(null,Validators.maxLength(8))
...

}

//In .html
<div *ngIf="controls.indexOf('customerName')>
   Customer :
   <input formControlName="customerName">
   ...
</div>

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

Discover the best way to showcase items within an arrayList using dual CSS styles!

I'm currently working on a project that involves an arrayList with two names: Bob and Steve. I have the requirement to display them in different colors, where Bob should be displayed in green and Steve in red. Component.CSS .Bob{ font-weight:bold; ...

Steer clear of creating new instances within loops in Angular

I am facing an issue with a bug in my code related to the green software scanning of casts. public addFilesToQueue(files: FileList | any): void { const addedFiles: AttachmentItem[] = []; for (let iFileId = 0; iFileId < files.length; ...

Exploring the world of tabbed dynamic routing in Angular 2 version 4

Today I encountered a routing issue that requires assistance from all of you. Currently, I have a sidebar with dynamic tree view navigations on the left and 4 tabs on the right. By default, tab1 is selected to display data related to the active link. Lin ...

Creating a completely dynamic button in Angular 6: A step-by-step guide

I have been working on creating dynamic components for my application, allowing them to be reusable in different parts of the program. At this point, I have successfully developed text inputs that can be dynamically added and customized using the component ...

Creating a variable name dynamically using Typescript

I am looking to efficiently create multiple instances of variables and assign values in a single statement, an example of which is shown below. this.myList1[data.id] = data.id + "-" + data.desc; this.myList2[data.id] = data.id + "-" + data.desc; this.myLi ...

A guide to implementing angularjs app.service and $q in typescript

I am fairly new to TypeScript and AngularJS and I am struggling to find the correct answer for my issue. Below is the relevant code snippet: export class SidenavController { static $inject = ['$scope', '$mdSidenav']; constructor(p ...

Encountering a TypeScript issue with bracket notation in template literals

I am encountering an issue with my object named endpoints that contains various methods: const endpoints = { async getProfilePhoto(photoFile: File) { return await updateProfilePhotoTask.perform(photoFile); }, }; To access these methods, I am using ...

Creating a concise TypeScript declaration file for an established JavaScript library

I'm interested in utilizing the neat-csv library, however, I have encountered an issue with it not having a typescript definition file available. Various blogs suggest creating a basic definition file as a starting point: declare var neatCsv: any; M ...

How can I display every index from my JSON Fetched Files?

In the picture shown here, I have a series of Tables being displayed: The issue highlighted in red is that I want to show the Index of each JSON array as the Table number. Below is the code snippet: function getExternal() { fetch('https://kyoala ...

Issue: The spy MovieService.getWatchListedMovies was expected to have been called during the angular Unit Testing, but it was

There is a component file named watchlist which relies on MovieService(service) to retrieve movies. Invoking ngOnInit() will trigger MovieService.getWatchlistedMovies() The component code is provided below, export class WatchlistComponent implements ...

Enhancing Angular version from 5.2.7 to 5.2.10

After creating an Angular project using an older CLI version, the default installation was Angular version 5.2.7. Now, I am looking to upgrade my application to the latest stable Angular build, which is 5.2.10. One of the main challenges I'm facing i ...

Typescript's Patch<T> type enforces strictness within the codebase

There have been instances where I needed to 'patch' an object T using Object.assign(). For instance, when propagating changes you might modify a stateful object that other code references (common in reactive programming like MobX or Vue). It&ap ...

Utilizing TypeScript's generic constraints for multiple primitive data types

Consider the following function: myFunc(object: string | null): string | null {} The desired behavior for this function is to return type string when the object parameter is of type string, and return type string | null when the object parameter is of ty ...

Ways to set the className prop for all components automatically without having to specify it repeatedly

One challenge I face is dealing with code duplication whenever I create a new component. Is there a way to pass the className property between components without having to explicitly define it every time a new component is created? For example, when I cr ...

Manipulating Typescript JSON: Appending child attributes and showcasing them alongside the parent item attributes

Here is a JSON data that needs to be processed: var oldArr = [{ "careerLevel": "Associate", "careerLevels": [ { "201609": 21, "201610": 22, "careerID": "10000120" }, { "201609": 31, "201610": 32, ...

Possible revision: "Dynamic property naming in TypeScript interface based on specified type"

The concept might seem complex, but here's the gist of it. I have a User interface that may or may not contain certain properties depending on where it is fetched from. For example, there are optional properties like role and client_details. export i ...

Exploring the process of linking MatPaginator to a server-sourced datasource within an Angular Material table

In my Angular 5 project, I am utilizing Angular Material table to create a grid. The data is fetched from an HTTP request and stored in a variable named dataSourceNew within the view.ts file. Since dataSourceNew has dynamic content and structure, no interf ...

The expiration date is not considered in JWT authentication using passport-jwt

I have been working on implementing an authentication system using JWT token in Express, utilizing passport-jwt and jsonwebtoken. Everything is functioning correctly at the moment, however, I am facing an issue where the token remains valid even after its ...

Disappearance of Current User in Console When Refreshing Angular 4/5 Firebase

After creating an Angular 5 login using Firebase, I noticed an issue with the authentication object disappearing upon page reload. Even though the user remains logged in, the auth object vanishes once the page is refreshed (the username is still displayed ...

What is the process for exporting libraries in TypeScript?

Encountering an error when attempting to export socket.io using this method import socketIOClient from 'socket.io-client';. The error message is TS1192: Module '"***/node_modules/socket.io-client/build/index"' has no default e ...