Verifying input fields array in Angular 2 and above

Check out this plunk showcasing an Angular form with a single input field and an array of input fields. Validation is needed to ensure that none of these fields are left empty.

The validation for the single field is working as expected, but I'm encountering issues when trying to validate the array of fields. An error

Error: Cannot assign to a reference or variable!
is appearing when the form is displayed. Any suggestions on how to resolve this issue in the plunk example?

@Component({
  selector: 'my-app',
  template: `
   <form #f="ngForm" name="form" (ngSubmit)="ok(f.form)" novalidate>
       <input name="singleField" id="singleField" [(ngModel)]="field1"  
              #singleField="ngModel" required />
       <div *ngIf="singleField.touched || submitted" class="errorMsg">
            <label *ngIf="singleField.control.hasError('required')">
                Field is required
            </label>
       </div>
       <br/><br/>
       <div *ngFor="let field2 of manyFields; let i = index">
           <input name="field" id="field" [(ngModel)]="field2"  
                  #field="ngModel" required />
           <div *ngIf="field.touched || submitted" class="errorMsg">
                <label *ngIf="field.control.hasError('required')">
                    Field is required
                </label>
           </div>
       </div>
       <br/><br/>
       <button type="submit">Submit</button>
   </form>
  `,
  styles: [`
    .errorMsg {
      color: red;
    }
  `]
})
export class App {

       field1: string = 'delete this';
       manyFields: string[] = ['Field 1', 'Field 2', 'Field 3'];

       ok(form: any){
            if (form.valid)
                 alert("Form is valid");
            else     
                 alert("Form is NOT valid");
       }
}

Answer №1

An issue occurred: Unable to allocate a reference or variable
due to [(ngModel)]="field2", it's not possible to assign field2

This solution resolves the error and enables the required validation feature

<input [name]="field2" [id]="field2" ngModel #field="ngModel" required /> 

I am utilizing the value of field from both the name and id attributes.

Validating dynamic fields

  validateMultipleFields(form: any) {
    let fields: string[] = [];

    if (form && form.value) {
      for (let f of this.manyFields) {
        if (form.value[f] === '') {
          fields.push(f)
        } 
      } 
    }

    if (fields.length > 0) {
      return { fields: true, message: `${fields.join(',')} are empty` }
    } else {
      return { fields: false, message: '' }
    }

  } 

Template

    <div class="errorMsg" *ngIf="validateMultipleFields(f).fields">
        {{validateMultipleFields(f).message}}
    </div>

View stackblitz demo

The template form is designed for simple forms, cleaner validation can be achieved through reactive forms using Form Array. Consider implementing reactive form for improved functionality

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

In TypeScript, what is the format in which the final type result of a generic utility type is shown?

After utilizing the provided code, I have encountered an issue with retrieving the ultimate type of type A in the editor. Despite my efforts, the editor persistently showcases the composite form of the generic utility, complicating the process of verifyi ...

Is it necessary to increment the major version of a package when updating one of its dependencies to a major version?

As I explore upgrading an RxJS dependency from v5.5 to v6 in my npm package, I am not expecting any challenges based on the migration guide. However, I am contemplating whether the updated version of my package should trigger a new major release. While I ...

Pass the API_BASE_URL parameter from the Angular 7 configuration

