For enquiries call:

Phone

+1-469-442-0620

HomeBlogWeb DevelopmentUnderstanding Property Binding in Angular

Understanding Property Binding in Angular

Published
18th Sep, 2023
Views
view count loader
Read it in
10 Mins
In this article
    Understanding Property Binding in Angular

    Angular is a component-based framework. Components are the building blocks of any angular application that controls and defines different aspects of the application. A component consists of an HTML template that tells the browser how it should render. This rendered version is called a View.  

    Property binding in Angular is one of the approaches you can use to set the property of an element in the view to a property defined in the component. You can use property binding to set attributes such as class, href, src, textContent, etc. Properties of custom components and directives can also be set using property binding. Angular's built-in directives manage forms, lists, styles, and what users see. 

    In more practical terms, property binding helps us pass data from the component typescript class (component.ts) and provide the value rendered in the HTML template (component.html). 

    Understanding these concepts is critical to building robust websites and controlling the flow of data in them. You can check out KnowledgeHut Web Designing and development course to learn more about this. 

    Know more about an introduction to angular components. 

    What is Property Binding in Angular? 

    Before understanding property binding, we must understand the difference between an HTML Attribute and a Document Object Model (DOM). Attributes are constants defined in HTML used to initialize the DOM properties, while the DOM properties refer to the current value of those attributes. HTML attributes remain unchanged. Property binding is used to assign a value to a given DOM property. 

    In property binding, properties are directly enclosed in square brackets and assigned a value using single quotes. These values are generally defined in the component class. Property binding is unidirectional. This implies that the data flows only in one direction, from the component to the template. We can update the values defined in the component, which updates the view.  

    However, the reverse is not possible. Any updates in the rendered view do not change the values in the component class. Take the case of an input form field as an example. By using Property Binding, you can set the initial value of the input. However, users can delete and type a new value in the view and change it. This does not update the initial value defined in the component. 

    Angular internally uses a change detection and run-time optimization algorithm to monitor any DOM and component changes and keep the view in sync with the latest information. You check out this course on angular advanced topics to learn more. 

    Get to know more about advantages and disadvantages of angular. 

    Four Types of Data Binding in Angular 

    We can broadly classify Binding in Angular into four types: 

    1. Interpolation 
    2. Property Binding 
    3. Event Binding 
    4. Two-way Binding 

    All types of bindings have two important aspects, a target that receives a value and a template expression that produces it from the model. These bindings vary from each other based on the direction of the data flow and how they are implemented in Angular. 

    Interpolation and Property Binding are one-way Data Binding methods from the component to the view of an Angular application. In Interpolation, expressions are embedded in a marked-up text, which is evaluated and passed on to the view as strings. It is implemented using double curly braces. Event binding binds events like delete requests and mouse clicks with some event handlers. Here, data flows from the view to the component class. Two-way binding is a mix of event and property binding where the data flow is bidirectional. 

    Property Binding can be further classified into multiple categories based on what type of value we bind: 

    1. Class Binding: Here, we set the value of the class of an HTML element in the view. 
    2. Style Binding: This sets CSS styling of a given HTML element. 
    3. Attribute Binding: This implies the binding of any attribute of an HTML element. For example, an <img> element can have an “src” attribute or an “alt” attribute, the value of which can be set using property binding. 

    Property Binding Example  

    Let us look at the various ways you can practically implement Property Binding in Angular. Before we get started, be aware that a simple angular component consists of the following: 

    • A component typescript class where we can define the attributes we want to bind and set the paths to the HTML template and the CSS styling. In our demo, this is the app.component.ts file. 
    • An HTML template that includes the code rendered in the view. This is where we use property binding to read the values defined in the component class. 
    • A CSS file where all the styling related to the HTML template is defined. 

    Here are the various scenarios where we can see the practical application of Property Binding: 

    1. Setting Properties of an HTML Tag 

    Let us take an example of the Input tag, which has many different attributes like “value,” “readonly” “disabled,” etc. Using the square bracket syntax, we can define all of them in our HTML template. 

    !-- app.component.html --> 
    <h1>Demo Output</h1> 
    <!-- Setting attributes of input using property binding --> 
    <input [value]='title'> 
    <br /> 
    <br /> 
    <input [readonly]=true> 
    <br /> 
    <br /> 
    <input [placeholder]='helloWorld'> 
    <br /> 
    <br /> 

    Whatever attributes we set, we have to define them in our component class. You can also pass some values directly. In this case, we have to define ‘title’ and ‘helloWorld’.  

    // app.component.ts 
    import { Component } from '@angular/core'; 
     
    @Component({ 
      selector: 'app-root', 
      templateUrl: './app.component.html', 
      styleUrls: ['./app.component.css'] 
    }) 
     
    export class AppComponent { 
      title = 'Knowledge Hut'; 
      helloWorld = 'Hello World'; 
    } 

    Here Is the output in the browser where we can see the values rendered. Note, that the second input box here is disabled as expected;  

    Similarly, any attribute of any HTML element can be passed down from the component class to the HTML template. 

    1. Using the “bind” Keyword 

    Let us take another example where we set an image's “src” attribute. Instead of using the square brackets, we can also use the “bind-” keyword, as seen below: 

    // app.component.ts 
    import { Component } from '@angular/core'; 
     
    @Component({ 
      selector: 'app-root', 
      templateUrl: './app.component.html', 
      styleUrls: ['./app.component.css'] 
    }) 
     
    export class AppComponent { 
    src= 'https://www.knowledgehut.com/_next/image?url=%2FKH_Logo_18_May%20(1).svg&w=1920&q=75'; 
    } 
    <!-- app.component.html --> 
    <h1>Demo Output</h1> 
     
    <!-- Getting image source --> 
     
    <img [src] = 'src'> 
    <br /> 
    <br /> 
    <img bind-src = 'src'> 
    <br /> 

    Both the approaches give the same output:  

    1. Disabling a Button Using Property Binding 

    You can set the boolean value for the disabled attribute of an HTML button using property binding: 

    <!-- app.component.html --> 
     
    <h1v>Demo Output</h1v> 
     
    <!-- Disabling a button using property binding --> 
    <button [disabled]='bool' style="margin: 20px;">Click Me!</button> 
    // app.component.ts 
    import { Component } from '@angular/core'; 
    @Component({ 
      selector: 'app-root', 
      templateUrl: './app.component.html', 
      styleUrls: ['./app.component.css'] 
    })  
    export class AppComponent { 
      bool = 'true'; 
    } 

    1. Binding Inner HTML and CSS Classes 

    Property Binding is not just limited to single values. You can also bind entire HTML components and style classes. This is done by setting the inner HTML attribute to whatever HTML code we want to render on screen. The styles can be defined under  app.component.css, and the class name can be bound to the class attribute. As an example, let us create a card component and bind it to an HTML div element: 

    /* app.component.css */ 
    /* CSS styles are defined here */ 
    .card { 
        box-shadow0 4px 8px 0 rgba(0,0,0,0.2); 
        transition0.3s; 
        width20%; 
        padding20px; 
        margin-left5%; 
    } 
    .card:hover { 
        box-shadow0 8px 16px 0 rgba(0,0,0,0.2); 
    } 
    // app.component.ts 
    import { Component } from '@angular/core'; 
    @Component({ 
      selector: 'app-root', 
      templateUrl: './app.component.html', 
      styleUrls: ['./app.component.css'] 
    }) 
    export class AppComponent { 
      card = '<div><h4><b>Title</b></h4><p>Description</p></div>' 
      cardClass = 'card'; 
    } 

    Notice that we are passing two variables. In card, we are directly passing on direct HTML code to render while using cardClass to pass the class name we defined in the styles above. 

    <!-- app.component.html --> 
    <h1 >Demo Output</h1 > 
    <!-- HTML passed down + binding CSS classes --> 
    <div [innerHtml]='card'></div> 
    <br /> 
    <div [innerHtml]='card' [class]='cardClass'></div> 
    <br /> 

    The entire HTML is rendered as expected and the styles are correctly applied in the second case where we passed down the CSS class. 

     

    1. Binding Styles 

    You can also bind styles directly without using CSS classes via various style attributes. Alternatively, you can group all the style attributes together and bind them using “ngStyle”. Here is an example to demonstrate the same; 

    Let us define styles in our component class in two ways- grouped together and separately. 

    // app.component.ts 
    import { Component } from '@angular/core'; 
    @Component({ 
      selector: 'app-root', 
      templateUrl: './app.component.html', 
      styleUrls: ['./app.component.css'] 
    }) 
    export class AppComponent { 
      styles = { 
        color: 'blue', 
        fontSize: '25px', 
      }; 
      color = 'blue'; 
      fontSize = '25px'; 
    } 
    <!-- app.component.html --> 
    <h1 >Demo Output</h1 > 
    <!-- Binding styles --> 
    <h1 [style.color]='color' [style.font-size]='fontSize'>Hello World</h1 > 
    <h1 [ngStyle]='styles'>Hello World</h1 > 

    Both approaches render the same output. 

    1. Binding Mathematical Expressions 

    In this case, the computed answer is passed down into the view. 

    <!-- app.component.html --> 
    <h1 >Demo Output</h1 > 
    <!-- Mathematical expressions --> 
    <p [innerText]="100*50"></p> 

    Unlock the Power of Python: The Best Course for Python, Mastering this Dynamic Language. Join Now and Discover the Endless Possibilities!

    Conclusion 

    Property Binding is integral to controlling data flow and DOM values from the component to the view in any Angular project. It can be used in multiple ways to control the presentation and logical flow of the application. For example, you can dynamically set paths or styling or use it to disable/enable functionalities of your HTML components. To dive deeper into various binding methods and other Angular concepts, you can check out KnowledgeHut’s advanced Angular topics training program. 


    Frequently Asked Questions (FAQs)

    1What is the difference between Property Binding and Interpolation in Angular?

    In Angular, Interpolation is a form of one-way data binding from the component to the HTML template using expressions embedded in the text. It is similar to Property Binding; in fact, Angular internally converts Interpolation into Property Binding. However, there is some fundamental difference in how it is implemented and used as follows: 

    Property BindingInterpolation
    Syntax used to implement is [ ] (square brackets)Syntax used to implement is {{ }} (double curly braces)
    Does not convert any expression evaluated into a string.Evaluated expressions are converted into strings and passed on to render in the view.
    Can be used to pass boolean valuesCannot be used to pass boolean values
    2What are Data Binding and Property Binding?

    Data Binding in angular is a method by which one can establish a real-time connection between a view rendered by a template and a component class. Data Binding helps us keep the model and view in sync and pass values to and from each other. 

    Property Binding is a type of Data Binding that is one-directional and helps us pass the value of HTML properties from the component class to the HTML template that renders them. 

    3What are the different types of binding in Angular?

    Based on the direction of data flow, you can classify binding in Angular under the following categories: 

    • Source to View 
    • Interpolation 
    • Property 
    • Attribute 
    • Class 
    • Style 
    • View to Source 
    • Event Binding 
    • Two-way Binding 
    Profile

    Sachin Bhatnagar

    Program Director, FSD

    With 20+ yrs of industry experience in media, entertainment and web tech, Sachin brings expertise in hands-on training and developing forward-thinking, industry-centric curricula. 30k+ students have enrolled in his tech courses.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon