Assigning styles and values to an object using ngStyle

Within my component, I am encountering an issue where I am trying to edit some styles on a different component. I am passing an object to the component through property binding. The problem arises when updating the BorderRadius - it works when declaring a new object in .style, but not when assigning a value to an existing key.

Is this an error in my code, or is it a bug? Why is this happening?

Binding elProp to elementComponent

<app-element text="Test4" (click)="selectItem(item.id)" [elProp]="getProperty(item.id)"></app-element>

ElementComponent

<div
  fxLayout="row"
  [fxLayoutAlign]="property.text?.style?.position"
  style="background-color: rgb(51, 134, 153);"
  [ngStyle]="elProp.style"
  [ngClass]="{ 'selectedItem': elProp.selected}"
>
  {{ elProp?.text?.value }}
</div>

Input...

<input type="text" class="form-control" id="borderradius" (ngModelChange)="updateStyle()" >
updateStyle(){
    this.itemProperty.map(el=>{
      if(el.itemId == this.selectedId)
        //  el.style.borderRadius = "20px"; <<< doesn't WORK
        //  el.style['borderRadius‘] = "20px"; <<< doesn't WORK
        // Object.assign(el.style,{borderRadius: "20px"}); <<< doesn't WORK
        el.style = {borderRadius: "20px"}; <<< WORKS
    })
  }

Model

export interface ItemProperty {
    itemId: string;
    selected : boolean;
    color: string;
    border: string;
    text: {
      value: string,
      style: {
        position: string
      },
    };
    style:{
      borderRadius: string;
     // border: string,
    };
  }

Answer №1

Angular does not consider this behavior a bug, but rather an expected outcome.

It's important to note that NgStyle is actually an @input property. When you pass an object like elProp.style to this @input, the issue arises when you attempt to change a property of the object. In this case, the @input does not recognize it as a new value because the object reference remains the same.

A helpful explanation can be found at :

The OnChanges lifecycle hook only triggers when the @Input property value changes. With objects, the value being checked is the object reference. If the object reference stays the same, OnChanges will not be triggered.

Therefore,

el.style.borderRadius = "20px"; // Same object reference -> OnChanges is not triggered
el.style = {borderRadius: "20px"}; // New Object -> new reference -> OnChanges triggered

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

Can callback argument types be contingent on certain conditions? For example, could argument 0 be null if argument 1 is a string?

I am attempting to implement conditional type logic for the parameter types of a callback function. In this scenario, the first argument represents the value while the second argument could be an error message. type CallbackWithoutError = (value: string, ...

Using Angular: A guide to setting individual values for select dropdowns with form controls

I am working on a project that involves organizing food items into categories. Each item has a corresponding table entry, with a field indicating which category it belongs to. The category is represented by a Guid but displayed in a user-friendly format. C ...

Exploring the process of manually establishing a route change stream in Angular versus utilizing the features of the @angular/router module

Why would a developer choose to manually create a stream of route changes instead of utilizing Angular's ActivatedRoute as recommended in the Angular guide? export class HeroListComponent implements OnInit { heroes$: Observable<Hero[]>; pr ...

Exploring the utilization of type (specifically typescript type) within the @ApiProperty type in Swagger

Currently, I am grappling with a dilemma. In my API documentation, I need to include a 'type' in an @ApiProperty for Swagger. Unfortunately, Swagger seems to be rejecting it and no matter how many websites I scour for solutions, I come up empty-h ...

In the datepicker, only the month and year are required for Angular 2

Can someone assist me in formatting the date as yyyy-mm using BsDatepickerModule of ngx-bootstrap? Currently, I am getting the date in this format: 2018-03-04 with the following code: ...... self.dateSales = dateofSales.toISOString().split('T' ...

Declaration of Typescript index.d.ts for a heavily nested function within an npm module

Regrettably, it appears that @types/rickshaw is lacking content, prompting me to create my own declaration file. The current one I have looks like this: declare module 'rickshaw' { export class Graph { constructor(obj: any); ...

Is it possible to construct an Angular project without altering the file size limit?

The budget of 40.00 kB fell short by 60.66 kB for a total of 80.66 kB. I've been grappling with the issue of exceeding the max file limit for anyComponentStyle. While working with Material UI and utilizing indigo-pink.css in my component scss, I&apo ...

Changing environment.ts with custom schematics in angular-cli

Currently, I am working on creating customized schematics for our Angular Cli project. One of the tasks involves adding properties/variables to both the environment.prod.ts and environment.dev.ts files. I am curious if anyone has experience with this and h ...

Which location can I find my 'bundles' folder in Angular 2, NPM, and Visual Studio 2015?

Each guide mentions /node_modules/angular2/bundles/... I'm puzzled why I can't find the 'bundles' directories for Angular or any library obtained from NPM within Visual Studio 2015? Downloaded from NPM "dependencies": { "angular ...

Error in NodeJS when trying to run ESM: "ReferenceError: exports is not defined

Having a tough time with this task. I'm attempting to execute ESM scripts on Node 14 (AWS Lambda) I am working on running this piece of code to convert 3D objects to THREE JSON. This involves using the command node -r esm fbx2three.js model.fbx. I ...

Is it feasible to tailor the structure of the new application directory?

Recently, I was assigned a task to explore customizing the folder structure for new apps, specifically Nest apps. After some research, I discovered that it is possible to create a "lib" folder within the "tools" directory and leverage patterns to automatic ...

Is it planned to include StencilJS as a development choice in Ionic?

I'm curious about the potential adoption of Stencil JS for developing mobile apps within the Ionic framework. When I mention "an option for developing," I'm referring to frameworks like NativeScript where developers can choose between Angular + ...

Set values to the inner property of the object

In my configuration file, I have set up nested properties as shown below export class Config { public msalConfig: { auth: { authority: string; clientId: string; validateAuthority: boolean; redirectUri: ...

custom field component for react-hook-form

I have been working on creating a form field component that can be utilized at both the root form level and as a nested field. export type FirstNameField = { firstName: string; }; type GenericFormType<T, NS extends string | never = never> = NS ext ...

CreateAsyncModule using an import statement from a variable

When trying to load a component using defineAsyncComponent, the component name that should be rendered is retrieved from the backend. I have created a function specifically for loading the component. const defineAsyncComponentByName = (componentName: strin ...

Typescript - Error in Parsing: Expecting an expression

I am currently working with Vue and TypeScript and have encountered a problem. How can I resolve it? Here is the code snippet in question: private setTitle(systemConfig: any) { const systemConfigParse; let obj; systemConfigParse = JSON.parse(sy ...

How to Hide Warning Messages in Angular NPM Package for Production Environment

Seeking advice on a coding issue I'm facing. Currently, I am in the process of creating an npm package for angular / angular material, which involves implementing some checks. If a developer fails to pass a specific argument to my function, the funct ...

What is the best way to handle the completion of an HTTP request in Angular 8?

This is the service provided. existWayBillByRsBillNumber(billNumber: string){ return this.http.get<boolean>(this.baseUrl + 'Common/ExistWayBillByRsBillNumber/'+billNumber); } This is how the service call is made. this.commonServic ...

Differentiating navigation design in various views of Angular 4

I am utilizing a shared navigation with content that changes via RouterModule. Is there a way to modify the design of the navigation in different views? <app-navigation></app-navigation> <router-outlet></router-outlet> For example ...

Struggling to properly test the functionality of my NgForm call in Angular2+

I've been trying to test the login functionality by inputting username and password in an NgForm, but I keep encountering unsuccessful attempts. Is there a vital step that I may be overlooking? Currently, I'm facing this error message: Chrome 6 ...