Class Binding in Angular 8

Class binding in Angular makes it very easy to set the class property of a view element. We can set or remove the CSS class names from an element’s class attribute with the help of class binding.

We bind a class of a DOM element to a field that is a defined property in our Typescript Code. Its syntax is like that of property binding.

Syntax:

<element [class] = "typescript_property">

Approach:

  • Define a property element in the app.component.ts file.
  • In the app.component.html file, set the class of the HTML element by assigning the property value to the app.component.ts file’s element.

Example 1: Setting the class element using class binding.



app.component.html

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<h1 [class] = "geeky">
  GeeksforGeeks
</h1>
Upper Heading's class is : "{{ g[0].className }}"

chevron_right


app.component.ts

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

import { Component, OnInit } from '@angular/core';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {
    geeky = "GeekClass";
    g = document.getElementsByClassName(this.geeky);
}

chevron_right


Output:

Example 2: setting the class element using a function.

app.component.html

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<h1 [class] = "setClass()">
  GeeksforGeeks
</h1>
Upper Heading's class is : "{{ g[0].className }}"

chevron_right


app.component.ts

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

import { Component, OnInit } from '@angular/core';
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {
    setClass() {
        return "GeeksforGeeks";
    }
    g = document.getElementsByClassName(this.setClass());
}

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.