Angularjs component styling Part III : conditionally bind class


Binding style class

You have been noticed that every Angularjs component has a component.css. This is where place all your SASS/CSS styling classes and ids. We can also use the inline style in your component.ts file, if you prefer ( as an array).

Define class as property

In class definition declare property with class.

  // style class
  public btnStyle = 'btn';

Property for toggling style

   public enableStyle = false

Define CSS

In your app component.css file define a simple button class

.btn{    
background-color:rgba(51, 134, 243, 0.986);    
margin: 5px;    
padding: 4px;    
color: white;    
border: 1px;    
border-radius: 2px;
}

Bind the class conditionally

To bind the class based on the property , the style will only applied when the property is set to true.

<button [class.btnStyle]="enableStyle">OK</button>

Class binding has higher precedence in Angular, that means when we use the both methods only the binding will work. So both can’t be used.

Keep reading Angular posts

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.