Changing HTML styles in AngularJS Dynamically

Hello Readers,

I would like to explain how to add styles to HTML elements dynamically in AngularJS.

In AngularJS, we can use the attribute ng-style to apply styles to HTML elements dynamically.

Consider the following example,

<html>
<script src="angular.js"></script>
<body>
<div ng-app="" ng-init="dyncolor='red';">
  <p ng-style="{color:dyncolor}"> We are assigning color to this paragraph dynamically. </p>
</div>
</body>
</html>

In this example we are initiating dyncolor to be red using ng-init. We are then applying this color dynamically to the paragraphs.

Output :

We are assigning color to this paragraph dynamically.

But this example is not dynamic. Color red is static in the given example. We are going to make it real dynamic.

Consider the following example.

<html>
<script src="angular.js"></script>
<body>
<div ng-app="" ng-init="dyncolor='#400080'">
	<div style="width:50%;margin:auto;padding:10px;">
		<input type="color" ng-model="dyncolor"> &nbsp; Color Selected : <span>{{ dyncolor }}</span>
		<div ng-style="{'border-color':dyncolor}" style="border:2px solid;padding:10px;margin:10px;">
			<h3 ng-style="{color:dyncolor}">Why learn HTML?</h3>
			<p>Every webpage you look at is written in a language called HTML. </p>

			<h3 ng-style="{color:dyncolor}">Advantages of HTML</h3>
			<p>In the editor to the right, there's a tab called test.html. </p>

			<h3 ng-style="{color:dyncolor}">How to write HTML Code</h3>
			<p>When we press Save & Submit Code, the results tab will act like an Internet browser.</p>
		</div>
	</div>
</body>
</html>

In this example we are using color picker to dynamically pick color and we apply it to our HTML elements.

By default we are initiating dyncolor to be #400080 and it gets updated when user picks a color from color picker.

demo-button

Output :
angular_op

Thanks for Reading.

Feedback are welcome. Please feel free to ask questions.

Don’t forget to subscribe to Geeks.Gallery, to get free emails to your inbox.

Subscribe to Geeks.Gallery

Nagarajan
Follow me

Nagarajan

Web Developer at Energy Alternatives India
I'm interested in developing Web applications andkeen on learning new technologies.

View Nagarajan's Profile
Nagarajan
Follow me

Latest posts by Nagarajan (see all)

Leave a Reply

Your email address will not be published. Required fields are marked *