Is there a problem with *ngFor not functioning as expected in Angular 2?

I'm currently working on a project that involves using the GoogleChart. However, I've encountered an issue where only one chart is being created instead of the expected four instances of the GoogleChart. I'm not sure why this is happening as there are four elements in the GoogleChart. It's puzzling why only one chart is being generated when it should be four.

Here is my code snippet:

profile-component.html:

<h2>Employee's Attendance Profile:</h2>
<div *ngFor="let member of chartObject; let i=index"  >
    <div class="col-md-6"
     [chartData]="member.data" id="i"
     [chartOptions] = "member.options" 
     chartType="PieChart" 
     GoogleChart>
</div>
</div>

profile-component.ts:

import { Component, OnInit, HostBinding, Input }         from '@angular/core';
import { Router, ActivatedRoute }                 from '@angular/router';
import { slideInDownAnimation }                  from '../../animations/animations'
import { GoogleChart}                             from'../../../../directives/angular2-google-chart.directive';
import { ProfileService                         } from '../../services/profile-component.service';
declare var bootbox: any;
@Component({
  selector: 'profile-component2',
  templateUrl: `../app/modules/dashboard/dashComponents/profileComponents/profile.component.html`,
  animations: [slideInDownAnimation],
  styles: [`
    .chart-css{
      height:400px;width:400px;border:0px solid red;flot:left;
    }
    `]
})

export class ProfileComponent2 implements OnInit {
  constructor(private profileService: ProfileService) { }
  name = "Shubham";
  message: string;
  @HostBinding('@routeAnimation') routeAnimation = true;
  @HostBinding('style.display') display = 'block';
  @HostBinding('style.position') position = 'absolute';
  public login: {} = {};
  private interval: any;
  private members: any;
  private totalMemberWithLeaves: number;

  public chartObject = new Array<any>();

  ngOnInit() {
    console.log("profile/Home component2 initialized");
    this.getAttendanceDetails();
  }

  getAttendanceDetails() {
    this.profileService.getAttendanceDetails().subscribe(
      (res) => {
        let totalMembersId = [];
        this.members = res.json();
        this.members.filter((element: any) => {

          if(totalMembersId.indexOf(element.userId) == -1)
          totalMembersId.push(element.userId);
        });
        this.totalMemberWithLeaves=totalMembersId.length;
        console.log("Total Member with leaves: ", this.totalMemberWithLeaves);


        totalMembersId.forEach((element: any) => {

          let chartDataforEachMembers = new Array<any>();
          let Task = ['Task', 'Hours per Day'];
          let present =['Present', 12];
          let earnedLeaves = ['Earned Leaves', 23];
          let Unplanned = ['Unplanned Leaves', 2];
          chartDataforEachMembers.push(Task,present,earnedLeaves,Unplanned);

          let memberObject={data   :[Task,present,earnedLeaves,Unplanned],
                            options:{
                                      title: element,
                                      width: element+500,
                                      height: element+500
                                    }};
          this.chartObject.push(memberObject);

        });
         console.log("chartObject : ",this.chartObject);
      }, (err) => {
        bootbox.alert("Error");
      }
    )
  }
}

Within my chartObject, there are four objects included. I have attached snapshots for better clarification. Any suggestions or feedback on where I might be going wrong would be greatly appreciated.

Snapshots:

https://i.sstatic.net/TXUr8.png

https://i.sstatic.net/GNPw9.png

Answer №1

One thing to consider is that the chart is being rendered into the same div. You may want to try a different approach like the following:

<div *ngFor="let member of chartObject; let index=i"  >
    <div class="col-md-6"
     [chartData]="member.data" [id]=index
     [chartOptions] = "member.options" 
     chartType="PieChart" 
     GoogleChart>
</div>

The use of [id]=index will ensure that each div created has a unique id. Hopefully, this suggestion helps address your issue.

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

Having trouble utilizing the Visual Studio Code debugger in an Express.js project that uses TypeScript

