Property Binding

  • Property binding is used to set the data from the component class to template i.e the html file.
  • We are going to change the text of an element after 5 seconds using property binding.
  • For this first we will create a new project using angular cli

First we need the create new angular project using angular CLI using below command

sudo ng new PropertyBindingDemo

Then we need to change app.component.html contents as per below

<div [innerHTML]="htmlStr">Default Message</div>

And app.component.ts file as per below.

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

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'PropertyBindingDemo';
  htmlStr : string = "Hello Static message";
  constructor() {  
    setTimeout(() =>{  
      this.htmlStr = "Hello Property Binding";  
    }, 5000);  

Now you can start the server by using command ng serve

Initially the screen will look like below

After 5 seconds the message changes to below screen

  • In the above code, we only change the value of htmlStr property in class AppComponent but the value of the template page i.e html changes because of the property binding.
  • [innerHTML]=”htmlStr” in app.component.html change the html inside the div tag according to the value of htmlStr data memeber in AppComponent class in app.component.ts file.

Some example of property that are binded using property binding

<input [value]="firstName">	
Binds property value to the result of expression firstName.

<div [attr.role]="myAriaRole">	
Binds attribute role to the result of expression myAriaRole.

<div [class.extra-sparkle]="isDelightful">	
Binds the presence of the CSS class extra-sparkle on the element to the truthiness of the expression isDelightful.

<div [style.width.px]="mySize">	
Binds style property width to the result of expression mySize in pixels. Units are optional.

Reference :

Leave a Comment