2

I'm having trouble getting custom two way data binding to work in Angular 2. The Docs indicate that the banana in a box model - [()] is just syntatic sugar, however in my example this way doesn't work and the longer method works:

<child-component [(test)]="check">This child updates only itself</child-component>
<child-component [test]="check" (check_send)="check=$event">This child updates all</child-component>

The @Output event is not changing the parent value in the banana in a box model (first line). As the second line works I don't see what I am doing wrong. Here is a link to the docs: https://angular.io/guide/template-syntax#two-way-binding---

Here is a plunker I have created to showcase this behavior:https://embed.plnkr.co/eTfkQmRfBRxeKCEpGdzh/

Edit: This is a different question to a possible duplicate because this question does not produce any errors, plus it is a much more simple and localised problem with the formatting of two way bind.

Daniel Judd
  • 23
  • 1
  • 5
  • Possible duplicate of [Angular2 - two way databinding on a component variable / component class property?](https://stackoverflow.com/questions/35639650/angular2-two-way-databinding-on-a-component-variable-component-class-propert) – HaveSpacesuit Jul 11 '17 at 16:04

1 Answers1

4

It's because check_send needs to be testChange as it is written in the documentation, Angular de-sugars that code with a xxxChange syntax.

<child-component [test]="check" (testChange)="check=$event">This child updates all</child-component>

@Output() testChange = new EventEmitter<number>();

this.testChange.emit(this.test);

Fixed stackblitz: https://stackblitz.com/edit/angular-ivy-165fvb?file=src%2Fapp%2Fapp.component.ts

eko
  • 39,722
  • 10
  • 72
  • 98
  • 1
    Good answer. I think the docs could be a little clearer (I thought that it was subjective, also I don't really like camelCase) for people like me. You would have thought that they could have used a red important block under the yellow banana block to say that this formatting was important. – Daniel Judd Jul 11 '17 at 16:22
  • @DanielJudd I definitely agree – eko Jul 11 '17 at 16:29
  • the plunker above not running in todays chrome/firefox browsers. My stackblitz reproduction seems to be identical code but is failing to support banana in box notation for a 2 way binding. Changes in the child component are not emitted back to the parent. Splitting notation into event binding works. Do you have any clues why my code is NOT working? Please fork and share your link, Thank you. https://stackblitz.com/edit/ionic-23dufx?file=pages%2Fhome%2FValueSelectorComp.ts – Meryan Jan 12 '22 at 01:39
  • I updated the code to stackblitz but i didn't understand what you're trying to do in your stackblitz. Could you elaborate? I tried clicking on "set/change value" in the child component and it seems to be working – eko Jan 12 '22 at 09:02