Custom Angular Component Using Two-Way Data Binding AKA “BANANA IN A BOX” = [🍌] Syntax
Standard Angular Two Way Data Binding is by using the
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
What is “BANANA IN A BOX” [🍌]
Banana in a box it just a template syntax for Two-Way Data Binding
and it combines the property binding and the event binding.
So instead of writing it explicitly:
<my-input [text]="val" (textChange)="val=$event"></my-input>
We can leverage the shortened syntax:
Why is it named “BANANA IN A BOX”?
The naming assists us in remembering the order of the brackets of the Two-Way Data Binding.
-  = box
- () = banana.
- [()] = banana in a box 😃
Build the Custom Input Component
Let's break down the above custom input component:
- The template builds with
- Using the property binding
[value]=”value”to keep the view updated when the model is changing.
- 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
@Input() value: string;to update our view
@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
Use the Custom Input Component with Two-way data binding 💪
Now we can use it in our parent component like this:
If you like this article, please 👏