Data Binding
Data Binding in Angular
Types of Data Binding
Angular provides several ways to bind data between your component’s TypeScript code and the HTML template.
1. One-way Binding
Data flows in one direction: from the component to the view (HTML).
Interpolation {{ }}
Displays component data in the view:
// component.ts
export class GreetingComponent {
name = 'John';
}
<!-- template.html -->
<h1>Hello, {{name}}!</h1>
Property Binding [ ]
Binds a component property to an element property:
// component.ts
export class ButtonComponent {
isDisabled = true;
imageUrl = 'path/to/image.jpg';
}
<!-- template.html -->
<button [disabled]="isDisabled">Click me</button>
<img [src]="imageUrl" [alt]="'Profile image'">
2. Two-way Binding [( )]
Synchronizes data in both directions between the component and view.
Using ngModel
First, import FormsModule in your module:
// app.module.ts
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
BrowserModule,
FormsModule // Add this
],
// ...
})
export class AppModule { }
Then use [(ngModel)] in your component:
// component.ts
export class NameComponent {
name = '';
}
<!-- template.html -->
<input [(ngModel)]="name">
<p>Hello, {{name}}!</p>
Complete Example
Here’s a working example combining different types of binding:
// name-editor.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-name-editor',
template: `
<div>
<label>Name: </label>
<!-- Two-way binding -->
<input [(ngModel)]="name">
<!-- One-way binding with interpolation -->
<p>Hello, {{name}}!</p>
<!-- Property binding -->
<button [disabled]="!name">Clear</button>
<!-- Event binding -->
<button (click)="resetName()">Reset</button>
</div>
`
})
export class NameEditorComponent {
name = '';
resetName() {
this.name = '';
}
}
Evaluation Question
Q: “How do you change an input value without ngModel?”
A: You can use a combination of property binding and event binding (also known as “banana in a box” syntax):
// component.ts
export class ManualBindingComponent {
name = '';
onNameChange(event: any) {
this.name = event.target.value;
}
}
<!-- template.html -->
<input [value]="name" (input)="onNameChange($event)">
<p>Hello, {{name}}!</p>
This approach:
- Uses [value] to bind the component property to the input
- Uses (input) event to update the component property when the user types
- Gives you more control over the input handling
- Doesn’t require FormsModule
Best Practices
- Use interpolation {{ }} for text content
- Use property binding [ ] for element properties
- Use [(ngModel)] for form inputs when two-way binding is needed
- Consider manual binding for more control or when FormsModule isn’t available
- Always validate and sanitize user input when using two-way binding
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.