AngularJS – ng-style Directive

AngularJSWeb DevelopmentFront End Technology

The ng-style Directive in AngularJS helps you to set the CSS style of an HTML element conditionally. If the condition evaluates to True, the style will be applied. The expression inside the ng-style directive must be an object. This is supported by all the HTML elements.

Syntax

<element ng-style="expression">..content..</element>

Example − ngStyle Directive

Create a file "ngStyle.html" in your Angular project directory and copy-paste the following code snippet.

<!DOCTYPE html>
<html>
   <head>
      <title>ngStyle Directive</title>

      <style>
         span {
            color: black;
         }
      </style>

      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">      </script>
   </head>

   <body ng-app style="text-align: center;">
      <h1 style="color: green;">
         Welcome to Tutorials Point
      </h1>
      <h2>
         AngularJS | ngStyle Directive
      </h2>

      <input type="button" value="set color" ng-click="myStyle={color:'red'}" />
      <input type="button" value="set background" ng-click="myStyle={'background color':'yellow'}" />
      <input type="button" value="clear" ng-click="myStyle={}" />
      <br />
      <br />
      <span ng-style="myStyle">Welcome to Tutorials Point</span>
      <pre>myStyle={{myStyle}}</pre>
   </body>
</html>

Output

To run the above code, just go to your file and run it as a normal HTML file. You will see the following output on the browser window.

raja
Published on 08-Oct-2021 12:17:44
Advertisements