티스토리 뷰

https://angular.io/docs/ts/latest/tutorial/toh-pt1.html

https://angular.io/docs/ts/latest/guide/structural-directives.html#!#prefer-asterisk



[]는 template tag 안에서, 그 변수가 있을지 없을지 모르는 상태에서 사용

*는 변수가 존재할때,


The asterisk (*) prefix

Surely you noticed the asterisk (*) prefix to the directive name and wondered why it is necessary and what it does.

Here is *ngIf displaying the hero's name if hero exists.

<div *ngIf="hero" >{{hero.name}}</div>

The asterisk is "syntactic sugar" for something a bit more complicated. Internally, Angular desugars it in two stages. First, it translates the *ngIf="..."into a template attributetemplate="ngIf ...",  like this.

<div template="ngIf hero">{{hero.name}}</div>

Then it translates the template attribute into a template element, wrapped around the host element, like this.

<template [ngIf]="hero">
  <div>{{hero.name}}</div>
</template>
  • The *ngIf directive moved to the <template> element where it became a property binding,[ngIf].
  • The rest of the <div>, including its class attribute, moved inside the <template> element.

None of these forms are actually rendered. Only the finished product ends up in the DOM.

hero div in DOM

Angular consumed the <template> content during its actual rendering and replaced the <template> with a diagnostic comment.

The NgFor and NgSwitch... directives follow the same pattern.

Inside *ngFor

Angular transforms the *ngFor in similar fashion from asterisk (*) syntax through template attribute to template element.

Here's a full-featured application of NgFor, written all three ways:

<div *ngFor="let hero of heroes; let i=index; let odd=odd; trackBy: trackById" [class.odd]="odd">
  ({{i}}) {{hero.name}}
</div>

<div template="ngFor let hero of heroes; let i=index; let odd=odd; trackBy: trackById" [class.odd]="odd">
  ({{i}}) {{hero.name}}
</div>

<template ngFor let-hero [ngForOf]="heroes" let-i="index" let-odd="odd" [ngForTrackBy]="trackById">
  <div [class.odd]="odd">({{i}}) {{hero.name}}</div>
</template>

This is manifestly more complicated than ngIf and rightly so. The NgFor directive has more features, both required and optional, than the NgIf shown in this guide. At minimum NgFor needs a looping variable (let hero) and a list (heroes).

You enable these features in the string assigned to ngFor, which you write in Angular's microsyntax.

Everything outside the ngFor string stays with the host element (the <div>) as it moves inside the <template>. In this example, the [ngClass]="odd" stays on the <div>.



'AngularJS 2.0 > + ANgularJS 2.0' 카테고리의 다른 글

AngularJS Route / canActivate  (0) 2018.02.28
Angular의 ngFor를 사용할때 구분자 넣기  (0) 2017.08.02
AngularJS에서 *가 의미하는 것  (0) 2017.03.24
angular 4  (0) 2016.12.12
Angular Release Breaking Changes  (0) 2016.11.07
Angular Spring MVC  (0) 2016.10.07
댓글
댓글쓰기 폼