Unexpected ngStyle behavior: failing to update when property changes occur

I'm feeling a little puzzled about why the ngStyle directive is not behaving as anticipated. I came across this issue while following a tutorial by Brad Traversy on Udemy, where we were instructed to utilize ngStyle in the following manner:

<h3 [ngStyle]="currentStyles" >{{user.firstName}} {{user.lastName}}</h3>

This code snippet relies on the currentStyles property defined in the component class, like so:

currentStyles = {'padding-top': this.showExtended ? '15px': '0'}

The showExtended property is a boolean that is toggled using a method:

toggleExtended() {
      this.showExtended = !this.showExtended;
}

Expected behavior: the padding-top of the h3 element should transition from 0 to 15px when showExtended is switched from false to true. The showExtended property is indeed changing, and other parts of the component relying on it are working correctly. However, it seems that the ngStyle directive only evaluates once during the initial render and does not update when the component property changes.

To resolve this issue, I discovered a workaround by creating a method that returned a locally scoped variable:

getCurrentStyles() {
      let styles = {
          'padding-top': this.showExtended ? '0' : '40px'
      }
      return styles;
  }

and then updating the element to:

<h3 [ngStyle]="getCurrentStyles()">{{user.firstName}} {{user.lastName}}</h3>

This workaround indeed produced the expected results. In summary, the ternary condition within the currentStyles object only gets evaluated during the component's initial mount, and the value does not update when the property changes.

What could I be overlooking in this scenario?

Answer №1

A small tweak to achieve your desired outcome.

toggleExtended() {
      this.showExtended = !this.showExtended;
      this.currentStyles = { 'padding-top': this.showExtended ? '20px': '0' };
}

Angular checks for changes in the currentStyles object in order to trigger a redraw.

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

Navigating through an array in Angular 5: a guide

This question may seem simple, but I'm having trouble figuring it out. Here is the code snippet I am working with: getInstabul(): void { this.homeService.getWeather() .subscribe((weather) => { this.instanbulWeathers = weather ...

Using the ngClass directive with a conditional statement: Select 'class1' if true, otherwise select 'class2'

i am currently experimenting with this piece of code <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <button [ngClass]="{'btn': showDirectiveContent === false ? 'btn btn-danger ...

Jest | Testing Tool for Functions with Multiple Parameters

I have developed a new tool that requires 3 parameters: value (string), service (any - an actual GET service), and name (string). Below is the code for the tool: import { serverErrorResponseUtil } from 'util/serverErrorResponseUtil'; import { H ...

The best approach for setting a select value and managing state in React using TypeScript

Currently, I am in the process of familiarizing myself with TypeScript within my React projects. I have defined a type for the expected data structure (consisting of name and url). type PokedexType = { name: string; url: string; } The API respon ...

Unable to apply SASS styling within an Angular 2 component

As per the information shared in this blog post, I'm attempting to structure my component in the following way. @Component({ selector: "navbar", template: require("./navbar.html"), styleUrls: ["./navbar.sass"] }) Encountering error messages in ...

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

What is the best way to simulate mailgun.messages().send() with Jest?

Currently, I am utilizing the mailgun-js Api for sending emails. Instead of a unit test, I've created an integration test. I am now facing the challenge of writing a unit test case for the sendEmail method within the Mailgun class. I am unsure of how ...

Tips for incorporating a mesh into Forge Viewer v6 with Typescript

Is there a way to add meshes to Forge Viewer v6 using Type script? I've tried various methods that worked with v4, but I'm encountering issues now. private wallGeometry: THREE.BoxBufferGeometry; drawWalls() { ...

Tips for transferring a value from a component class to a function that is external to the class in angular

Is there a way to pass a variable value from a component class to a function outside the class? I've been struggling to make it work. Whenever I click the button, I receive an error message saying "cannot read property divide of undefined". Here' ...

"Angular SwtAlert2: The Ultimate Multi-Selection Tool

I am trying to integrate the ng-select directive into SweetAlert2, but the code snippet below is not working as expected: const { value: formValues } = await swal.fire({ title: 'Multiple inputs', html: '<ng-select id=" ...

What is the best way to refresh information following its removal?

In my app, I have implemented a feature where posts are displayed as HTML cards using a component called PostList. Each card has a delete button to remove it from the list. The issue I am facing is that when I delete a card, it remains visible in the post ...

Angular Kendo UI - How to Rotate X-Axis Labels in a Bar Chart

On smaller screens, I am trying to rotate x-axis labels to prevent overlapping. EXAMPLE <kendo-chart *ngIf="!yearLoader" (seriesClick)="barClick($event)"> <kendo-chart-tooltip format="{0} events"></kendo-chart-tooltip> < ...

Unable to invoke an external function from bolt Response Handler Callback

I am facing an issue where I am unable to call my Update method from the bolt responseHandler. Can someone please help me with this problem? Using Angular 9: Error: core.js:1673 ERROR TypeError: this.updatePaymentInfo is not a function at Object.resp ...

"Enhance your PrimeVue Tree component with interactive action buttons placed on every TreeNode

Details: Using Vue 3.3.6 in composition API script setup style Utilizing PrimeVue 3.37.0 and PrimeFlex 3.3.1 Implemented with Typescript Objective: To create a tree structure with checkboxes that are selectable, along with action buttons on each TreeNod ...

What are the properties needed for a context provider around the component <App/>?

Let's take a look at how I've set up a context provider to wrap my <App/> component: // index.ts ReactDOM.render( <ApolloProvider client={client}> <React.StrictMode> <AuthProvider> <App /> & ...

Angular 2 - Bootstrap - Toggle Hide/Show

Is there a way to create a unique ID for each collapse item? The issue I'm facing is that when I click anywhere in the list, the first item always collapses. I've tried giving the div the data.id, but it doesn't seem to work. <div class ...

The module "react-leaflet" is showing a type error because it does not have a exported member named "useEventHandlers"

My Next.js application is built with TypeScript and React-Leaflet. Everything runs smoothly when I start my development server using npm run dev, no errors whatsoever. However, the problem arises when I attempt to build the project using npm run build. An ...

In the search for "action.payload" using Redux Toolkit

const userSlice = createSlice({ name: 'user', initialState, reducers: { // Setting the user setUser: (state, action: PayloadAction<string | null>) => { state.user.email = action.payload; }, setLoading: (state, ...

Tips for connecting to a docker container containing an Angular application while the Angular app is also running in its own container

I have encountered an issue with my application that consists of a frontend and a backend running together in a Docker compose container. The backend has been functioning well without any problems during development, but the frontend, which is an Angular a ...

Error TS2307: Module 'calculator' could not be located

Running a Sharepoint Framework project in Visual Studio Code: This is the project structure: https://i.stack.imgur.com/GAlsX.png The files are organized as follows: ComplexCalculator.ts export class ComplexCalculator { public sqr(v1: number): number ...