Having troubles with *ngFor in Angular 8? Learn how to use ng-template effectively

I need assistance creating a table with dynamically generated columns and using the PrimeNg library for the grid.

Despite asking several questions, I have not received any responses. Can someone please help me achieve this?

To generate table column headers, I utilized *ngFor in combination with an array of row data and another array for column names.

Below is an example of my row data array that contains one row:

uersSurveyAnswers: any = [
    {
      userEmail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="51303c30233011363c30383d7f323e3c">[email protected]</a>',
      qustns: [
        {
          qNo: 1,
          ansrs: ['1']
        },
        {
          qNo: 2,
          ansrs: ['1', '0', '1', '1']
        },
        {
          qNo: 5,
          ansrs: ['2']
        },
        {
          qNo: 6,
          ansrs: ['0', '1', '1', '0']
        }
      ]
    }];

The mapping between columns and data should be as follows:

column Q1.1 - > uersSurveyAnswers -> qustns[0].ansrs[0]
column Q2.1 - > uersSurveyAnswers -> qustns[1].ansrs[0]
column Q2.2 - > uersSurveyAnswers -> qustns[1].ansrs[1]
column Q2.3 - > uersSurveyAnswers -> qustns[1].ansrs[2]
column Q2.4 - > uersSurveyAnswers -> qustns[1].ansrs[3]
column Q5.1 - > uersSurveyAnswers -> qustns[2].ansrs[0]
column Q6.1 - > uersSurveyAnswers -> qustns[3].ansrs[0]
column Q6.2 - > uersSurveyAnswers -> qustns[3].ansrs[1]
column Q6.3 - > uersSurveyAnswers -> qustns[3].ansrs[2]
column Q6.4 - > uersSurveyAnswers -> qustns[3].ansrs[3]

Here is the HTML code snippet:

And here is the columns array:

columns = [ ... ]; // The columns array content goes here 

This array of columns is dynamically generated.

The challenge I am facing lies within the second 'ng-template' tag which contains 'let-surveyAnswer', representing the row data.

If I create a column with:

<td>{{surveyAnswer.qustns[0].ansrs[0]}}</td>

It correctly displays the row data. However, using *ngFor like this:

<td *ngFor="let col of columns">
  {{col.field}}
</td>

Where 'col.field' contains the data such as 'qustns[0].ansrs[0],' poses a challenge.

I ideally want to achieve something similar to:

<td *ngFor="let col of columns">
      {{surveyAnswer.col.field}}
    </td>

For further clarification, you can access the Stackblitz URL here.

Please provide guidance on how to address this issue. Thank you!

Answer №1

An issue arises in your ngOnInit() method where you attempt to assign field values as follows:

{
  field: 'qustns[0].ansrs[0]',
  header: 'Q1.1',
}

The problem lies in the fact that you are assigning field to the string 'qustns[0].ansrs[0]' instead of the actual value. To correct this, adjust it to:

{
  field: this.uersSurveyAnswers[0].qustns[0].ansrs[0],
  header: 'Q1.1',
}

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

Store Angular 17 control flow in a variable for easy access and manipulation

Many of us are familiar with the trick of "storing the conditional variable in a variable" using *ngIf="assertType(item) as renamedItem" to assign a type to a variable. This technique has always been quite useful for me, as shown in this example: <ng-t ...

While working with Ngrx/effects, an error with code TS2345 occurred. The error message stated that the argument is of type 'Product[]', which cannot be assigned to a parameter of type

When I compile my code, I encounter the following issue (despite not finding any errors in the browser console and the application functioning properly). An error occurs in src/app/services/product.service.ts(15,9): The type 'Observable<Product> ...

Switching slides in Ionic 4 with a simple button click

I want to switch slides by clicking a button on my presentation. Here is an example code snippet: <ion-slides> <ion-slide> Slide one <ion-slide> <ion-slide> Slide Two <ion-slide> </ion-slides> <butt ...

When integrating the @azure/msal-angular import into the Angular application, the screen unexpectedly goes blank,

