Executing the Mat-tab method within an *ngFor loop in Angular 5 results in multiple executions

I'm facing an issue where a function called inside *ngFor is executing multiple times, more than the number of elements in the array tabsName. Here's the code snippet:


    <mat-tab-group>
      <mat-tab  *ngFor="let tab of tabsName">
        <ng-template mat-tab-label>
          {{getTabName(tab)}}
          <span class="badge">{{getTabCount(tab)}}</span>
        </ng-template>
        <div *ngTemplateOutlet="comments"></div>
      </mat-tab>
    </mat-tab-group>  

    <ng-template #comments>
      <div class="col-sm-9 jj-pad-0">Deep</div>
    </ng-template>

After implementing all lifecycle hooks of a component, I noticed that some methods are being called repeatedly.

I'm unsure if this behavior is correct or not.

The properties of tabsName include names and counts, retrieved from a service through a REST call.

tabsName : [{name:'tab1',count:'2'},{name:'tab2',count:'1'}]

Here's the associated TypeScript file:


export class TabsComponent implements OnInit {

  @Input() tabsName: any;
  @Input() template: TemplateRef<any>;
  @Output() tabSelected: EventEmitter<any> = new EventEmitter();

  constructor(private service: SomeService) {

  }

getTabName(tab): string {

    return this.service.configData[tab]['UILabel'];
  }

  getTabCount(tab): number {
    if (this.service.dataMap) {
      return this.service.dataMap.get(this.service.configData[tab]['dataType']).data.length;
    }
  }

  onSelect(event) {
    this.tabSelected.emit(event);
  }

}

Answer №1

Your implementation of *ngFor appears incorrect to me. I recommend using {{ tab.getTabName }} and {{ tab.getTabCount }} instead.

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

How to incorporate a multi-dimensional object using ng-init in AngularJS

Trying to include a multi-dimensional object in ng-init: object({ friends:[ {name:John,phone:555-1276}, {name:Mary,phone:800-BIG-MARY}, {name:Mike,phone:555-4321}, {name:Adam,phone:555-5678}, {name:Julie,phone ...

React-leaflet with TypeScript is failing to display GeoJSON Points on the map

I am attempting to display points on a map using geojson points in my react application with react-leaflet. However, for some unknown reason, the points are not rendering on the map. When I try importing a JSON file, I encounter an error: TS2322: Ty ...

A guide on how to retrieve images from a URL and save them using Blob in Angular 5

In my web application, I have a few links that lead to files with different content types - some are application/pdf and others are image/jpeg. When clicking on these links, the file should download or save based on their respective type. While downloadin ...

Issue encountered with TinyMCE integration in Angular 2

As a newcomer to Angular 2, I recently attempted to integrate the TinyMCE editor into my project. I diligently followed the instructions outlined in this guide to create and implement the TinyMCE component: Despite meticulously following each step, I enc ...

What causes the error message "Expected ':' when utilizing null conditional in TypeScript?"

UPDATE: After receiving CodeCaster's comment, I realized the issue was due to me using TypeScript version 3.5 instead of 3.7+. It was surprising because these checks seemed to be working fine with other Angular elements, such as <div *ngIf="pa ...

Refilling state through an NgRx Effect

I am facing a situation where I have JSON data stored in my effect, which was initially generated using JSON.stringify(state), and now I need to insert that JSON string back into the state in order to update the application. As someone new to Angular and N ...

Unlocking rotation on a single screen in a react native application can be achieved by altering

I attempted to use react-native-orientation within a webview in order to make it the only view that would rotate. import React, {useEffect} from 'react'; import { WebView } from 'react-native-webview'; import Orientation from "react-na ...

Adding fewer components to your current Angular 5 project

I have a JS Fiddle showcasing a CSS chart. How can I integrate LESS into my current Angular 5 project to make use of this chart? Also, where should I place the JavaScript and references to the LESS file from this example within my Angular component? The li ...

What method is most effective for generating an Observable that emits immediately upon instantiation?

I'm pondering the best and most semantically proper way to create an observable that emits immediately upon creation. While I could use of(unknown), of(undefined), of(null), of(true), etc., I'm curious if there is a more "correct" approach or an ...

How can I resolve the issue of a React hook being called within a callback function when working with TypeScript and React?

I am trying to display the names of company and owner when sharing an item, but I am encountering an error that says "React hook cannot be used in callback function. React hooks must be called in a react functional component or a custom react hook function ...

Using a jQuery plugin within an Angular 2 component: A step-by-step guide

Looking to implement an image slider plugin called Vegas only on the home page within my Angular 2 application. The Vegas jQuery plugin has been added via npm and is located under the /node_module directory. The following code snippet shows my home page c ...

A technique for deactivating reactive forms control within a nested formArray

Is there a way to selectively disable individual controls within the 'fields' group which is nested under this.form.get('groups').controls? I know how to disable an entire group by using this.form.get('groups').controls.disabl ...

Transform a Class component into a functional component using hooks

Looking to transition this to a functional component using hooks, but running into some issues. How can I achieve this? (I am new to hooks). I've attempted to follow the documentation, but it's not clicking for me. The functionality should remain ...

Ensure that the date is valid using Joi without transforming it into UTC format

Is there a method to validate a date using @joi/date without converting it to UTC? I need to ensure the date is valid before storing it in the database. Here's what I've attempted: const Joi = require('joi').extend(require('@joi/ ...

Error encountered in TypeScript exclusively when implementing GetStaticProps function within a Next.js component and using the getStaticProps method

I'm encountering a challenge with TypeScript as I try to implement the type GetStaticProps in my code. Surprisingly, everything runs smoothly without any issues when this type is not used. The error message reported by TypeScript has left me puzzled. ...

Waiting for an HTTP observable to emit in Angular

When I make a request to the backend via HTTP, it often takes some time before receiving a response. The result is returned as an observable. Is there a way to have the .subscribe() method hold until a value is emitted? ...

typescript mistakenly overlooked a potential undefined value in indexed records

In my code, I have defined an index-based type X. However, when using a non-existing key, TypeScript does not accurately infer the result type as ValueType | undefined. Is there a solution to correct this issue? type ValueType = { foobar:string; } t ...

Typescript's Nested Type Assignments

Simply put, I'm making an API call and receiving the following data: { getUserInfo: { country: 'DE', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c59445d514c5059125f5351">[e ...

Differentiating AWS API errors in TypeScript: A guide

How can I write different handlers in TypeScript for ThrottlingException and ExecutionLimitExceeded when starting a StepFunction execution? new StepFunction.startExecution({}, (err, data) => { if (err) { // Need to identify ThrottlingExcepti ...

SWC's packaging tool converts code to ES6 import syntax rather than using require statements

Is there a way to bundle TypeScript files using SWC and transform ES6 imports into commonjs require()? I'm not sure if my lack of understanding is causing the issue or if I am missing a specific option. In my entry TS file, I import an external libra ...