Angular two way binding and banana box syntax

Adrian Brand
1 min readMar 11, 2021

--

In Angular we have input properties

@Input()
myInputProperty: string;

and event emitters

myInputPropertyChange = new EventEmitter<string>();

We can use these to bind to in the template

<my-component [myInputProperty]="propertyToBindTo" (myInputPropertyChange)="propertyToBindTo = $event"></my-component>

Because of the way this input property and event emitter combination are named where the event emitter has the same name as the input property with the suffix Change we can do the above binding with the short hand version called two way binding.

<my-component [(myInputProperty)]="propertyToBindTo"></my-component>

In the above banana box syntax [()], it looks a banana in a box, the compiler looks for an input property with the same name and a matching event emitter with the suffix Change.

When we are binding to template forms with the ngModel directive we have the same concept. The ngModel directive has an input property called ngModel and an event emitter called ngModelChange. Here is the source code if you are interested. https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts

This means we can simply two way bind to a form control

<input name="checked" [(ngModel)]="propertyToBindTo">

or we can add some custom logic when using the value that comes from the user input

<input name="propertyToBindTo" [ngModel]="propertyToBindTo"  (ngModelChange)="myFunctionWithCustomLogic($event)">

I know this is pretty much Angular 101 stuff but some of the pull request I get lately make me realise some devs don’t quite get the banana box syntax. It really is quite simple once you understand it is just shorthand for an input property and event emitter combo with matching names.

--

--

No responses yet