Starting a new Angular app and everything is rendering as expected at localhost:4200 until the following change is made: @NgModule({ declarations: [ AppComponent, HeaderBannerComponent, MainContentComponent, FooterContentinfoComponent ...

Join a subscription and remain subscribed in sequential order

Within the code below, there is a nested subscribe function. It takes a schedule_id and retrieves questions based on that schedule_id. The functionality works correctly, but the order in which getQuestion() is executed is not guaranteed. Schedule IDs: 111, ...

Retrieving rows from a MySQL table that contain a specified BIGINT from an array parameter

I've encountered a problem with mysql while using serverless-mysql in TypeScript. It seems like my query might be incorrect. Here is how I am constructing the query: export default async function ExcuteQuery(query: any, values: any) { try { ...

How can I prevent the enter key from working with Twitter Typeahead?

Is there a way to prevent the enter key from being pressed on an element within Twitter Typeahead's dropdown feature while using Angular with Typescript? I attempted to utilize preventDefault() when event.keycode === 13 on the ng-keydown event for th ...

The properties are absent in Angular Service - Observable

I recently started learning angular and I'm struggling to make this HTTP get request work. I have been looking at various examples of get requests for arrays and attempted to modify one for a single object (a user profile) but without success. The err ...

Encountering a TypeScript type error when returning a promise from a function

I currently have a scenario in which there is a function that checks if user whitelisting is required. If not, it calls the allowUserToLogin function. If yes, it then checks if a specific user is whitelisted. If the user is not whitelisted, an error is thr ...

What could be causing the React text input to constantly lose focus with every keystroke?

In my React project using Material-UI library, I have a component called GuestSignup with various input fields. const GuestSignup = (props: GuestSignupProps) => { // Component code goes here } The component receives input props defined by an ...

Higher-Order Component integrated with HTMLElement

Check out this complex code snippet I created: export type AdvancedHoverElementProps<TElement extends HTMLElement> = React.HTMLProps<TElement> & { hoverDuration: number, onHoverChanged: (isHovering: boolean) => void }; export ...

Using GSAP in an Ionic application

What is the best way to add the GSAP library to an Ionic project? Simply running npm install gsap doesn't seem to work when I try to import it using: import { TweenMax, TimelineMax} from "gsap"; I am currently using TypeScript. Thank you. ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

Learn how to define an object with string keys and MUI SX prop types as values when typing in programming

I want to create a comprehensive collection of all MUI(v5) sx properties outside of the component. Here is an example: const styles = { // The way to declare this variable? sectionOne: { // What type should be assigned here for SXProps<Theme>? } ...

Can you explain the significance of using curly braces in an import statement?

The TypeScript handbook has a section on Shorthand Ambient Modules, where an import statement is shown as: import x, {y} from "hot-new-module"; It doesn't explain why y is in curly braces in the above statement. If both x and y were inside the brace ...

Troubleshooting issues with importing modules in TypeScript when implementing Redux reducers

Struggling to incorporate Redux with TypeScript and persist state data in local storage. My current code isn't saving the state properly, and as I am still new to TypeScript, I could really use some suggestions from experienced developers. Reducers i ...

Angular (TypeScript) time format in the AM and PM style

Need help formatting time in 12-hour AM PM format for a subscription form. The Date and Time are crucial for scheduling purposes. How can I achieve the desired 12-hour AM PM time display? private weekday = ['Sunday', 'Monday', &apos ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...

Tips for conducting tests on ngrx/effects using Jasmine and Karma with Angular 5 and ngrx 5

Here is the file that I need to test. My current focus is on some effects service while working with Angular5 (^5.2.0) and ngrx5 (^5.2.0). I have been struggling to properly implement the code below for testing purposes. Any tips or suggestions would be ...

Adjusting an item according to a specified pathway

I am currently working on dynamically modifying an object based on a given path, but I am encountering some difficulties in the process. I have managed to create a method that retrieves values at a specified path, and now I need to update values at that pa ...