Errors have been encountered in the Angular app when attempting to add FormControl based on the data retrieved from the backend

This specific page is a part of my Angular application.

Within the ngOnInit method, I make two API calls to retrieve necessary data and iterate through it using forEach method to construct a reactive form. However, I am facing one of two different errors along the way.

One error looks like this: see image here

While the other error resembles this: check out image here

Sometimes, there are no errors at all.

I would appreciate any insights on what might be causing issues in my code.

Below is a snippet from my code:

user-manager.component.ts

export class UserManagerComponent implements OnInit {
    constructor(
    private fb: FormBuilder
  ) {}
    ngOnInit(): void {
        this.commonData.getDropdownData('menus')
        .pipe(takeWhile(() => this.alive))
        .subscribe(r => {
          if (r.status === 0) {
            this.menuForm = this.fb.group({});
            this.menuList = r.result.menus;
            this.menuList.forEach(i => {

              const control = new FormControl();
             (this.menuForm as FormGroup).setControl(i.MenuId, control);

              i.children.forEach(a => {
                const con = new FormControl();
                (this.menuForm as FormGroup).setControl(a.MenuId, con);
              });
            });
            this.isMenuFormReady = true;
      } else {
        this.toastrService.danger(r.message);
      }
    },
      error => {
        if (!environment.production) {
          this.menuForm = this.fb.group({});
          this.menuList = menuMock.menus;
          this.menuList.forEach(i => {

            const control = new FormControl();

            (this.menuForm as FormGroup).setControl(i.MenuId, control);

            i.children.forEach(a => {
              const con = new FormControl();
              (this.menuForm as FormGroup).setControl(a.MenuId, con);
            });

          });
          this.isMenuFormReady = true;
        }
          console.log(error);
      });

    this.commonData.getDropdownData('permissions')
    .pipe(takeWhile(() => this.alive))
    .subscribe(r => {
      if (r.status === 0) {
        this.permissionsForm = this.fb.group({});
        this.permissionsList = r.result;
        this.permissionsList = this.groupBy(this.permissionsList, function(item) {
          return [item.GroupId];
      });

      this.permissionsList.forEach(i => {

        const id = i[0].GroupId;
        this.permissionsForm.addControl(id, this.fb.group({}));

        i.forEach(a => {
          const con = new FormControl();
          (this.permissionsForm.get(id) as FormGroup).addControl(a.ActionId, con);
        });
      });
      this.isPermissionFormReady = true;

      } else {
        this.toastrService.danger(r.message);
      }
    },
      error => {
        if (!environment.production) {
          this.permissionsForm = this.fb.group({});
          this.permissionsList = userMock.Permission;
          this.permissionsList = this.groupBy(this.permissionsList, function(item) {
            return [item.GroupId];
        });

          this.permissionsList.forEach(i => {

            const id = i[0].GroupId;
            // console.log('id: ', id)
            this.permissionsForm.addControl(id, this.fb.group({}));

            i.forEach(a => {
              const con = new FormControl();
              (this.permissionsForm.get(id) as FormGroup).addControl(a.ActionId, con);
            });
          });
          this.isPermissionFormReady = true;
          // console.log(this.permissionsForm);
        }
          console.log(error);
      });
  }
    groupBy( array , f ) {
        const groups = {};
        array.forEach( function(o) {
            const group = JSON.stringify( f(o) );
            groups[group] = groups[group] || [];
            groups[group].push( o );
        });
        return Object.keys(groups).map( function( group ) {
            return groups[group];
        });
    }
}

