Ending the iteration in a TypeScript/JavaScript function by utilizing a for loop within

Currently, I am facing a challenge in breaking an iterative loop and returning false when a specific condition is met.

Essentially, my goal is to determine whether a reactive form is empty or not:

 public isEmpty(form: AbstractControl): boolean {
    if (form instanceof FormGroup) {
      for (const key of Object.keys(form.controls)) {
        if (key !== 'modalite') {
          const control = form.get(key);
          if (control instanceof FormGroup) {
            this.isEmpty2(control);
          } else {
            if (control.value && control.value !== '') {
              return false;
            }
          }
        }
      }
    } else {
      if (form.value && form.value !== '') {
        return false;
      }
    }

    return true;
  }

The issue lies in the fact that my "return false" statement breaks out of the for loop but still continues iterating thereafter, resulting in always returning true. My aim is to return false and stop the iteration as soon as a non-empty form control is encountered. Any insights on how to achieve this would be greatly appreciated. Thank you!

Answer №1

It's more efficient to utilize the required validator instead of looping through all your controls.

const newControl = new FormControl('', Validators.required);
console.log(newControl.value);      // ''
console.log(newControl.status);     // 'INVALID'

Check out: https://angular.io/api/forms/FormControl

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

Analyzing Development Environment Metrics in Google Analytics 4

Is there a way to automatically filter out pageviews from localhost without having to manually create custom reports? I want to track developer traffic, but I don't want it to skew my data. In GA4, there are currently two options to filter out develo ...

Creating a personalized Typescript type declaration for a npm package in a Create React App

I'm having trouble incorporating a type declaration for the react-load-script package in my Create React App project. To address this, I created a file named react-load-script.d.ts within the src directory and included the following code: // Type de ...

What is the best way to upload a file using a relative path in Playwright with TypeScript?

Trying to figure out how to upload a file in a TypeScript test using Playwright. const fileWithPath = './abc.jpg'; const [fileChooser] = await Promise.all([ page.waitForEvent('filechooser'), page.getByRole('button' ...

javascript get the value of the text field

Is there a way to calculate even and odd numbers using a text field for entering the range of values and a select tag to choose between even and odd? How can I retrieve the value from the text field in order to pass it to the calculation function? Custom ...

Is it not the case that using spread syntax does not make a reference to the original array?

I am currently facing an issue with my React application. I have two Object arrays in my state, one called names and the other called shuffledNames. I am attempting to create a copy of the names array and shuffle it into the shuffledNames array. However, w ...

Adjusting the zoom level in leaflet.js ImageOverlay will cause the marker

Using ImageOverlay to display an image as a map with Leaflet.js, but encountering issues with marker positions shifting when changing the zoom level. Followed instructions from this tutorial, and you can find a code pen example here. // Code for markers ...

Type validation in TypeScript through cross-referencing variables

Can TypeScript be used to define a variable that determines the type of other variables? I want to simplify the process by only needing to check one variable, stateIndicator, which is dependent on other variables to infer their types. type A = {prop1: st ...

Is there a way to use HTML, JavaScript, and CSS to manipulate an object's opacity when a button is clicked?

I am looking to add a button on my website landing page that can hide the weather section, but I am unsure how to go about it! https://i.sstatic.net/COA82.jpg Currently, I am using a "selector" where I can choose either 0 or 1 from the bottom right corner ...

Creating a dynamic user interface in Angular 6 that successfully tracks changes without reliance on the parent

As I delve into the world of Angular, I am faced with a challenge in creating a reusable component that will be bundled into an npm module. The issue lies in the UI change detection aspect. In order for the component to function properly, the application ...

Tips for restricting User access and displaying specific sections of the menu

I have a component that utilizes map to display all menu parts. Is there a way to make certain parts of the menu hidden if the user's access rights are equal to 0? const Aside: React.FunctionComponent = () => { const[hasRight, setHasRight] = us ...

Is there a way to anticipate and address issues that are not directly related to the code, such as internet connectivity problems, in order to minimize disruptions?

Currently, I am in the process of developing code that can automatically download and unzip a file from a website. The code is set up to check for the latest version of the file every 4 hours, ensuring it doesn't redownload if already up to date. Howe ...

Is it appropriate to include JavaScript and CSS in views?

In my ASP.NET MVC project, I have set up a _Layout, a controller, and several views. Certain pieces of code are clearly global in nature, such as the CSS included in the _Layout file and other styles that are consistent throughout the site. However, when ...

How can I loop through SVG elements and attach an event listener to each one in JavaScript?

I am struggling with loading a simple SVG file and iterating through the shape nodes to add an onclick event. Unfortunately, after the SVG file is loaded, it cannot find the shape nodes. What could be the issue here? Here is the SVG code snippet: < ...

Upgrade jQuery visibility and opacity animations to pure JavaScript for a more lightweight solution

Currently I am in the process of removing jQuery from an older website. However, I have encountered a problem with an animation that is currently being used. I have managed to replicate the opacity fade effect, but I am struggling to smoothly transition t ...

Harnessing the Power of Webpack, TypeScript, and Sequelize: A Comprehensive Guide

After revising my query, I'm still encountering the same issue. The technologies I am utilizing include webpack, TypeScript, and Sequelize. My aim is to integrate Sequelize into a TypeScript backend file. I have successfully installed Sequelize and ...

Error: The property 'combine' of 'winston_1.default.format' cannot be destructured since it is not defined

Encountered an error while using Winston in Node.js, how can we resolve it? The version of Winston I am using is 3.3.3 and winston-daily-rotate-file version is 4.5.0 I attempted npm i winston@next --save, but the error persists. ** Here is the Error Mes ...

What is the best way to incorporate multiple JS files into Rails 6 using a template that I came across on the web

So, here's the dilemma... I've spent almost a month on this project and I'm at a loss for what to do next. I came across a fantastic Bootstrap theme online that includes a plethora of JavaScript files. Wanting to build the website in Rails 6 ...

Adding row numbers to a table generated by a JQuery DataTable with server-side data source can be achieved by implementing a custom function

Utilizing JQuery and DataTable to display data, I am unable to add row numbers to the grid generated on the client-side. Below is a snippet of my code: HTML <table id="applications_list" class="table table-bordered datagrid"> <thead> ...

Unable to move an element with Webdriver in Java Script

Trying to Drag an Element with the Following Code - "WebElement baseElement = driver.findElement(By.xpath("Element ID"); Actions clicker = new Actions(driver); clicker.moveToElement(baseElement).moveByOffset(20,0).click().perform(); Encount ...

Trying to call an applet method using JavaScript will not be successful

When trying to invoke methods of a Java applet using JavaScript, I encounter an issue that requires the site to be added to trusted sites and security set to low in order for it to work properly. Otherwise, an error is thrown: Microsoft JScript runtime ...