Angular ngStyle

testYourselfAngular Angular161 1 0

ngStyle is an Angular directive that adds or removes CSS styles based on a condition or expression. It is an attribute directive, which means it changes the appearance of the element on which it is used. It does not manipulate the DOM like the structural directive.
 

NgStyle accepts an object literal where the keys are the style property names and the values are the corresponding values you want to apply.

Here is a simple example of using ngStyle to apply a specific background. Note that a condition is not used yet, so the CSS style is always added.

<div [ngStyle]="{ background: 'blue' }"></div>

If the style property contains hyphens, they must be enclosed in quotation marks or replaced with camelCase notation.

<div [ngStyle]="{ 'border-color': 'blue' }"></div>
<div [ngStyle]="{ borderColor: 'blue' }"></div>

Here is more useful example with a condition:

<div [ngStyle]="{ borderColor: value < 0 ? 'red' : 'green' }"></div>

The same result can be achieved using a style attribute.

<div [style.borderColor]="value < 0 ? 'red' : 'green'"></div>

The difference between a style attribute and ngStyle is that ngStyle allows you to add multiple CSS styles.

<div [ngStyle]="{borderColor: < 0 ? 'red' : 'green', background: 'lightyellow'}"></div>

Additionally, the logic for adding styles can be moved directly to the component code.

html:

<div [ngStyle]="getStyles()"></div>

ts:

@Component({
  selector: 'home',
  templateUrl: './home.html'
})
export class HomeComponent {
  getStyles() {
    return { 
      borderColor: < 0 ? 'red' : 'green',
      background: 'lightyellow'
    };
  }
}

An interesting tip is that you can add the unit directly to the property name:

<div [ngStyle]="{'font-size.px': 20}"></div>

Keep in mind that ngStyle doesn't overwrite a style attribute but extends it. If an HTML element has both style and ngStyle, they are merged.

for the code below:

<p style="color: blue;" ngStyle="{border: '1px solid red', background: 'yellow'}">lorem ipsum</p>

The Angular renders the given result:

<p style="color: blue; border: 1px solid red; background: yellow;">lorem ipsum</p>