-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: &lt;switch [ngModel]=&quot;value&quot; (ngModelChange)=&quot;value = $event&quot;&gt;&lt;/switch&gt;, }) export class AppComponent { value = false; }

Those look functionally identical to me.

Can someone help explain the difference?

Paul Draper
  • 6,080

1 Answers1

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. :-)

JanRecker
  • 1,584