Prevent NgClass in Angular 2 from constantly updating

Currently, I have a map feature integrated with a video element. When the video is clicked, the classes of both components switch, resulting in the video becoming fullscreen and the map being displayed as an inset.

While utilizing NgClass to update the classes of the components, I observed some flickering in the class section of the map element while testing my app on Chrome.

Upon investigation, it appears that ngClass constantly updates the class starting from the app's launch, even when no changes are made to the component. I aim to only modify the class upon clicking the inset element.

Is this standard behavior? Are there any measures I can take to resolve this issue?

Here is the HTML code:

<map class="map" (click)="switchInset('map')" [ngClass]="setClass('map')"></map>
<app-video class="video" (click)="switchInset('video')" [ngClass]="setClass('video')"></app-video>

And here is the TypeScript logic:

mapFullscreen: boolean = true;

switchInset(target: string) {
    switch (target) {
        case 'map':
            if (!this.mapFullscreen) {
                this.mapFullscreen = this.mapFullscreen ? false : true;
            }
            break;

        case 'video':
            if (this.mapFullscreen) {
                this.mapFullscreen = this.mapFullscreen ? false : true;
            }
            break;

        default:
            break;
    }
}

setClass(target: string) {
    let classes = {};
    switch (target) {

        case 'map':
            classes = {
                inset: !this.mapFullscreen,
                fullscreen: this.mapFullscreen
            }
            break;

        case 'video':
            classes = {
                inset: this.mapFullscreen,
                fullscreen: !this.mapFullscreen
            }
            break;

        default:
            break;
    }

    return classes;
}

Answer №1

Indeed, when you have a method (function) in your binding, it will be executed each time change detection is triggered, which can occur frequently as you've noticed.

This is precisely why the practice of binding directly to methods is not recommended.

Instead, it's better to assign the result of the method call to a property and then bind to that property instead.

[ngClass]="mapClass"
ngOnChanges() { // Here is an example demonstrating the use of `ngOnChanges`
  this.mapClass = setClass('map');
}

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

I am looking to replicate a DOM element using Angular 4

I am interested in creating a clone of a DOM element. For example, if I have the following structure: <div> <p></p> <p></p> <p></p> <p></p> <button (click)="copy()"></button> & ...

Bidirectional enumeration in TypeScript

I am working with an enum defined as: enum MyEnum { key1 = 'val1' key2 = 'val2' } However, I am unsure how to create a SomeType implementation that fulfills the following requirements: Function: const myFunction = (param: SomeT ...

Passing Toastr to child component in Angular 4 was successfully implemented

I am working with a parent component that utilizes ng2-toastr version 4.1.2. Parent Component: import { Component, ViewContainerRef } from '@angular/core'; import { AfterViewInit, ViewChild } from '@angular/core'; import { Rou ...

What is the best way to effectively personalize my Bootstrap variables using SASS?

After creating a web page and adding Bootstrap styling, I attempted to customize the Bootstrap variables, but encountered an issue where it did not seem to work despite no errors being displayed. I followed a tutorial on YouTube meticulously, but to no av ...

Issue with React Moment library when using DatePicker and moment (Possibly related to dependencies)

My issue lies with setting default values for the DatePicker. I've attempted it in the following ways: To start, I import Moment like so: import moment from 'moment'; //Then try: <DatePicker defaultValue={moment('2015/01/01&a ...

Leveraging FormControlName in Typescript to Interact with HTML Components in Angular 4

How can I use FormControlName to access HTML elements in typescript? Typically, I am able to access HTML elements using their ID. For example: var element = document.getElementById("txtID") But is it possible to access the element without using its ID a ...

How can TypeScript rules be incorporated into a Next.js project without compromising next/core-web-vitals?

In my current NextJS project which is in typescript, I have the following configuration in my .eslintrc.json: { "extends": "next/core-web-vitals" } Now, I want to include additional typescript rules, such as enforcing the rule of n ...

By default, the ng build command constructs the development environment rather than the production environment

Whenever I execute the "ng build" command in the terminal, it constructs the development environment instead of the production environment. If I use the "ng build --prod" command, everything works as expected. However, by default, it continues to build th ...

Since updating from Angular 16 to 17, I am experiencing a TypeScript compilation issue specifically related to 'openui5'

Everything was running smoothly in Angular16. I had "@types/openui5" : "1.40.4" listed in my dev-dependencies. Here is how it's configured in the tsconfig.json: { "compilerOptions": { "downlevelIteration": ...

The value of "metadata" is not a valid export entry for Next.js

After I installed Next.js 14 with TypeScript, I encountered an error related to my metadata type definition. import type { Metadata } from "next"; export const metadata: Metadata = { title: "next app", description: "next app 1 ...

The reloading feature in Angular components is not functioning as intended

I am looking for a way to refresh the component without having to refresh the entire page. Below is the code snippet that I have been using: import { Component, VERSION, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from &apos ...

Building a hierarchical tree structure using arrays and objects with Lodash Js

I am attempting to create a tree-like structure using Lodash for arrays and objects. I have two arrays, one for categories and the other for products, both with a common key. The goal is to organize them into a tree structure using string indexing. let ca ...

What exactly is the function of the NextPage feature in Next.js?

Recently, I began incorporating TypeScript into my Next project. Could someone clarify the purpose of the following code snippets for me? import { NextPage } from 'next'; export const Page: NextPage = () => {} After reviewing the documentation ...

What could be causing eslint to generate errors for .d.ts files within my node application?

I recently set up eslint for my TypeScript node project and included a file called app.d.ts in the repository. However, when I run the linting process, I encounter the following error: error Parsing error: "parserOptions.project" has been set f ...

ngx-bootstrap: Customizable horizontal sorting with templates

I'm encountering a problem with the ngx-bootstrap sortable component. My goal is to utilize the sortable component in a horizontal layout instead of the vertical one shown in the documentation examples. ngx-bootstrap sortable If anyone has a solutio ...

How can you make sure that VS Code always utilizes relative paths for auto imports in TypeScript?

VS Code has been automatically importing everything using Node-like non-relative paths relative to baseUrl, which is not the desired behavior. Is there a way to instruct VS Code to import everything with relative paths, excluding Node modules? Removing t ...

The Jest test is experiencing a failure as a result of an imported service from a .ts file

In my Jest test file with a .spec.js extension, I am importing an index.js file that I need to test. Here is the code snippet from the .spec.js file: var HttpService = require('./index.js').HttpService; The problem arises because the index.js f ...

Determine the duration of an HTTP request in Angular applications

Is there a way to accurately measure the execution time of an HTTP request in Angular (specifically version 5)? The following code snippet is giving incorrect values because of its asynchronous nature: myFunction(someVariable):void { let startTim ...

Enhancing the visual aesthetics of KendoUI Charts through custom formatting

I've been working on a custom visual to showcase some formatted values. After formatting the text and creating a visual, I expected to see the new values displayed. However, the values remain unchanged. Below is my code snippet: valueAxis: { labels ...

What is the best way to convert this into a distinct function using typescript?

Is there a way to create a single method in Protractor or Webdriver API that can get the browser width and height? const getWindowWidth = async () => { const size = await browser.manage().window().getSize(); return size.width; }; I need this metho ...