Home  >  Angular

Angular 2 NgStyle and Style Binding Example

By Arvind Rai, November 26, 2016
On this page we will provide angular 2 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.

Software Used

Find the software used in our demo.
1. Angular 2.3.0
2. TypeScript 2.0.10
3. Node.js 4.6.0
4. NPM 3.10.8
5. Firefox 50.1.0

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.

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(\'images/red.gif\')' : 'url(\'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(\'images/red.gif\')' : 'url(\'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.

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(\'images/red.gif\')' : 'url(\'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(\'images/red.gif\')' : 'url(\'images/green.gif\')'  
We need to use backslash (\) here otherwise it will throw error.

Complete Example using TypeScript


app.component.ts
import {Component} from '@angular/core';
@Component({
    selector: 'my-app',
    templateUrl: 'app/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(\'images/red.gif\')' : 'url(\'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(\'images/red.gif\')' : 'url(\'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(\'images/red.gif\')' : 'url(\'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> 
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 { } 
main.ts
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {AppModule} from './module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);  

Run Application

Find the steps to run the example.
1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.
2. Download the source code using download link given below in the example.
3. Go to the root folder of the project using command prompt and run npm install command.
4. Now run npm start command.
5. Now run index.html file. Find the print screen of the output.
Angular 2 NgStyle and Style Binding Example

References

Angular 2 NgStyle
Angular 2 style bindings

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us