The aim of this tutorial is to understand the concept of data binding in Angular and learn how to bind component data to the HTML template.
By the end of this tutorial, you should be able to:
Before you proceed, you should have:
Data binding in Angular is a technique to link your data to your view layer. By binding a variable, you are essentially creating a two-way data binding - the model and view.
Interpolation is a special syntax that Angular converts into property binding. It’s a way to display a component property in the HTML template. It is denoted by double curly braces: {{ }}
.
Property binding is one way, from the component to the view. It involves binding DOM properties (values) to a component’s property.
// app.component.ts
export class AppComponent {
title = 'Hello World';
}
<!-- app.component.html -->
<h1>{{ title }}</h1>
In the above example, {{ title }}
in the HTML will be replaced by the value of the title
property from the component.
// app.component.ts
export class AppComponent {
isDisabled = true;
}
<!-- app.component.html -->
<button [disabled]="isDisabled">Click me</button>
In this example, the button's disabled attribute is bound to the isDisabled
property from the component. If isDisabled
is true, the button will be disabled.
In this tutorial, we learned about data binding in Angular, how to bind component data to the HTML template, and the usage of interpolation. We explored property binding and provided examples for each.
Create a new component with a property message
and display this property in the HTML template using interpolation.
// message.component.ts
export class MessageComponent {
message = 'Hello Angular';
}
<!-- message.component.html -->
<p>{{ message }}</p>
In the above example, the message
property from the component is displayed in the HTML template.
Create a new component with a property isHidden
and bind this property to the hidden attribute of a div
in the HTML template.
// visibility.component.ts
export class VisibilityComponent {
isHidden = false;
}
<!-- visibility.component.html -->
<div [hidden]="isHidden">This is a visible div</div>
In this example, the div's hidden attribute is bound to the isHidden
property from the component. If isHidden
is true, the div will be hidden.
Try to create more complex scenarios using interpolation and property binding. Experiment with different HTML elements and attributes. The more you practice, the more comfortable you'll become with data binding in Angular.