Troubleshooting: Angular add/edit form issue with retrieving data from a Span element within an ngFor loop

I am currently working on an add/edit screen that requires submitting a list, among other data. The user will need to check 2-3 checkboxes for this specific data, and the saved record will have multiple options mapped.

Here is what the HTML looks like:

<div class="col-sm-6 form-group">
          <label>P</label>
          <div class="form-control details">
            <div class="row" formArrayName="pay" *ngFor="let item of payArray.controls; let i = index;">
              <div class="col-12" [formGroupName]="i">
                <input type="checkbox" formControlName="selected" class="custom-checkbox-input">
                <span class="m-l-5" title="{{ item.Id }}">{{item.title}}xy</span>
              </div>
            </div>
          </div>
        </div>

On the .ts side, I am initializing it with this function:

getPay() {
    this.PayDS.getItems(true).subscribe(result => {
      this.ddlPay = result.list || [];
      this.payArray = this.form.get('pay') as FormArray;
      this.pay.clear();

      this.ddlPay.forEach(item => {
        console.log('item.Id = ' + item.Id + ', item.title = ' + item.title);
        this.payArray.push(this.formBuilder.group({
          Id: new FormControl(item.Id),
          title: new FormControl(item.title),
          selected: new FormControl({ value: item.selected })
        }));
      });

    });
  }

The Console.log() displays all records correctly, including Id and titles. Everything seems to be in order.

In the screen, I have the same number of records (11), each with checkboxes.

The issue? All the records are empty, without any text or title, just 11 checkboxes with no text displayed.

What I've tried so far:

  1. The "xy" next to the {{item.title}}xy does display, which confirms there are no missing classes or issues.

  2. The id that I added as a hint ("title") is not showing up when inspected in Chrome's elements tab

    <span class="m-l-5" title=""> xy</span>

  3. When I replaced {{item.title}} with {{ item }}, it showed "[object object]", indicating that the correct object is being passed.

Why is nothing being displayed? What could be going wrong here? Why are there no errors in the console or anywhere else? What else should I try?

Answer №1

<span class="m-l-10">{{item.controls.content.value}}</span>

Answer №2

Remember that your .subscribe() function does not automatically trigger change detection, so you will need to handle it manually.

Include private cd:ChangeDetectorRef in the constructor of your component, and after the forEach() loop inside the subscribe function, add this.cd.markForCheck();

fetchData() {
    this.dataService.getData().subscribe(data => {
        ...
        this.list.forEach(item => {
            ...
        });
        this.cd.markForCheck();
    });
}

Answer №3

Form groups are created with form controls labeled as Id and title.

It's important to note that these are actually FORM CONTROLS, not just simple values.

To display them, the following code is needed:

<span class="m-l-5" title="{{ item.Id.value }}">{{item.title.value}}</span>

If the selected control is not included in the formBuilder.group, it cannot be bound to. Make sure to include it for proper functionality.

Additionally, the correct syntax should be:

<div class="col-12" [formGroup]="payArray.controls[i]">

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

Module not found: vueform.config

For my current project, I decided to integrate Vueforms into the codebase. However, when I pasted their installation code into both my .ts and .js files, I encountered errors during the import of vueformconfig and builderconfig. This is a snippet of my ma ...

Discover the best way to emphasize a chosen mat-list-item using color in Angular

Is there a way in Angular to highlight mat-list-item elements with red color when clicking on Notification, Dashboard, or Comments? <mat-list> <mat-list-item style="cursor: pointer" routerLink="/base/dashboard">Dashboard</mat-list-item ...

Tips for ensuring the correct typing of a "handler" search for a "dispatcher" style function

