EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials AngularJS Tutorial AngularJS ng-style
Secondary Sidebar
AngularJS Tutorial
  • AngularJS Basic and Advance
    • What is AngularJS
    • Career In AngularJS
    • Uses of Angular JS
    • AngularJS Architecture
    • Angular JS Application
    • AngularJS Application
    • AngularJS Filter Array
    • AngularJS ng-style
    • AngularJs ng init
    • AngularJs ng-repeat
    • AngularJs ng-change
    • AngularJs ng-options
    • AngularJs expressions
    • AngularJs onclick
    • AngularJS ng-show
    • AngularJs ng-include
    • Scope in AngularJS
    • AngularJS ng-if
    • AngularJS Number Filter
    • AngularJS Date Filter
    • AngularJS ng-class
    • AngularJS ng-model
    • AngularJS ng-disabled
    • AngularJS Custom Filter
    • AngularJS Validation
    • AngularJS Filters
    • Controllers in AngularJS
    • AngularJS Animations
    • AngularJS Services
    • AngularJS Events
    • AngularJS Versions
    • AngularJS Directives
    • AngularJS Unit Testing
    • AngularJS with Bootstrap
    • AngularJS UI Bootstrap
    • AngularJS Routing Example
  • Interview Question
    • Angular JS Interview Questions

AngularJS ng-style

AngularJS ng-style

Introduction to AngularJS ng-style

AngularJS ng-style is an In-Built AngularJS directive used in the HTML view to design a web page and use CSS styles that can be handled conditionally. This directive comes into usage whenever the developer needs to handle CSS styling on HTML view dynamically based on some conditions or model value change as well as can be handled in the controller by making a method call from HTML view to the controller where method names are passed as the value of the ng-style directive. This can be used with any HTML tag such as div, span, paragraph, select, input, etc.

Syntax of AngularJS ng-style

There are various ways to write ng-style directives within HTML Tags.

1. Using ng-style to make a method call in a controller and handle the styling in the controller.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

<div ng-style=”methodToBeCalled”></div>

2. Another way for writing using ng-style is to add conditional expressions such as the binary or ternary operator.

<div ng-style=”conditionaExpression”></div>

3. Using ng-style with model value in HTML tag.

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,502 ratings)

<input ng-model=”modelValue” type=”text” place holder =”Enter width”>
<span ng-style=”{width: modelValue }”></span>

The ng-style directive can be used with any HTML element and can be used conditionally.

How ng-style Directive works in AngularJS?

  • In the AngularJS framework, it is important to know that all the In-Built directives that the AngularJS framework has provisioned will always be denoted with the ng prefix. The ng-style directive is very simple and very easy to use directive in HTML view. This directive is used to handle any sort of conditions a developer needs to add while adding style to the HTML page, say the developer needs to keep changing the color of the webpage based on some criteria like scrolling effect, on click of a checkbox, on change of some value in a controller or any other complex logic in the controller all of it can be solved just by using ng-style directive as an attribute in any HTML Element.
  • The ng-style attribute directive accepts any conditional binary or ternary expression as the value. In addition, it accepts any method call which is defined inside the controller, and the controller can handle it as per requirements. the ng-style directive can also be used to handle the View and CSS styling based on the model value, so as and when the model value changes, ng-style will get executed and update the CSS styling as well. the ng-style directive is executed at priority level 0 and has few limitations as well in terms of interpolation. There are few CSS styling names which are not valid keys for objects in ng-style, due to which it is very important to always mention the CSS styling key in single quotes.

Examples of AngularJS ng-style

Given below are the examples of AngularJS ng-style:

Example #1

Code:

Index.html