user-manager.component.html

      <nb-card>

          <nb-card-header>
            Form 1
          </nb-card-header>
          <nb-card-body>
              <form [formGroup]="permissionsForm" autocomplete="off" *ngIf="isPermissionFormReady">
            <nb-card *ngFor="let item of permissionsList; let i = index;" [formGroupName]="i">
              <nb-card-header>
                {{item[0].GroupName}}
              </nb-card-header>
              <nb-card-body class="pt-0">
                <div class="row">
                  <div class="col-4 my-1" *ngFor="let permission of item">
                    <label>
                      <input type="checkbox" [formControlName]="permission.ActionId"/>
                      {{permission.ActionName}}
                    </label>
                  </div>
                </div>
              </nb-card-body>
            </nb-card>
          </form>
          </nb-card-body>

        </nb-card>

        <nb-card>
            <nb-card-header>
              Form 2
            </nb-card-header>
            <nb-card-body>
              <form [formGroup]="menuForm" autocomplete="off" *ngIf="isMenuFormReady">
                <div class="row">
                    <div class="col-4" *ngFor="let menu of menuList" >
                        <nb-card>
                          <nb-card-header>
                            <label>
                              <input type="checkbox" id="{{menu.MenuId}}" [formControlName]="menu.MenuId" (change)="menuClick($event)"/>
                              {{menu.title}}
                            </label>
                          </nb-card-header>
                          <nb-card-body class="pt-0">
                            <div class="row">
                              <div class="col-12 my-1" *ngFor="let item of menu.children">
                                <label>
                                  <input type="checkbox" id="{{item.MenuId}}" [formControlName]="item.MenuId" (change)="menuClick($event)"/>
                                  {{item.title}}
                                </label>
                              </div>
                            </div>
                          </nb-card-body>
                        </nb-card>
                      </div>
                </div>
              </form>
            </nb-card-body>
          </nb-card>

Answer №1

If you're encountering a bug in Chrome 80 where Array.reduce isn't functioning as expected, especially when using reactive forms in your Angular project, you may come across browser-specific issues like 'form.get('key').value' being undefined or 'valuechanges' being undefined even if it exists - an issue that was not present in Chrome 79. To resolve this problem, manually add the Array.reduce polyfill to your Angular project by following the steps below.

Insert the following code into your main.ts file:

(function () {
 function getChromeVersion() {
 const raw = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);

 return raw ? parseInt(raw[2], 10) : false;
    }

 const chromeVersion = getChromeVersion();
 if (chromeVersion && chromeVersion >= 80) {
      Array.prototype.reduce = function (callback /*, initialValue*/) {
 'use strict';
 if (this == null) {
 throw new TypeError('Array.prototype.reduce called on null or undefined');
        }
 if (typeof callback !== 'function') {
 throw new TypeError(callback + ' is not a function');
        }
 let t = Object(this), len = t.length >>> 0, k = 0, value;
 if (arguments.length === 2) {
          value = arguments[1];
        } else {
 while (k < len && !(k in t)) {
            k++;
          }
 if (k >= len) {
 throw new TypeError('Reduce of empty array with no initial value');
          }
          value = t[k++];
        }
 for (; k < len; k++) {
 if (k in t) {
            value = callback(value, t[k], k, t);
          }
        }
 return value;
      };
    }
  })();

ForMoreInfo

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

Use ngClass to dynamically change the color of a button when it is clicked. This functionality can be applied to buttons

In my application, there are 80 buttons displayed on the screen using the following code: <tr *ngFor="let plans of PlanList"> <td class="text-primary">{{plans.typename}} </td> <td class="text-center&quo ...

What is the best way to bring in local modules within the browser environment using Playwright?

Let me illustrate what I am attempting to achieve: ../src/Foo/Bar.ts represents a local TypeScript file This particular file contains code that is designed to function within a browser environment (it utilizes WebSockets), and therefore needs to be execu ...

The information in the map cannot be inferred by Typescript based on the generic key type

