Skip to content

Instantly share code, notes, and snippets.

@gund
Last active September 14, 2019 03:04
Show Gist options
  • Save gund/3ae21110e7fd9cf63cb72c54e4d6a4ac to your computer and use it in GitHub Desktop.
Save gund/3ae21110e7fd9cf63cb72c54e4d6a4ac to your computer and use it in GitHub Desktop.
Two way binding in a nutshell...

In Angular

Two-way binding is actually a one way binding with changes synchronized back to the same state

@Component({
  template: `<input [(ngModel)]="value">`
  // This is syntactic sugar of the following
  template: `<input [ngModel]="value" (ngModelChange)="value = $event">`
})
class MyComponent {
  value: string;
}

In React

Controlled inputs are actually same as two-way bindings - just more verbose in syntax

class MyComponent extends React.Component {
  state = {
    value: '',
  };

  render() {
    return <input value={this.state.value} onChange={e => this.setState({value: e.target.value})} />
  }
}

See closer

<input [ngModel]="value" (ngModelChange)="value = $event">
<input value={this.state.value} onChange={(e) => this.setState({value: e.target.value})} />

Looks the same quite similar, isn't it? =)

@gund
Copy link
Author

gund commented Sep 14, 2019

Examples in Angular how to implement decoupled reactive two-way bindings: https://stackblitz.com/edit/angular-two-way-magic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment