How to add styles in Angular?
- Angular uses the templates so that we can easily style using class names, style attributes.
Using class attribute
<div class="box"> <h1>Hello angular</h1> </div>
Using style attribute.
<div><p style="color:red" > using style attribute </p></div>
How to dynamically add and remove class names in angular?
sometimes we need to add and remove styles in particular use cases like disabling buttons and changing the colors.
To get this behavior we need to use [ngClass] instead of the normal class attribute.
export class MyComponent {
isActive=true
}
In below example, we used a ternary operator so that if an isActive property is true it adds box-1 class else it adds the box-2 class.
what ngClass does is it evaluates the javascript expression.
<div [ngClass]="isActive? 'box-1’:’box-2' " >
<h1>How to style dynamically</h1>
<p>To style dynamically in angular we need to use [ngClass]</p>
</div>
How to dynamically add and remove inline styles in angular?
We need to use [ngStyle] directive instead of the normal html style attribute and we need to pass styles as an object.
export class AppComponent {
isActive=false
box = {
border: '1px solid black',
width: "50%",
color:"blue"
}}
<div [ngStyle]="box"> <h1>Hello</h1> </div>
second-way using the ternary operator
<p [ngStyle]="{color:isActive?'red':'green'}">
This always green color because isActive property is false
</p>
✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.