While working on Angular projects, We frequently need to dynamically style the template of Angular components. Therefore as an Angular developer, it’s necessary to know the different ways to dynamically style the template of Angular components.
So in this article, We will see the easiest ways(using ngStyle and ngClass) to dynamically add the style into the Angular component template.
For applying multiple inline styles dynamically, ngStyle is used. All the css properties are applied with the help of an object: See the example below:
<div [ngStyle] = { ‘backgroundColor’ : blue, ‘padding’ : ‘10px’ } />
The same property can be applied by writing below also:
<div [ngStyle] = { ‘background-color’ : blue, ‘padding’ : ‘10px’ } />
Both the above example works in the same because CSS format or javascript format can be used.
With Condition
If some css property needs to apply on the base of some condition then the same can be applied easily with ngStyle syntax. See the example below:
<div [ngStyle] = { ‘backgroundColor’ : isTrue ? ‘green’ : ‘red’} />
In the above example, we can see, on the base of the value of isTrue background color of the div applies.
Define style object in the component file
It is also possible to define the style properties object in the component file and apply it in the Component template file. See the example below:
Inside component.ts file,
….
this.dynamicStyle = {‘color’: ‘red’, ‘height’:’50px’, width:’30px’}
…
Inside component.html file
<div [ngStyle] = “dynamicStyle” />
It is one the easiest ways to dynamically add style to the component. With the help of this attribute, class can be added dynamically into the template where the class definition is available in the external CSS file. See the example below:
A. Add different classes on the base of a condition
<div [ngClass] = ” { ‘top docs’ : condition } ” />
B. Add different classes on the base of different conditions
<div [ngClass] = ” { ‘top : condition1, ‘docs’ : condition2 } ” />
C. Add different classes alternately on the base of diferent conditions(using ternary operator)
<div [ngClass]="isActive? 'active’:’inactive' " >
Let me know your thoughts over email pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.
Thank You!