Thursday, April 19, 2018

Angular - Property and Event Bindings

Binding with Interpolation

Use {{expression}} to pull (only one way binding) in content from the component class. The expression can have many forms.

For example:
{{propertyName}}
{{'ABC' + functionName()}}
{{'Answer is ' + 3*2}}
{{showImage ? 'Hide' : 'Show'}} Image

<img src={{product.imageUrl}}>

Notice that it does not use quotes!

Property Binding

Property Binding is one way just like interpolation.

We could use interpolation to set the src url for an image using:

<img src={{product.imageUrl}}>

or 

<img src='http://someUrl/{{product.imageUrl}}'>

We can use Property binding to do the first case, but not the second case.

<img [src]='product.imageUrl'>

The syntax for Property Binding has a two parts:
  • Binding Target - Is always in surrounded by []
  • Binding Source - Is Surrounded by '' (two single quotes).
Generally, Property Binding is preferred instead of interpolation.

Event Binding

When the user clicks something an event is generated. We can listen for these events using Event Binding. Here is the syntax.

<button (click)='doSomething()'>

The syntax for Property Binding has a two parts:
  • Target Event - Is always in surrounded by ()
  • Template Statement - Is Surrounded by '' (two single quotes).
In this example, when the button is clicked the doSomething() method in our component class is executed.


Two-way Binding

This is useful for having the component and dom in sync such as in the case of an input field on a form.

<input [(ngModel)]='someProperty'>

The Banana in a Box metaphor can be used to remember the order of the parenthesis. Imagine the [()] to have a banana as () in a box as [].

The class for the component would be something like this.
export class MyComponent {
    someProperty: string = 'abc';
}

ngModel is a keyword defined in the FormsModule. The FormsModule will need to be added to the AppModule. To do this open your app.module.ts and add to the top of the file the following:

import { FormsModule } from '@angular/forms';

Next, in the same app.module.ts file add FormsModule to the array of imports in the @NgModule().


No comments: