Angular Data Binding – Part III

Style Binding

  • Style binding is used to set a style of a view element.
  • Style Binding starts with the prefix class, followed by a dot (.) and the name of the style style.style-name.
  • ngStyle adds and removes a set of HTML styles

Write the below code in app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
fontSize: number = 30;
 addStyles() {
    let styles = {
        'font-weight': this.isBold ? 'bold' : 'normal',
        'font-style': this.isItalic ? 'italic' : 'normal',
        'font-size.px': this.fontSize
    };

    return styles;
}
}

Write the below code in app.component.html

<h1>{{"Style Binding"}}</h1>
<div>  <button style='color:red' [style.font-size.px]="fontSize">My Button
</button> </div>
<br/>

<h1>{{"ngStyle"}}</h1>
<div><button style='color:blue' [ngStyle]="addStyles()">My Button 2</button></div>
<br/>

Once you run the code, you can see the similar below screen

Class Binding

  • Class binding is used to set a class property of a view element.
  • We can add and remove the CSS class names from an element’s class attribute with class binding.
  • Class Binding starts with the prefix class, followed by a dot (.), and the name of the class class.class-name
  • ngClass adds and removes a set of CSS classes.

Write the below code in app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  applyBoldClass: boolean = false;
  classesToApply: string = 'italicsClass boldClass';
  applyItalicsClass: boolean = true;

  addClasses() {
        let classes = {
            boldClass: this.applyBoldClass,
            italicsClass: this.applyItalicsClass
        };

        return classes;
    }
}

Write the below code in app.component.html

<h1>{{"Class Binding"}}</h1>
<div><button class='colorClass'>My Class Button</button></div>
<div><button class='colorClass' [class]='classesToApply'>My classes to apply Button</button></div>
<div><button class='colorClass' [class.boldClass]='applyBoldClass'>My Bold Class Button</button></div>
<div><button class='colorClass boldClass italicsClass'
  [class.boldClass]='applyBoldClass'>My Color Italics Class Button</button></div>
<br/>
<h1>{{"ngClass"}}</h1>

  <div> <button class='colorClass' [ngClass]='addClasses()'>My ngClass Button</button></div>
<br/>

Write the below code in app.component.css

boldClass{
    font-weight:bold;
}

.italicsClass{
    font-style:italic;
}

.colorClass{
    color:red;
}

Once you run the code, you can see the similar below screen

References

  • https://angular.io/guide/template-syntax

We will discuss about Attribute and Two way binding in our upcoming Blog article.

Happy Learning!