<!DOCTYPE html>
<html>
<head>
<style>
.defaultColor {
color: black;
font-weigth: bold;
margin: 20px 20px 20px 140px;
}
.any-style-for-dropdown {
margin: 20px;
width: 80%;
height: 35px;
line-height: 35px;
border: 1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="cssStylingApp" ng-controller="cssStylingCtrl">
<div ng-style="{'margin-left': '20px'}">Select Color :</div>
<select class="any-style-for-dropdown"
ng-options="color.key for color in colors" ng-model="selectedColor">
</select>
<div class="defaultColor" ng-if="selectedColor" ng-style="{'color': selectedColor.value}">Selected color
is {{selectedColor.key}}</div>
</body>
</html>

Script.js

var app = angular.module('cssStylingApp', []);
app.controller('cssStylingCtrl', function($scope) {
$scope.colors = [
{'key': 'Black', 'value': 'black'},
{'key': 'Red', 'value': 'red'},
{'key': 'Blue', 'value': 'blue'},
{'key': 'Light blue', 'value': 'cyan'},
{'key': 'Green', 'value': 'green'}];
});

The above example shows how easily ng-style directive can be used in AngularJS HTML view and tweaked around conditions as the developer wants to. A list of colors have been added to the HTML using select Tag, and ng-options attributes are added where colors is a list of Object of Color, each Color object consists of Key and value. Where key is the Name of the Color, which should be displayed on the UI inside the dropdown, and value should be the name of the CSS styling color which can be added to the CSS attribute ‘color’ inside the ng-style directive. The model value of ng-options consists of an entire selected object. This model value has 2-way binding and is being added as value to the ng-style directive. So now, as the model value will change, the ng-style will get triggered and will update the CSS color attribute.

Another example of ng-style, which has been used above, is to directly use ng-style inside div block to add a margin-left attribute. Again, make sure the syntax is the same as shown above, and the CSS attribute must be defined in the quote; otherwise, the compiles will not ready this property at all. Finally, make sure to include the AngularJS dependency in the Script tag so that you will be able to use the ng-repeat directive of AngularJS.

<div ng-style="{'margin-left': '20px'}">

Here simply style has been added to a div block where CSS attribute margin-left is used. Again, make sure it’s in quotes and syntax is the same as above.

<select class="any-style-for-dropdown"
ng-options="color.key for color in colors" ng-model="selectedColor">
</select>

Here we are adding a list of Colors which is being picked from the controller. Each color object consists of a key and value initially defined in the controller. The model value selectedColor will hold the entire object corresponding to the selected value in the dropdown and can be used to access color key and color value.

ng-style="{'color': selectedColor.value}">

Here ng-style directive has been initialized, and CSS attribute color has been added, where the value of this CSS attribute is dynamic and will reflect based on selectedColor model value from the dropdown.

Output:

Output 1:

Selected color is Black

Output 2:

Selected color is Red

Output 3:

Selected color is Light blue

Example #2

Code:

Index.html

<!DOCTYPE html>
<html>
<head>
<style>
.defaultColor {
margin-top: 80px;
}
.any-style-for-dropdown {
margin: 20px;
width: 80%;
height: 35px;
line-height: 35px;
border: 1px solid black;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="cssStylingApp" ng-controller="cssStylingCtrl">
<div>Select Color :</div>
<select class="any-style-for-dropdown"
ng-options="color.key for color in colors" ng-model="selectedColor">
</select>
<div class="defaultColor" ng-if="selectedColor" ng-style="modifyColor()">Selected color
is {{selectedColor.key}}</div>
<div class="defaultColor" ng-style="selectedColor.key == 'Blue' ? blueValue :
otherValue">Ternary Style
</div>
</body>
</html>

Script.js

// Code goes here
var app = angular.module('cssStylingApp', []);
app.controller('cssStylingCtrl', function($scope) {
$scope.colors = [
{'key' : 'Black', 'value' : 'black'},
{'key' : 'Red', 'value' : 'red'},
{'key' : 'Blue', 'value' : 'blue'},
{'key' : 'Light blue', 'value' : 'cyan'},
{'key' : 'Green', 'value' : 'green'}];
$scope.modifyColor = function() {
return {
'color': $scope.selectedColor.value
};
}
$scope.blueValue = {
"color" : "white",
"background-color" : "black",
"font-size" : "60px",
"padding" : "50px"
}
$scope.otherValue = {
"color" : "black",
"background-color" : "cyan",
"font-size" : "60px",
"padding" : "50px"
}
});

Above example, everything is the same as above except that the ng-style is being now handled as a function inside the controller instead of directly handling it on the UI. This can be used when some modifications or calculations need to be done on a controller, and then the value should be added to the CSS styling attribute.

Another Example for ng-style is to use ternary operators. Ng-style works perfectly if used with ternary operators in HTML view. Here we are modifying the background colors based on the condition in the ternary operator.

ng-style="modifyColor()"

Making a function call which is defined in the controller. This method should return the CSS attributes.

ng-style="selectedColor.key == 'Blue' ? blueValue :
otherValue"

Using conditions based on selected Color’s Key, we can decide which CSS property to use, and it will reflect accordingly on the UI.

Output:

Output 1:

AngularJS ng-style 4

Output 2:

AngularJS ng-style 5

Output 3:

AngularJS ng-style 6

Conclusion

ng-style is a directive in AngularJS, which is commonly used In-Built AngularJS directive, which is used to Style the HTML view using CSS properties with conditional abilities. There are various forms of using this directive, and proper syntax is needed, and you are ready to go.

Recommended Articles

This is a guide to AngularJS ng-style. Here we discuss the introduction, how ng-style directive works in AngularJS? and examples, respectively. You may also have a look at the following articles to learn more –

  1. Angular Bootstrap Datepicker
  2. Angular Time Picker
  3. Angular 7 Components
  4. Angular 2 Architecture
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more