Sunday, November 24, 2019

Banana in a box for Angular 1.x code monkeys :)

Two-way databinding, used to be this simple in AngularJS 1.x:

<input ng-model="todo.completed" type="checkbox" />

Angular 2 made the two-way databinding explicit, which can be accomplished by either of the following:

<input [checked]="todo.completed" (input)="todo.completed = $" type="checkbox" />

<input [ngModel]="todo.completed" (ngModelChange)="todo.completed = $event" type="checkbox"/>

Still pining for the old days? You can do Angular 1's terser approach in Angular 2:
<input [(ngModel)]="todo.completed" type="checkbox" />

That's called banana in a box. Just put parenthesis (a.k.a. banana) around ngModel, otherwise it won't work.

It's true, we are code monkeys :)

Using the ngModel approach produces an error if FormsModule is not imported:

Can't bind to 'ngModel' since it isn't a known property of 'input'

To solve that, import FormsModule from "@angular/forms", a good place to import it is from app.module.ts, on entry point of the app.

No comments:

Post a Comment