Custom Angular Component Using Two-Way Data Binding AKA “BANANA IN A BOX” = [🍌] Syntax

Standard Angular Two Way Data Binding is by using the [(ngModel)]=”model”.

In this article, I will show how we can create a custom component and using the “BANANA IN A BOX” syntax [()] for Two-Way Data Binding without using the ngModel.

For Example: <my-input [(value)]=”value”></my-input>

What is “BANANA IN A BOX” [🍌]

So instead of writing it explicitly:
<my-input [text]="val" (textChange)="val=$event"></my-input>

We can leverage the shortened syntax:
<my-input [(text)]="val"></my-input>

Why is it named “BANANA IN A BOX”?

  • [] = box
  • () = banana.
  • [()] = banana in a box 😃

Build the Custom Input Component

Custom Input Component

Let's break down the above custom input component:

  1. The template builds with </input> tag.
  2. Using the property binding [value]=”value” to keep the view updated when the model is changing.
  3. Using event binding (input)=”updateValue($event.target.value)” to keep model updated when the view is changing. In addition, we emit an event in order to update the host component with the new value.

The Component Class

  1. Using @Input() value: string; to update our view
  2. Using @Output() valueChange = new EventEmitter<string>(); to update our model

So all we have to do, to make the banana in the box work[(value)]=”value” is to add Change suffix to our @Output

Use the Custom Input Component with Two-way data binding 💪

stackblitz example

If you like this article, please 👏

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store