-3

After hours of reading blog posts, I understand that React has one-way data binding, and Angular has two-way. But I don't actually know what that means....

React

import { useState } from 'react';
import Switch from "./switch";

function App() {
  const [value, setValue] = useState(false);
  return (
    <Switch
      isOn={value}
      handleToggle={() => setValue(!value)}
    />
  );
}

Angular

import { Component } from '@angular/core';

@Component({
  selector: 'app',
  template: `
    <switch [ngModel]="value" (ngModelChange)="value = $event"></switch>
  `,
})
export class AppComponent {
  value = false;
}

Those look functionally identical to me.

Can someone help explain the difference?

1
  • 1
    Your angular example isn't two-way binding. Two-way binding looks like [(something)]="something". Commented Nov 25, 2020 at 15:36

1 Answer 1

0

In your examples, both frameworks make use of two one-way bindings. That means in both cases there is a one way binding from the JavaScript datamodel to the HTML and a second binding from the HTML to the JavaScript model.

A "Two-way-Binding" would be (like @Karl Bielefeldt mentioned) to write (in Angular) someling like [(myHTMLAttribute)]="myJavaScriptValue"

The important difference is that in the second approach your value could be changed directly from both sides (HTML / JavaScript). While the one-way-binding approach makes it very explicit. The JavaScript value is reflected in the HTML. And if someone changes the value in HTML, the JavaScript value is NOT directly changed. Instead a method is called (which is under your control) and there you can decide to update the JavaScript value.

Two-way bindings safe some code you would have to write if you would use only one-way-binding.
On the other side it makes your code less explicit and partially harder to understand and less easy to debug.
At least thats what i think. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.