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

Is there a way to enhance a pre-existing component in Angular?

Trying to integrate an Angular component and wanting to implement a unique template. By referencing the documentation, it is possible to customize the menuComponent by utilizing the built-in TextInputAutocompleteMenuComponent component to apply a custom t ...

Challenges in Testing Angular 2

During my efforts to conduct integration tests using Angular 2 and Karma test runner, I encountered a perplexing issue. Regardless of the expected outcome, a particular test was consistently passing instead of failing as it should have been. The problem ar ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

release a Node.js module on NPM

Being a complete beginner in creating npm packages using typescript2 and angular2, I find myself in need of creating an npm package and publishing it on our company's private repository. I've managed to generate files like d.ts and .js. But how ...

A step-by-step guide to resolving the TS2345 compilation error during your TypeScript upgrade from version 4.7 to 4.8

We encountered a compiling error after upgrading from TypeScript 4.7.4 to a newer version (specifically, 4.8.4). This error was not present in our codebase when using 4.7.4. To pinpoint the issue, I have extracted the error into a small code snippet. When ...

When using ngStyle to bind a variable, the binding variable will be null

Currently, I am attempting to utilize ngStyle to set the background image. <div class="artist-banner fluid-banner-wrapper" [ngStyle]="{'background-image': 'url(../imgs/banner/' + event?.category + '.jpg)' }"> The fun ...

Adonisjs latest version (v5) model creation command malfunctioning

Using Adonisjs v5 The controller command works fine with: node ace make:controller Posts However, the new model creation command is not working: node ace:make model Post When running the make model command, an error occurs: An error message stating &ap ...

Resolve the issue of text overflow in PrimeNG Turbo Table cells

When utilizing Primeng table and enabling the scrollable feature, the table is expected to display a scrollbar while ensuring that the text within the cells does not overflow. Unfortunately, this expected behavior is not occurring. To see an example of th ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Trouble with running the "npm run tsc" command in Angular 2 beta

I'm facing an issue with compiling my Typescript using the command npm run ts. What's odd is that I can successfully compile and run it by running npm start. Below is the log: 0 info it worked if it ends with ok 1 verbose cli [ 'node' ...

Unable to locate any NativeScript modules for tns-core-module/ui

I'm working on a {N}-Application and facing an issue with importing Images from the tns-core-modules/ui/image module. Unfortunately, it seems that the target cannot be found within the tns-core-module. This is my code snippet: import * as ImageModul ...

Creating a Powerful Application with Typescript and NodeJS

Currently, I am attempting to utilize Got with Typescript and ESM. With Got being written in Typescript itself, I anticipated a seamless integration. Alas, even after diligently following this comprehensive guide authored by the creator of Got, I am unable ...

I can't figure out why I'm getting the error message "Uncaught ReferenceError: process is not defined

I have a react/typescript app and prior to updating vite, my code checked whether the environment was development or production with the following logic: function getEnvironment(): "production" | "development" { if (process.env.NODE_E ...

Changing the background color of a selection in Angular can be customized by modifying

Is there a way to customize the background color of a select element in Angular? I would like to change the default grey background to white. How can this be achieved? Below is the code for my select element: <select id="areaOfExpertiseFilter" ...

Error: The object is not defined (evaluating '_$$_REQUIRE(_dependencyMap[32], "react-native-safe-area-context").SafeAreaView')

I am currently working on developing a chat application using react-native with the following dependencies: "dependencies": { "@react-native-async-storage/async-storage": "~1.17.3", "@react-native-community/masked ...

Retrieve user information by their unique user ID from a MongoDB database using a Node, Express, and TypeScript API

Currently, I am working on a Node JS and Express with TypeScript API project. In this project, I need to retrieve data stored by a specific user from MongoDB based on their user ID. This is a snippet from my DataRouter.ts: router.get('/:userId', ...

does not have any exported directive named 'MD_XXX_DIRECTIVES'

I am currently learning Angular2 and I have decided to incorporate angular material into my project. However, I am encountering the following errors: "has no exported member MD_XXX_DIRECTIVES" errors (e.g: MD_SIDENAV_DIRECTIVES,MD_LIST_DIRECTIVES). Her ...

Place the setState function within the useEffect hook

I'm currently working on a project that includes a "login" page. Once the user logs in, they should be directed to an interface displaying all their lists. To ensure this data loads immediately after login, I have implemented the useEffect hook and u ...

Is it possible for me to add a string to a URL as long as the string is not null?

When retrieving data from a database, I have the option to include specific parts for a more targeted search. Let's say I have an object structured like this: { title: "wonderland", aliases: "", ... } My goal now is to generate a URL for the ...

An error is thrown when a try/catch block is placed inside a closure

An issue arises when attempting to compile this simple try/catch block within a closure using TypeScript: type TryCatchFn = (args: any, context: any) => void; function try_catch(fn: TryCatchFn): TryCatchFn { return (args, context) => void { ...