0
votes

I'm trying to make two-way binding in a component and propagate it through other components that contain the child component:

I have a child component, with two-way binding and it's working. The binding is pointing to a variable called child_value

Then this child component is present in the template of a parent component. I want a two-way binding here too, so I use [(child_value)]=parent_value

Finally this parent component is used in my application, so in this component I also want a two-way binding like [(parent_value)]=application_value

But only the first binding is working in two way. To exemplify it I created this plunker

http://plnkr.co/edit/IWVzmRbqL3ARFaYxjs3F?p=preview

When you drag the slider you can see that the Child value updates, but the others don't. If I change the application_value in code, through the button, then it is propagated through all components.

1

1 Answers

5
votes

1. The easiest way to fix your code:

If you check the console log that you've written into, you can see that AppComponent and ParentComponent are notified by the valueChanged event, all you need to do is to update the value of the variables accordingly:

In AppComponent:

  onchange(event)
  {
    this.application_value = event.value; // <-- add this line
    console.log('root::onchange() => value:' + event.value);
  }

In ParentComponent:

  onchange(event)
  {
    this.parent_value = event.value; // <-- add this line
    console.log('parent::onchange() => value:' + event.value);
    this.valueChanged.emit({value: event.value});
  }

Here's the plunker for your reference: http://plnkr.co/edit/TW2F6mdx1SJbdjKqonmO?p=preview

2. Understand two-way binding and make it works:

Here is the reason why the two-way binding doesn't work on your case:

The banana in the box syntax ([(child_value)]="someValue") is just a syntactic sugar for having both [child_value]="someValue" and (child_valueChange)="someValue=$event".

And because you never define the @Output() child_valueChange in your component, the return way is blocked. To solve it:

  • Change your @Output() valueChanged to @Output() child_valueChange in your ChildComponent and
  • Change your @Output() valueChanged to @Output() parent_valueChange in your ParentComponent

The second plunker that has working two-way binding: http://plnkr.co/edit/M5CPqrgWJ53vBkqhVz4f?p=preview