Issue: Control with the specified name '0' could not be located

Kindly review this code snippet and assist me in resolving the issue.
I have set up a formArray where the label and formControlName do not match, so I have utilized mapping to synchronize them. Upon receiving a response from the API, I initialize the form and update the form values based on the grants array.
The grants, also known as userPermissions, is an array of objects where each object represents a set of permissions for the institutions.

import {
  Component,
  Input,
  OnChanges,
  OnInit,
  SimpleChanges,
} from '@angular/core';
import { UserPermissionsService } from '../../../services/user-permissions.service';
import {
  AbstractControl,
  FormArray,
  FormBuilder,
  FormControl,
  FormGroup,
} from '@angular/forms';
import { Grant, UserPermissionsReponse } from '../../../modals/users.model';
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'web-messenger-user-permissions',
  templateUrl: './user-permissions.component.html',
  styleUrls: ['./user-permissions.component.scss'],
})
export class UserPermissionsComponent implements OnChanges, OnInit {
  @Input() userId = '';
  public permissionsForm: FormGroup;
  public isEditMode = false;
  public userPermissions!: Grant[];
  public allActions = [
    // List of actions
  ];
  public formControlLabelMapping!: { [key: string]: string };

  constructor(
    private userPermissionsSvc: UserPermissionsService,
    private fb: FormBuilder,
    private translate: TranslateService
  ) {
    this.permissionsForm = this.fb.group({
      grants: this.fb.array([]),
    });
  
  }

  ngOnInit(): void {
    this.initializeFormControlLabelMapping();
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes['userId'].currentValue) {
      console.log('user Id', this.userId);
      this.getUserPermissions(this.userId);
    }
  }

  get grantsFormArray() {
    return this.permissionsForm.get('grants') as FormArray;
  }


  getControls(control: AbstractControl): { [key: string]: AbstractControl } {
    return (control as FormGroup).controls;
  }

  // Methods for handling user permissions

Furthermore, the HTML code has been adjusted to accommodate the grantsFromArray and obtain the form controls with label mappings.

<form [formGroup]="permissionsForm">
        <div class="p-4 border dark:border-gray-700 rounded w-full shadow-sm">
          <!-- ... -->
          <h3 class="font-medium text-secondary dark:text-white text-lg mb-4 flex justify-between flex-wrap">
            {{'institutionGrants' | translate}}
            <button class="btn btn-primary dark:btn-accent btn-sm text-white" (click)="addNewPermissionsSet()">
              {{'addAdditionalInstitutionGrants' | translate}}
            </button>
          </h3>
          <h4 class="flex justify-between mb-3 text-base">
            <span>{{'institution(s)' | translate}}:</span>
            <span *ngFor="let institute of userPermissions">
              <a class="link text-primary dark:text-accent font-medium">Intelegencia Okta</a>
            </span>
          </h4>
          <div *ngFor="let grantControl of grantsFormArray.controls; let i = index">
            <ng-container [formGroupName]="i">
              <div *ngFor="let action of getControls(grantControl) | keyvalue">
                {{action.key}}
                <label class="cursor-pointer label mb-1 rounded px-3 border dark:border-gray-700">
                  <span>{{ formControlLabelMapping[action.key] }}</span>
      
                  <!-- Display 'Yes' or 'No' based on value --
                  
                </label>
              </div>
            </ng-container>
          </div>
          <!-- ... -->
        </div>
      </form>

Answer №1

Ensure you provide the formArrayName attribute for your formarray

<ng-container formArrayName="grants">
  <div *ngFor="let grantControl of grantsFormArray.controls; let i = index">
    ...
  </div>
</ng-container>

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

Issues with the drop-down menu in the <s:select> element arise when attempting to set the

While utilizing a Map to populate the Struts2 tag <s:select >, I have noticed that when the form is submitted multiple times, a blank line is added at the end of the list. For example, if the Map contains 2 key-value pairs, it displays 3 records and ...

Organizing outcome searches through ajax

I have a result table displayed on the left side https://i.stack.imgur.com/otaV4.png https://i.stack.imgur.com/pp9m0.png My goal is to transform it into the format shown on the right side of the table In a previous inquiry found here, @Clayton provided ...

Do devDependencies get installed when running `npm install -g my-package` command?

After browsing through this forum discussion, I found the answers a bit confusing and not directly addressing my concern. Therefore, I am posing a specific question: When using the command npm install -g my-package, are the dependencies listed under devDe ...

Scroll the table automatically when the currently selected row is the second-to-last row