My package.json file is shown below: ` { "name": "crm-backend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev" ...

Utilizing Angular to Handle Multiple Sockets on a Single Client

Is it feasible to achieve this task? If not, kindly guide me in an alternative direction. I am managing a server that has the capability for multiple socket-io connections. The server produces a random number and transmits it to registered sockets. In th ...

Utilize systemJs to import a node module in a TypeScript file

I attempted to import a node module called immutablejs into my TypeScript file: /// <reference path="../node_modules/immutable/dist/immutable.d.ts" /> import { Map } from 'immutable'; var myMap = Map(); Here are the script tags in my inde ...

Angular error: Attempting to create a property on an empty string using Rxjs

Currently, I am working with Angular 11 and using rxjs. I am trying to filter my course collection to show only courses with the category "frontend," but I am encountering some errors. Here is my code: getPosts():Observable<ICourses[]> { return ...

Developing a custom pipe in Angular4

Can anyone explain why the code snippet below has (limit) in parentheses? import { Pipe, PipeTransform } from '@angular/core' @Pipe ({ name: 'summary' }) export class SummaryPipe implements PipeTransofm { transform(value: string, l ...

Tips for specifying a clear type in TypeGraphQL when dealing with key-value pair objects

In my efforts to define explicit types in type-graphql for key-value pairs, I am encountering an issue. I have declared the key-value pair using [key: string]: string, indicating that the keys can be of any string type and the values must be strings. This ...

What steps do I need to take in order for TypeScript source files to appear in the node inspector?

Currently developing a node express app with TypeScript 2.3. Compiling using tsc Interested in debugging TypeScript code using node-inspector (now included in node 6.3+) SourceMaps are enabled in my tsConfig.json file { "compilerOptions": { "targ ...

Zone.js error: Promise rejection caught

When I call a function from an external library on page load in my Angular application, Chrome dev tools console shows the error message: "Unhandled Promise rejection: Cannot read properties of undefined (reading 'page') ' Zone: <root> ...

Is it possible to customize the borders of boxes in Google Charts Treemap?

Although this may seem like a minor issue, I can't find any information in the documentation. I'm currently using Google Charts treemap for monitoring a specific project. The problem I'm facing is that when all the parent level rectangles ar ...

Generating TypeScript Type Definitions for dynamic usage

In my client server application, I use REST calls for communication. To avoid using the wrong types by mistake, I have defined all RestCalls in a common file (excerpt): type def<TConnection extends Connections> = // Authentication ...

What could be causing the error I'm encountering when attempting to declare a local variable?

I am new to TypeScript and am encountering an issue with variable declaration in my component function. I am trying to declare a local variable "contains" like this: setUpgrade($event) { contains : Boolean = this.selectedUpgrades.includes($even ...

Angular - tracking the window scroll event to target a specific scrollbar on a page with multiple scrollbars

I am facing difficulty in accessing a specific scrollbar from a component in my web page. The page contains multiple scrollbars, and I need to target and modify the position of a particular scrollbar (scrollTop). I have tried implementing the following co ...

Encountered an issue with the Dynamic Form: TypeError - The property 'value' is undefined and cannot be read

RESOLVED An incorrect value was causing an issue with the onChange function. public onChange = (e:any, key:any) => { this.setState({ [key]: e.target.value }); }; I'm struggling to resolve an error while inputting data into my form in T ...

Placing an image on the chosen option of a <mat-select> using Angular Material

I have incorporated Angular Material into my Angular 2 project, and I am trying to insert a static image (HTML element) in the selected value of mat-select. Unfortunately, I have been unable to find a solution for this issue. Is there anyone who can ...

encountering a problem integrating react-dropzone into a project using react-16.13.1

I'm having an issue adding the package https://www.npmjs.com/package/react-dropzone to my TypeScript React project using Yarn as the package manager. I ran the command yarn add @types/react-dropzone, but it ended up installing a deprecated package h ...

A guide on distinguishing between two dates in Ionic3 using either date-fns or Moment libraries

How can I calculate the difference between two dates to determine the end of an employee's service? Similar Question: What is the best way to find the day difference between two dates using Ionic 3? I am looking for a solution on how to get the exac ...

Despite EsLint and Prettier's efforts to improve code quality, users are experiencing frequent unnecessary errors and unexpected auto-insertion of parentheses at

When working with redux saga for handling asynchronous calls, I encountered an issue. After making an API call and storing the retrieved data in local storage, eslint/prettier automatically adds parentheses to the assignment operator at the end of the line ...

Obtaining the display name and phone numbers of a contact

Using the Ionic Contacts Native feature, I am able to retrieve a list of contacts from my phone. .ts: import { Contacts } from 'ionic-native'; ///////// export class ContactPage { contactsfound = [] constructor(public navCtrl: NavCont ...

Error: The window object is not defined in NextJS

I've encountered an issue while trying to build the app for production. The error message states: ReferenceError: window is not defined. I'm struggling to find a solution. FullCode: const [windowSize, setWindowSize] = useState<WindowInfo>( ...

What is the best approach to limit the return type of a function in JSX?

Is it possible to create a function where the return type should be a specific JSX type? For instance: const setHosting : <GitlabLogo> | <GithubLogo> = (h: Hosting) => ??? In this case, the return type must either be <GitlabLogo> or ...