ngstyle Angular 6 | ngstyle Angular 8 | Attribute Directives in Angular

ngstyle Angular 6 | ngstyle Angular 8 | Attribute Directives in Angular

Hello and welcome back to our series on Angular tutorials for beginers. In our previous video we learnt about directives and its categories. The video link is coming in suggessions and I will also provide the links in the comment box. Don't forget to check it out.  

In this video we will learn:

Attibute directive, I will talk about ngStyle attribute directive in this video and in the next video I will talk about ngClass.

At the end of this video, you will be able to understand, when and how to use ngStyle directive to set and element style.

So, without any further delay lets start-

In my previous video I created this table out of students array of objects. This table contains the information about the students.

The NgStyle directive lets you set a given DOM elements style properties.
One way to set styles is by using the NgStyle directive and assigning it an object literal, like so:






<div [ngStyle]="{'background-color':'green'}">Hello World</<div>



This sets the background color of the div to green.

ngStyle becomes much more useful when the value is dynamic. You can set the background color of the div based on the value passed from the component.

Lets create one more property for student object call it house and assign some color to it.


Now go back to the html-



<div [ngStyle]="{'background-color': student.house}">Hello World</<div>



Lets imagine we wanted to set the font size to 24, we could use:

[ngStyle]="{'font-size':24}"

But this wouldn’t work, it isn’t valid CSS to just set the font size to 24. We also have to specify a unit such as px or em.

if we wanted the size to be 24 pixels we would write:
{property}.{unit}
which looks like this-



 [ngStyle]="{'font-size.px':24}"



The .px suffix says that we are setting the font-size in pixels.



You could .em to express the font size in ems or even in percentage using .%


This is also applicable with the alternative syntax, e.g:-
[style.font-size.px]="24"


So,



This is all for now. If you have any questions/suggessions/feedback, you can share in the comment box and stay tuned for upcoming videos on directives.. thank you for listening!!

Comments