Skip to content

Instantly share code, notes, and snippets.

@Tanapruk
Last active March 18, 2017 17:20
Show Gist options
  • Save Tanapruk/fd9bb8ba24e8dd7d6d76d4e84b3271d7 to your computer and use it in GitHub Desktop.
Save Tanapruk/fd9bb8ba24e8dd7d6d76d4e84b3271d7 to your computer and use it in GitHub Desktop.
Angular2 Shortnotes

Variable Reference from inside HTML Tag. Double bracklets.

{{var}}

Two-way binding. "Banana in a box". All variables that refer to the hero.name will be updated , too.

[()]

[(ngModel)]="hero.name"

from inside:

<input [(ngModel)]="hero.name" placeholder="name">

In comparision, this is one way binding:

value="{{hero.name}}"

<input value="{{hero.name}}" placeholder="name">

Directives

Special Angular HTML element. For example, [(ngModel)]="hero.name"

*ngFor

<li *ngFor="let localHero of heroes">
  <span class="badge">{{localHero.id}}</span> {{localHero.name}}
</li>
  • *ngFor = this class and its children is the master template
  • let localHero of heroes
  • localHero = local variable of heroes array
  • it is similar to this in java
for(Hero localHero: heroes) {
  //do something
}

Event Binding. Parenthesis.

  • (click)=onSelect(hero)
  • (click) is click event
  • onSelect(hero) is a method that this event is binded.

Property Binding. Square Bracklet.

  • [class.selected]="hero === selectedHero"
  • [class.selected] is a property
  • It changes class to [class.selected] when hero === selectedHero
  • hero === selectedHero --> true
  • when its class changes, the property changes accordingly.
<my-hero-detail [hero]="selectedHero"></my-hero-detail>

[hero] is a property binding. This hero variable is assigned with the selectedHero variable.

*ngIf

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
</div>

Hide itself and its child if variable is null. If selectedHero is null. Then don't show div and its sibling.

Attribute Directives

@Input()
hero: Hero;

@Input() to annotate that this variable is passed from another component.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment