Data Binding #
When it comes to data binding in Angular, the synergy between TypeScript and HTML is facilitated through various techniques:
String Interpolation: #
- Utilizes double curly braces
{{ data }}to inject dynamic values into HTML. - Example:
<p> Hi {{ Name }}</p> - The variable
Nameis Declared , assigned or modified in the respective TypeScript file. - Note: The
{{ }}can encapsulate expressions like ternary operations or functions returning strings.
Property Binding: #
- Links TypeScript properties with HTML attributes or properties.
- Example:
<button [disabled]="!active">Submit</button> - The
activevalue toggles between true and false to enable or disable the button. - String Interpolation and Property Binding can often be used interchangeably.
- Examples using either approach:
<p>{{name}}</p><p [innerText]="name"></p>- Both yield the same result, e.g., ‘john’.
- Note: Avoid mixing String Interpolation and Property Binding.
Event Binding: #
- Triggers actions in response to events.
- Example:
<button (click)='onClickCreate()'>Create</button> - The
(click)event calls theonClickCreatefunction defined in the TypeScript code. - Additional example passing data during an event:
<input type="text" (input)="onUpdate($event)">- TypeScript:
onUpdate(event: Event) {
this.name = (<HTMLInputElement>event.target).value;
}
- when user enters data into the input field it will trigger the function with a
$eventvariable containing event data, including the value input by the user.
Two-way Binding: #
- Combines Property and Event Bindings for a bidirectional flow.
- Example:
<input type="text" [(ngModel)]="serverName"> - Updates the
serverNamevalue when changed in the field or TypeScript. - Note: Enable Two-Way Binding by importing and adding the
FormsModulefrom@angular/formsto theimports[]array in the AppModule. Note: Remember to also include the import statement:
import { FormsModule } from '@angular/forms';
These data binding techniques empower developers to create dynamic and interactive Angular applications, seamlessly connecting the logic in TypeScript with the representation in HTML.