Currently, I am developing an Angular 7 Application using es6 Javascript and Swagger integration. My current challenge involves adding the configuration to APP_INITIALIZER in the app.module file: export class SettingsProvider { private config: AppConfi ...

Error: The property referenced in the Typescript Ref of another Ref does not exist on the specified type

Utilizing the library https://github.com/lhz516/react-h5-audio-player, I am facing a challenge in correctly defining the type for my useRef without resorting to useRef<any>(null). I have managed to access and modify the audio element using the code ...

Error: Angular detected a change in the expression after it was already checked

Being a novice in Angular, I am attempting to construct form validations using code. My requirement is that when I click on the Reset button, the fields should reset. To achieve this, I followed the code below. However, the issue arises when I tap on the ...

Typescript encounters transpilation issues when the spread operator is omitted for undefined values {...undefined}

I am currently working on a TypeScript project where I have encountered a peculiar issue. Within some of my TypeScript files, I am including a plain JavaScript/Node file named config.js. The content of config.js is as follows: 'use strict'; modu ...

Why is npm/bower necessary only for AngularJS?

I am currently exploring the differences between npm and bower, their usage, how they work, and their purposes. Most explanations I have come across mention that these tools are primarily used in NodeJs development. However, when I delved into AngularJS2 t ...

Enriching HtmlElement with a type property using TypeScript

Check out my TypeScript code snippet below: let script: HTMLElement = document.createElement("script"); script.appendChild(document.createTextNode(` { "json": "property" } `)); script.id = 'appContextModel'; document.body.appendChild(scr ...

Create two separate subdirectories within the Angular project for each of the development projects

1-I recently deployed an Angular project to my hosting service and it is working fine. () 2-I decided to create a new folder on my host named '/magazine'. 3-In this new folder, I am developing another project, a magazine website. However, when ...

What is the best way to transfer an image between Angular components and then showcase it?

I've developed a feature using an observable and I'm attempting to transfer a dataURL from one component to another in order to display it as an image. Here is the HTML code for the component where I want to send data from: <canvas id="p ...

Having issues with Bootstrap customization in an Angular 7 project

I am currently working on customizing a Bootstrap 4 theme within an Angular 7 project. After installing Bootstrap, I updated my angular .json file to include the following: "styles": [ "./node_modules/@angular/material/prebuilt-themes/de ...

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: https://i.sst ...

Tips for managing nested data in Angular 4 using a Bootstrap 4 data-table

I am currently using the Data Table from a GitHub project found at: https://github.com/afermon/angular-4-data-table-bootstrap-4-demo. It works perfectly with data structured in a key-value format like the sample provided. However, I am facing challenges wh ...

Develop an observer to retrieve values from a CSV file

My current objective is to read a csv file and retrieve its content as a string. I attempted using an Observable to achieve this functionality. Initially, I used the observable and filereader combination like so: readDocument(fileChangeEvent: Event) { ...

In Angular2, the derived class can inherit decorators

Within my Angular application, I am utilizing the BaseComponent which has a specified template. My goal is to use this same template HTML in a component that extends the base one. However, I am aware that class inheritance in Angular2 only applies to cla ...

Exploring the functionality of className using materialUI

Attempting to test whether my component has a specific class is proving challenging. This difficulty stems from the fact that the class is generated using MaterialUI. For instance, I am looking for a class named spinningIconCenter, but in reality, it appea ...

Issue ( Uncaught TypeError: Trying to access a property of undefined ('data') even though it has been properly defined

One of my custom hooks, useFetch, is designed to handle API data and return it as a state. useFetch: import { useState, useEffect } from "react"; import { fetchDataFromApi } from "./api"; const useFetch = (endpoint) => { const [d ...

Error encountered in Angular CLI: Attempting to access property 'value' of an undefined variable

I am encountering an issue while trying to retrieve the values of radio buttons and store them in a MySql database. The error message I receive is TypeError: Cannot read property 'value' of undefined. This project involves the use of Angular and ...

Combining and compressing files in an Angular 2 quick start project

What is the best way to bundle and minify an Angular 2 quick start project to decrease HTTP requests during the initial load? When the first page of the Quick start project loads, it generates approximately 300 HTTP requests, resulting in significant dela ...

Warning: NG2 RC5 has deprecated the use of HTTP_PROVIDERS

With the release of Angular2 version RC5, there have been some changes such as deprecating HTTP_PROVIDERS and introducing HttpModule. While my application code is functioning properly with this change, I am facing difficulties in updating my Jasmine tests. ...