Angular NgStyle and Style Binding Example

By Arvind Rai, February 10, 2024
On this page we will provide Angular NgStyle and style binding example. Style binding binds an inline style property with a given value and NgStyle sets more than one inline styles dynamically. Style binding is used in the same way as property binding is used. Style binding can bind only one inline CSS property at one time. When we want to use more than one style property at one time dynamically then the role of NgStyle directive comes into picture. NgStyle and style property binding both can be used with bracket [] and bind- keyword. Here on this page we are providing the example for style binding and NgStyle with style properties such as color, font-size, background-image. Now find the complete example step-by-step.

1. Style Binding

The use of style binding is to set inline styles. The syntax is same as we use in property binding with the difference that style binding starts with style. . Find the syntax for style binding.

[style.style-property] = "style-value"

Here style is a prefix and style-property is a name of a CSS style property. style prefix and style property are concatenated using dot (.) . Style property binding can be achieved with bracket [], bind- keyword and interpolation {{}}. Now find the code to use style binding.
<p [style.color] = "result > 30 ? 'blue' : 'green'"> Hello Color World! </p>
<p bind-style.color = "result > 30 ? 'blue' : 'green'"> Hello Color World! </p>
<p style.color = "{{result > 30 ? 'blue' : 'green'}}"> Hello Color World! </p>  
In our style binding example we are using conditional operator. When the condition result > 30 returns true then color style will be set to blue otherwise green. Let us know about conditional operator.

Conditional (ternary) Operator
Conditional operator that is also called ternary operator, is used as a short cut of if else statement. Find the syntax as below.
condition ? expr1 : expr2
When the condition is true then expr1 will be returned otherwise expr2 will be returned.

2. NgStyle

NgStyle directive is used to set many inline styles dynamically. Setting styles using NgStyle works as key:value pair. key is the style property name and value is the style value. Find the code snippet.
myStyles = {
    'color': this.colorFlag ? 'black' : 'yellow',
    'font-size.em': this.isSmall ? this.small/5 : this.big/5,
    'background-image': !this.isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'
};  
We will observe that more than one style properties are being used as key:value pair separated by comma (,) within {}. This set of style properties has been assigned to a variable myStyles. To use this set we will create a component method as following.
getMyStyles() {
    let myStyles = {
       'color': this.colorFlag ? 'black' : 'yellow',
       'font-size.em': this.isSmall ? this.small/5 : this.big/5,
       'background-image': !this.isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'
    };
    return myStyles;
}  
Here the role of let keyword is to define a local variable. In this way myStyles variable has only method scope. NgStyle can be used with bracket [], bind- keyword. Our method getMyStyles() can be called by ngStyle as follows.
<div [ngStyle]="getMyStyles()">
	NgStyle Example
</div>  
In the output our text within <div> will be applied with all the style properties defined in myStyles set. NgStyle directive should be used over style binding when we want to set many inline styles at one time dynamically.

3. NgStyle with Background Image

To load background image the style property background-image is used. Its value is given in the following syntax.

url('images/red.gif')

In inline style binding we can use it as follows.
<div [style.background-image] = "isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'">
	Style Binding Example
</div>  
And while using with NgStyle the key:value pair is created as following.
'background-image': !this.isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'  
We need to use backslash (\) here otherwise it will throw error.

4. Complete Example

app.component.ts
import {Component} from '@angular/core';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {
    result = 50;
    colorFlag = false;
    isSmall = true;
    isBackgroundRed = false;
    small = 10;
    big = 15;
    num = 10;
    isRed(num) {
	if (num > 10) {
	    return false;
	} else {
	    return true;
	}
    }
    allRequiredStyles(styleSet) {
	let myStyles;
	if(styleSet == 'one') {  	  
	  myStyles = {
		'color':  this.colorFlag ? 'black' : 'yellow',
		'font-size.em': this.isSmall ? this.small/5 : this.big/5,
		'background-image': !this.isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'
	  };
	} else if(styleSet == 'two') {
	  myStyles = {
		'color':  !this.colorFlag ? 'black' : 'yellow',
		'font-size.em': !this.isSmall ? this.small/5 : this.big/5,
		'background-image': this.isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'
	  };
	} else {
	  myStyles = {
		'background-color':  this.colorFlag ? 'cyan' : 'grey',
		'font-size.%': !this.isSmall ? this.small * 10: this.big * 10
	  };
	}
	return myStyles;
    }	
}  
app.component.html
<p [style.color] = "result > 30 ? 'blue' : 'green'"> Hello Color World! </p>
<p bind-style.color = "result > 30 ? 'blue' : 'green'"> Hello Color World! </p>
<p style.color = "{{result > 30 ? 'blue' : 'green'}}"> Hello Color World! </p>

<button 
     [style.background-color] = "colorFlag ? 'cyan' : 'grey'"
     [style.color] = "isRed(8) ? 'red' : 'black'" > Button </button>

<div [style.font-size.em] = "isSmall ? small/8 : big/8" > Font Size Test with em</div>
<div [style.font-size.px] = "!isSmall ? small : big" > Font Size Test with px</div>
<div [style.font-size.pt] = "isSmall ? small : big" > Font Size Test with pt</div>
<div [style.font-size.%] = "!isSmall ? small * 10: big * 10" > Font Size Test with %</div>
	 
<div [style.background-image] = "isBackgroundRed ? 'url(\'/assets/images/red.gif\')' : 'url(\'/assets/images/green.gif\')'">
	Style Binding Example
</div>

<br/><br/>
<div [ngStyle]="allRequiredStyles('one')">
	NgStyle Example
</div>
<br/><br/>
<div bind-ngStyle="allRequiredStyles('two')">
	NgStyle Example
</div> 
app.module.ts
import {NgModule}       from '@angular/core';
import {BrowserModule}  from '@angular/platform-browser';
import {AppComponent}   from './app.component';
@NgModule({
  imports:      [BrowserModule],
  declarations: [AppComponent],
  bootstrap:    [AppComponent]
})
export class AppModule { } 
Find the print-screen of the output.
Angular NgStyle and Style Binding Example

Reference

Angular NgStyle

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us