Middle
What is two-way and one-way data binding?
sobes.tech AI
Answer from AI
-
One-way data binding: Data flows in one direction, usually from the component to the DOM or from a parent component to a child. Changes in the data source update the view, but changes in the view do not directly affect the source.
- Examples: interpolation (
{{ value }}) or attribute binding ([attribute]="value") in Angular; props in React.
- Examples: interpolation (
-
Two-way data binding: Data is synchronized between the source (e.g., a variable in the component) and the view (e.g., an input field). Changes in the view automatically update the source, and vice versa.
- Examples:
ngModelin Angular (synthetic sugar over one-way binding and event handling); in React, usually implemented with a combination of bindingvalueand handlingonChangeevents.
- Examples:
| Principle | One-way | Two-way |
|---|---|---|
| Data flow | In one direction (source -> view) | In both directions (source <-> view) |
| Complexity | Easier for debugging, more predictable | Can be more complex to track changes |
| Performance | Often slightly more efficient (no hidden synchronization logic) | Can potentially lead to update cycles, requires caution |
| Usage | Reactive programming, predictable UIs | Rapid form development where input synchronization is important |
// Example in React (one-way binding of value and event handling to emulate two-way)
import React, { useState } from 'react';
function MyInput() {
const [value, setValue] = useState(''); // Data source
const handleChange = (event) => {
setValue(event.target.value); // Update source on input change
};
return (
<input type="text" value={value} onChange={handleChange} /> // value: one-way; onChange: event handling from view
);
}
// Example in Angular (two-way binding with ngModel)
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<input [(ngModel)]="name" type="text"> // Two-way binding
<p>Hello, {{ name }}!</p> // One-way binding
`
})
export class AppComponent {
name: string = ''; // Data source
}