Imagine having a structure like this: type TInfoGeneric<TType extends string, TValue> = { valueType: TType, value: TValue, // Correspond to valueType } To prevent redundancy, a type map is created to list the potential valueType and associate i ...

Unit Testing Sentry with Jest Framework using TypeScript in a Node.js Environment

I'm in the process of integrating Sentry into my existing NodeJS project, but I'm facing an issue with mocking a specific part of the Sentry code. Here's the relevant Sentry code snippet: const app: express.Express = express(); Sentry.init ...

What's the best way to implement an NPM package in a Deno application?

I am curious about integrating the NPM package into my Deno application. Can anyone guide me on how to achieve this? ...

Encountering an issue with the message: "Property 'ref' is not available on the type 'IntrinsicAttributes'."

Having trouble implementing a link in React and TypeScript that scrolls to the correct component after clicking? I'm using the useRef Hook, but encountering an error: Type '{ ref: MutableRefObject<HTMLDivElement | null>; }' is not assi ...

Using a generic type as a value in an abstract class <T, K extends keyof T> allows for flexible and dynamic data manipulation

Currently, I am in the process of transferring some logic to an abstract class. Let's look at the abstract generic class with specific constraints: abstract class AbstractVersion< TModel extends object, TProperty extends keyof TModel, T ...

Enhancing Angular2 authentication with Auth0 for enabling Cross-Origin Resource Sharing

I have been working on implementing user authentication through Auth0. I followed the instructions provided on their website, but I am encountering authentication issues. Whenever I try to authenticate, an error message appears in the console stating that ...

Encountered a ZoneAwareError while trying to incorporate angular2-onsenui into

Have you run the following commands in your terminal: npm install angular2-onsenui@latest --save npm install <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0bfbea3b5bea5b990e2fee2fea8">[email protected]</a> ...

Error: Unable to locate binding.gyp file

I'm currently in the process of setting up the required modules for my web application. As I execute $npm install, an error message pops up: john@mylaptop frontend % npm install > <a href="/cdn-cgi/l/email-protection" class="__cf_ ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

Troubleshooting: The reason behind my struggles in locating elements through xpath

There is a specific element that I am trying to locate via XPath. It looks like this: <span ng-click="openOrderAddPopup()" class="active g-button-style g-text-button g-padding-5px g-margin-right-10px ng-binding"> <i class=&quo ...

Issue with accessing container client in Azure Storage JavaScript library

When working on my Angular project, I incorporated the @azure/storage-blob library. I successfully got the BlobServiceClient and proceeded to call the getContainerClient method, only to encounter this error: "Uncaught (in promise): TypeError: Failed ...

Is there a way for my React application to detect changes in an npm package?

I am currently customizing an npm package for my application, but I am facing issues with it not being detected when starting my development server. Previously, I was able to resolve this by removing the library and reinstalling it, followed by replacing t ...

Utilizing a configuration file with Vue's `use` method

Within my index.ts file, I am setting up the configuration for the Google reCAPTCHA component using a specific sitekey: Vue.use(VueReCaptcha, { siteKey: 'my_redacted_sitekey' }); This setup occurs prior to the initialization of the new Vue({ ...

How to trigger a function in a different component using Angular 4

I have a query bar located within the header element, designed to search through a list in a separate component. How can I set up communication for the headerComponent to invoke a function in the BooksComponent? export class HeaderComponent { search ...

Incorporating Paypal subscription functionality and refining subscription challenges

The angular project I'm working on requires configuring a PayPal payment gateway for create subscription, cancel subscription, and upgrade subscription functionalities. I have encountered two issues with PayPal: 1) The PayPal button has been success ...

Dynamic URL in Angular service for JSON API request

Utilizing an Angular service, I am retrieving JSON data from a specified URL. Take a look at the code snippet provided below: import { Injectable } from '@angular/core'; import {Http,Response} from "@angular/http"; import { Observable } from "rx ...

What is the best way to bring in a service as a singleton class using System.js?

I have a unique Singleton-Class FooService that is loaded through a special import-map. My goal is to efficiently await its loading and then utilize it in different asynchronous functions as shown below: declare global { interface Window { System: Sy ...

After logging out, Next-auth redirects me straight back to the dashboard

In my NextJS application, I've implemented a credential-based authentication flow along with a dashboard page. To handle cases where an unauthorized user lands on the dashboard route, I've created a custom AccessDenied component. In the getServer ...