Hit enter after type your search item

Apply CSS by using ng-style in AngularJS: 3 demos

The ng-style directive

The angular ng-style directive can be used for applying the CSS to the specified elements of HTML.

For example, upon clicking a button, you may change the background color, font size etc of a paragraph as using the ng-style attribute.

This is how you may use the ng-style directive.

As HTML element attribute:


 

Where, you may use a paragraph, span or other elements in place of a div.

You may also use ng-style as CSS class:

<div class=”ng-style: expression;”> … </div>

You may apply CSS by using ng-style conditionally. Have a look at the live demos below with complete code for learning more about this directive.

A demo of changing color of text by using ng-style

In this simple example, as you click the button “Apply Color by ng-style”, the color of the text will change. In the input type button tag, the ng-click attribute is used while the ng-style is used in the span tag that contains the text.

ng-style

See online demo and code

The code:


 

Get the complete code from the demo page.

A demo of applying multiple properties

In this demo, multiple CSS properties are applied by using ng-style directive. Note that, multiple CSS properties are separated by commas. The background-color property is enclosed in single quotes, unlike the color I used in above example.

Again, press the button to apply color, background color, font size, border radius properties to a paragraph tag.

ng-style CSS

See online demo and code

The code:


 

A demo of applying CSS by using an object

In this demo, the CSS properties are applied by using an object. A paragraph is used where the ng-style attribute is used and an object is given as expression. In the controller, different CSS properties like background, border, border-radius etc are set for the paragraph. Click on the button, and it will display the paragraph with applied CSS properties:

ng-style object

See online demo and code

The code:


 

The example also uses a little CSS in the <style> section. You may see and get the complete code from the demo page.

This div height required for enabling the sticky sidebar