George Huang
George Huang

Reputation: 2523

AngularJs 2.0 built-in components - How to use them correctly

Angular 2 provides a number of built-in components. Such as NgIf, NgFor, NgStyle, NgNonBindable.... Some of the components were used with an '*', such as *ngIf and *ngFor:

<div *ngFor="item of items">
   {{item}}
</div>

Some of them were used with '[]', such as [ngStyle] and [ngClass]: (Component inputs?)

<div [ngStyle]="{'background-color': 'yellow'}">Content</div>

And some were used like 'Angular-1': for example:

<div ngNonBindable>
   Angular code snippet: {{content}}
</div>

Does anyone here know why? and what's the differences? How do I remember the way to use them correctly?

Upvotes: 0

Views: 308

Answers (2)

Zachary Scott
Zachary Scott

Reputation: 21172

Just for fun, these are all equivalent:

{{ expression }}              
[target] = "expression"       
bind-target = "expression"

{{ expression }} is interpolation and one way binding
[ expression ] is also one way binding
( event ) is for events like (click)

[(ngModel)] is for two way binding that is the same as this:

<input type="text" 
       [value] = "character.name"
       (input) = "character.name = $event.target.value />

*ngFor and *ngIf are Structural Directives, the * denotes changing the DOM

Upvotes: 0

Nikola Nikolov
Nikola Nikolov

Reputation: 1310

The Angular 2 directives which cause some kind of change to the DOM like ngIf for conditionally added/removed blocks or ngFor - for repeated ones are marked with asterisk "*".

ngStyle and ngClass are used with "[]" because this causes a one way data binding to the desired property of the element with the passed value.

Some of the directives like ngNonBindable are used in Angular 1 style because theirs using don't require data binding to surround them with "[]" or banana in box syntax "[()]" (two way data binding), but provide information for the Angular core about the current element.

Upvotes: 2

Related Questions