Having trouble with a scrolling table issue. https://i.sstatic.net/PFyN3.png Upon page load, the first row (ROW 1) is automatically selected and highlighted. Clicking the next button selects and highlights the subsequent rows. However, once ROW >= 8 (e ...

Are there specific files or classes that store constants for different keyboard events?

When working in Angular, I often bind data with a host listener using code similar to the example below: @HostListener('window:keyup', ['$event']) onKeyUp(event: KeyboardEvent) { if (event.keyCode === 13) { this.onEnterClicked(ev ...

Error: Unable to access the 'CustomerId' property because it is undefined

Recently, I made some updates to my website. As part of the upgrade process, I switched to AngularJS v1.7.6 and JQuery v1.12.1. However, after making these changes, I encountered an error in my console log. TypeError: Cannot read property 'CustomerId ...

Encountered an Angular SSR error stating "ReferenceError: Swiper is not defined"

When attempting to implement SSR (Server-Side Rendering) in a new project, everything runs smoothly and without issue. However, encountering an error arises when trying to integrate SSR into an existing project. https://i.sstatic.net/QOI6A.png ...

Is it possible to apply the DRY Concept to this React JS code?

https://i.stack.imgur.com/jcEoA.png import React from "react"; import { Chip, Box } from '@mui/material'; const Browse = () => { const [chip, setChip] = React.useState("all" ...

The 'bind' property is not found within the 'void' data type

Here's the code snippet I'm working with: setInterval(this.CheckIfCameraIsAvailable(false).bind(this), 2 * 60 * 1000); private CheckIfCameraIsAvailable(forceCheck: boolean) { } I encountered the following error message: Property 'bin ...

Tips on persisting dynamic form data using JavaScript and a database query

I have a unique script that generates dynamic form content with inputs named "field-1", "field-2", and so on until the last input is created. How can I effectively save this dynamically generated form to the database? Usually, I would create a form with ...

What is the best way to use Jquery to enclose a portion of a paragraph text within a

How can I wrap the content inside a span that comes after another span, inside a paragraph and a new span? To further illustrate this, consider the following example: <p>foo <span>bar</span> baz</p> The desired outcome is: <p& ...

Updating Vue component with mismatched props

I am looking to optimize the Vue component where data is received in varying structures. Take for example Appointment.vue component: <template> <div> <div v-if="config.data.user.user_id"> {{ config.data.user.user_id ...

Can JavaScript be executed from the console while navigating between pages?

I am facing a challenge that I can't find any solutions for online or elsewhere. The task at hand seems straightforward. I am using the Chrome console and attempting to run Javascript code to navigate between pages with pauses in between. It feels lik ...

"Implement ngx-translate to cater to multi-language support in your Angular library

How can I effectively incorporate ngx-translate for handling translations within an Angular library? I have been experimenting with various methods, but have yet to find a successful solution. ...

Differentiating a path element in SVG by dynamically adding color using d3 and react

I have a unique SVG icon: <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <circle cx="12" cy="12" r="12" /> <path class="svg-fill" d="M12,2A10,10,0,1,0,22, ...

The Chrome (version 58) webdriverio is currently inactive, while Firefox is up and running

Previously, I successfully ran automation tests on Firefox and Chrome locally. However, there seems to be an issue that has arisen when trying to run them on Chrome recently. My system configurations: Operating System: Windows 10 (64-bit) Chrome Versio ...

Is it possible for a jQuery ajaxSuccess function to detect an AJAX event in a separate JavaScript file? If it is, what steps am I missing?

I've been attempting to initiate a function following an ajax event. I have been informed that despite the ajax event occurring in a different file (on the same server, if that makes a difference) and that the file is javascript, not jquery, "Ajaxsucc ...

The dimensions of the cards adjust automatically when the flex direction is set to row

My cards, created in CSS and React.js, have a set height and width. However, when I change the flex direction from column to row, the cards automatically shrink in size. Why is this happening? Card's CSS and JS code CSS .card{ height: 50%; w ...

Modifying input values in AngularJS/HTML

I'm encountering an issue with the ng-repeat function in AngularJS within my HTML code. The problem is that when I change the input with the ID 'add-price' in one cartproduct, it simultaneously changes in all other cartproducts as well. For ...

Removing a select menu in Discord.js once a selection has been made

Currently in the process of creating a ticket tool that utilizes a select menu for choosing a topic const row = new MessageActionRow() .addComponents( new MessageSelectMenu() .setCustomId(`select_menu`) .setPlac ...