Angular 4 Directives- Lesson 3.2

Hi friends, in the last session we have learned about built-in directives (ngIf, ngFor, ngSwitch). In this session we will learn,

  • Style and Class Directives ( ngClass, ngStyle)

ngClass:

  • It is used to add and remove CSS classes on an HTML element.
  • CSS Classes can be added in several ways
  1. Using string
  2. Using array
  3. Using object
  4. Using Component methods
  • When using ngClass with object, classes will be added and removed based on the Boolean value that returned.
  • If the value of expression istrue then respective CSS class will be added otherwise that CSS class will be removed from HTML element at run time.

Using String: When using string format, class names must be presented between single quotes with in double quotes “‘class1′” and multiple classes can be separated by space.

File: template.html

File: app.component.ts

Adding styles for the respective classes in component

ngClass using array: When using Array format, each ngClass array item (i.e.,class) must be presented in the string format.

Ex: [ngClass] =”[‘class1′,’class2’]”

File: template.html

ngClass using object: When using object, classes will be formatted in the form of object i.e., each class will be of key and value pairs.

Key: css class name

Value: expression that returns Boolean value

In component file add styles for the respective classes

Using Component Methods: Whereas when using component methods, instead declaring styles statically here styles will be dynamically rendered into template by calling component methods.

  • Depending upon the need/requirement we can pass parameters to the component methods and can dynamically get the required styles.

Ex: [ngClass]=”GetStyles( )”

File: template.html

File: app.component.ts

ngStyle: This directive is used to modify the elements / component styles

  • It accepts an object which defines the elements styles.
  • Both kebab case and lower camel case can be used when specifying style properties.
  • Flexible to add and remove style properties.

File: template.html

File: app.component.ts

2 thoughts to “Angular 4 Directives- Lesson 3.2”

  1. Hi there! This post couldn’t be written any better! Reading through this post reminds me of my previous room mate! He always kept talking about this. I will forward this article to him. Pretty sure he will have a good read. Thank you for sharing!

  2. Hi tһere, simply changed іnto aware of yoսr blog- thru Google, аnd located
    thаt it iѕ truly informative. Ι’m gonna Ьe cautious
    foг brussels. І’ll appreciate if yoᥙ hɑppen to continue tһis in future.
    Numerous people ԝill proƄably be benefitd fгom your writing.

Leave a Reply

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