Validating dynamic textboxes in Angular with custom rules

Creating dynamic textboxes with *ngFor in Angular

<tr *ngFor="let computer in _Computers; let i = index;">
<td>{{computer.Name}}</td><td>{{computer.Optional}}</td>
<td> <input matInput [formControl] = "frmCtrl"  name="UnitofPrice" [(ngModel)]="computer[i]">
</td>
<td>{{computer.UnitofPrice}}</td>

Typescript code for form control validation

public frmCtrl: FormControl = new FormControl('', this.customValidator());
customValidator() {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if ((!control.value)) {
        return { 'textRequired': true };
      }
      return null;
    };
 }

The current implementation validates empty textboxes. How can I modify the custom validator function to validate only based on the "Optional" property of the computer list? Any suggestions would be appreciated.

Answer №1

To improve the functionality of your form and formarray, it is recommended to make some adjustments. Currently, you are using only one formcontrol for your entire array, which may not be suitable for handling the array effectively.

In addition, the validator you have created essentially duplicates the built-in required validator. It would be more efficient to utilize the existing validator for this purpose. Here's a suggested approach:

You can hardcode the _Computers array, then create the form and loop through each item in the array to add formcontrols to the formarray. Depending on the value of the Optional property, set the Validators.required for the unit price only when necessary. Each formgroup in the array should contain two formcontrols: name and unitOfPrice, but you can adjust this as needed.

A getter function should be implemented for easy access to the formarray. The overall code structure would resemble the following:

// Code example here

It's worth noting that the use of any type is temporary for demonstration purposes; please replace it with appropriate data types.

The template will display the form, with validation messages shown whenever required:

// Template code here

The above uses div elements, but the same logic can easily be applied to a table layout as well.

For further reference, check out this STACKBLITZ 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

Guide on organizing the Object into a precise structure in Angular

I am looking to transform the current API response object into a more structured format. Current Output let temp = [ { "imagePath": "", "imageDescription": [ { "language": "en ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

Which JavaScript library or template engine would be most suitable for this scenario?

I am tasked with creating an invite your Facebook friends module that will display the names and photos of your friends, allowing you to message them. It is essential that this feature seamlessly integrates into my website's design, so I need to style ...

Dealing with unexpected modifications in a React class component

In short, I need to adjust the data in my class component before sending it to the server to match the API request format. To achieve this, I created a method called transformData within my class component which transforms the data extracted from the state ...

"Enhancing User Interaction with jQuery Hover State Dropdown Menus

Here's my issue: I've created a drop-down menu and I want the text color to change when hovering over the menu. Additionally, I'd like the hover state to remain active when hovering over the submenu. Currently, I'm using this code: $( ...

When running ng serve with Angular, an unexpected error arises: The workspace does not have the 'production' configuration set

When attempting to serve my Angular (9.1.12) application locally in production mode using ng serve --configuration=production, I encountered the following error: An unhandled exception occurred: Configuration 'production' is not set in the worksp ...

Struggling with displaying values from an array using getJSON

I've encountered an issue with displaying the results of a $.getJSON call. The code I have retrieves JSON data from a specific page. var loadItems = function() { if (hasNextPage === false) { return false } pageNum = pageNum + 1; var url = baseUr ...

Learn the process of submitting tag values using JohMun/vue-tags-input feature

I am a beginner in Vue.js and I am looking to implement an input field with multiple tags (user skills) using a Vue.js component. Although I have managed to make it work, I am struggling to figure out how to submit the tags in a form. Below is my code: T ...

Connecting the value of one input to influence another input

There are two input boxes provided - one for current address and another for permanent address. When the checkbox is clicked, the value of the current address should be displayed in the permanent address box. However, I am facing an issue where when I unc ...

Google Places Autocomplete with Angular 4 Material Design Integration

I'm looking to incorporate Google Places (autocomplete field) into my Angular 4/5 app that is styled using the Material UI framework. While I did come across a module here, it doesn't quite meet my needs as I am unable to style the input box wit ...

Discovering the method for accessing nested JSON data through ng-repeat in AngularJS

I'm attempting to access the items._id value within ng-view using ng-repeat. I am able to retrieve all data, but I am interested in specific data only. Data.json [ { _id : "td6v9db4514cc4ewew4334", firstName : 'ayaz', la ...

Removing a Child Object from a JSON Object in AngularJS

Encountering an error while attempting to remove a Child object Error Message: TypeError: ctrl.otsact.tests.splice is not a function HTML : <tr ng-repeat="act in ctrl.otsact.tests" ng-if="ctrl.editToggle"> <td><span ng-click="ctrl.r ...

Utilizing JavaScript to retrieve data from a self-submitting form

From my database, I am able to create a list of options for users to choose from. Once a selection is made, the values are submitted back to the same page and retrieved using Javascript. Within the same form, there are radio buttons and a multiple selecti ...

waiting to display information until it is necessary

I am currently working on optimizing my website for improved loading speed and responsiveness. Users can scroll through up to 4k images, apply filters, and sort them based on their preferences. Below is the code snippet for my filtering function: function ...

Utilizing TypeScript in a browser with a .NetCore WebApplication

After going through numerous articles, I have not been successful in finding a solution. My challenge lies with a .net core WebApplication that utilizes typescript code instead of javascript. Here are the specific requirements: I need to be able to debu ...

Using boolean flags in JavaScript and jQuery

I'm having trouble setting a boolean flag in JavaScript/jQuery. I thought that the flags should change globally after clicking btn1, but for some reason they remain unchanged when clicking btn2. What am I missing? JavaScript: $(document).ready(funct ...

Transform uploaded image file into a blob format and store it in a VueJS database

I am facing an issue with my form that has multiple inputs, including one of type "file". My goal is to upload an image and then submit the form to the API for storage in the database. <input name="image" class="w-full border-2 border-gray-200 rounded-3 ...

Managing Access Control Origin Headers in an Angular 4 Application

I currently have a Play framework based REST API running locally on port 9000 of my machine. Additionally, I have an Angular 4 application running on port 4200 on the same localhost. My goal is to have this Angular app display the JSON data received from ...

Showing a text value from a Github Gist on a Hugo website

I seem to be struggling with a seemingly simple task and I can't figure out what I'm missing. Any assistance would be greatly appreciated. I am working on generating a static site using Hugo. On one of my pages, I want to implement a progress ba ...

Using AJAX to showcase data from a table in a database using the <select> tag but with an unfinished submit process

I am encountering an issue with my code. When I submit the value in getinv.php, it only returns a partial value. For example, when I click '2016-08-27', it only retrieves '2016'... My question is, how can I ensure that the exact value ...