13

Using ngReact, how does one elegantly set up a two-way data binding?

Let's say I have a simple React input component, which takes a value and fires onChange:

angular.module('app', []).value('SimpleInput', props => 
  <input type='text' 
         value={props.value}
         onChange{e => props.onChange(e.target.value)} />
)

Then from the AngularJS side, I would expect something like this to update value in the scope:

<react-component name="SimpleInput" 
                 props="{value: value, onChange: v => value = v}">
</react-component>

However, is there a more elegant way to set up the two-way binding to the AngularJS scope, akin to ng-model?

ᆼᆺᆼ
  • 14,442
  • 8
  • 53
  • 87

2 Answers2

6

I don't think so. ngReact is merely a means to inject React components into an Angular framework; React was specifically designed to not have two-way data binding in favor of performance, so any implementation of that would necessarily be a work-around.

From the horse's mouth:

ngReact is an Angular module that allows React Components to be used in AngularJS applications. Motivation for this could be any of the following: You need greater performance than Angular can offer (two way data binding, Object.observe, too many scope watchers on the page) ...

Daniel Cottone
  • 3,589
  • 21
  • 37
0

I don't have much experience with ngReact, but the React way of doing it is to use refs, and fetch the value from the ref when you need it. I'm not sure what you component code looks like, so I can only guess. If you have an input field inside the component, do this:

var SimpleInput = React.createClass({

accessFunc: function(){
    //Access value from ref here.
    console.log(React.findDOMNode(this.refs.myInput).value);
},

render: function(){
    return (
        <input type="text" ref="myInput" />
    )
  }
})

However, you can also bind the value to a state variable using linkState: https://facebook.github.io/react/docs/two-way-binding-helpers.html

However, I would strongly recommend using the first way, because one of the reasons React is so much faster than Angular is because it avoids two way binding. Still, here's how:

var SimpleInput = React.createClass({

getInitialState: function(){
    return {
        myInput: ''
    }
},

render: function(){
    return (
        <input type="text" valueLink={this.linkState('myInput')}/>
    )
  }
})

Now any time you access this.state.myInput, you'll get the value of the input box.

siddhant
  • 639
  • 7
  • 22