I encountered a TypeScript issue while refactoring an existing feature in my app. It seems that TypeScript is having trouble picking up the correct type when passing the generic type through nested functions. enum App { AppOne = 'app-one', A ...

Angular - Ensuring the Independence of Field Pairs During Validation

I need to independently validate two sets of fields. One set is for passwords, which should match each other. The second set is for email addresses, which should also match. The current method I have tried isn't working. Can someone guide me on how ...

Typescript: Utilizing a generic array with varying arguments

Imagine a scenario where a function is called in the following manner: func([ {object: object1, key: someKeyOfObject1}, {object: object2, key: someKeyOfObject2} ]) This function works with an array. The requirement is to ensure that the key field co ...

Avoiding Overload Conflicts: TypeScript and the Power of Generic Methods

I have created an interface type as follows: interface Input<TOutput> { } And then extended that interface with the following: interface ExampleInput extends Input<ExampleOutput> { } interface ExampleOutput { } Additionally, I ha ...

ng2-table ways to customize the appearance of a particular row

Hey there, I'm currently new to Angular 2 and working with ng2-table. I've successfully added a table like the one shown here to my website. Now, I'm trying to figure out how to add color to specific rows within the table. Following the ste ...

Issue: NG05105 - Unforeseen artificial listener detected @transform.start

Encountered an issue in my Angular 17 app using Angular Material during the execution of ng test: Chrome browser throws 'app-test' title error in the AppComponent with the following message: Error: NG05105: Unexpected synthetic listener @ ...

What is the best way to verify the input of a TextField element?

When I visited the Material UI Components documentation for TextField, I was hoping to find an example of validation in action. Unfortunately, all they showed was the appearance of the invalid TextField without any insight into the actual validation code i ...

Creating divs dynamically in a loop and displaying them upon clicking a button in Angular

I am trying to dynamically create divs in a loop and show the selected div when I press a specific button. In theory, this is how I envision it... <div>div1</div><button (click)="showDiv(divID)">showDIV</button> To hide a ...

Unleashed Breakpoint Mystery in Ionic 5 Angular with VSCode

I recently upgraded my Ionic 5 Angular 12 app from Ionic 4 Angular 8. The application is working well and remains stable, but I have encountered some issues while debugging. Firstly, when I use the launch.json file in Visual Studio Code to run the app, it ...

Resetting ng-select values in an Angular application: A quick guide

Currently, I am utilizing ng-select within a modal window. <div class="modal-body"> <div class="form-group has-feedback"> <ng-select #select name="currenies" [allowClear]="true" [items]="currencyList" [disabled]="disabled" (selected)="sel ...

I'm encountering a 502 error while trying to use Supabase's signInWIthPassword feature

Despite all authentication functions working smoothly in my React, TypeScript, and Supabase setup, I'm facing an issue with signInWithPassword. In my context: I can successfully signIn, create a profile, and perform other operations like getUser() an ...

Using AKS Kubernetes to access a Spring Boot application from an Angular frontend using the service name

I have developed two frontend applications using Angular and a backend application using Spring Boot. Both apps are running in the same namespace. I have already set up two services of type Loadbalancer: The frontend service is named frontend-app-lb (exp ...

Sharing API data between components in Angular 5

Summary: I'm trying to retrieve data from an input field in a component form, then compare it using API services. After that, I want to take the value from the "correo" field in the form and pass it to another component. In this other component, I aim ...

Guide: Implementing material-ui theme with redux in gatsby

I'm currently utilizing the material-ui theme in conjunction with redux-toolkit within a gatsby project. This is my theme.ts file: import { createMuiTheme } from "@material-ui/core"; import { useSelector } from "react-redux"; import { State } from ". ...

Utilizing Input Value from Parent Component in Angular TypeScript File: A Guide

Is there a way to manipulate the @Input()items in the child-component.ts file before passing it to child-component.html? Currently experiencing an issue where I get an empty object when logging in the ngOnInit method. child-component.ts @Input()items: ...

Developing Custom Methods with TypeScript Factories - Step 2

Working in a factory setting, I find myself needing to incorporate custom methods at some point. Thanks to the valuable input from the community, I've made progress towards my goal with this helpful answer, although I'm required to include a see ...

When a property is removed from a variable in an Angular Component, it can impact another variable

During the iteration of the results property, I am assigning its value to another property called moreResults. After this assignment, I proceed to remove array elements from the testDetails within the moreResults property. However, it seems that the remova ...

Struggling with fetching the email value in .ts file from ngForm in Angular?

I'm trying to retrieve the form value in my .ts file, but I am only getting the password value and not the email. Here is the code snippet: <div class="wrapper"> <form autocomplete="off" class="form-signin" method="post" (ngSubmit)="lo ...