Skip to content

Instantly share code, notes, and snippets.

@viztastic
Last active October 10, 2016 03:15
Show Gist options
  • Save viztastic/12391396593a9d67effac0b39eeee2a5 to your computer and use it in GitHub Desktop.
Save viztastic/12391396593a9d67effac0b39eeee2a5 to your computer and use it in GitHub Desktop.

Bindings

<input type="text" [(ngModel)] = "componentPropertyName" placeholder="name">

The [(ngModel)] basically means that if I update the textbox, it will update the target variable (in this case componentPropertyName) and reflect it back in the screen.

Looping

<li *ngFor="let item of items">

The (*) prefix to ngFor indicates that the <li> element and its children constitute a master template.

Bindings

Event Binding

<li (click)="methodName(componentPropertyName)">

The parenthesis identify the <li> element’s click event as the target. The expression to the right of the equal sign calls the AppComponent method, methodName(), passing the template input variable hero as an argument. That’s the same hero variable we defined previously in the ngFor

Property Binding

<li [class.selected]="hero === selectedHero">Hi</li>

Notice in the template that the class.selected is surrounded in square brackets ([]). This is the syntax for a property binding, a binding in which data flows one way from the data source (the expression hero === selectedHero) to a property of class.


The HeroDetailComponent must be told what hero to display. Who will tell it? The parent AppComponent!

The AppComponent knows which hero to show: the hero that the user selected from the list. The user's selection is in its selectedHero property.

<my-hero-detail [hero]="selectedHero"></my-hero-detail>

Notice that the hero property is the target of a property binding — it's in square brackets to the left of the (=).

Angular insists that we declare a target property to be an input property. If we don't, Angular rejects the binding and throws an error.

In order to tell the my-hero-detal component that the hero variable is an input property, we simply annotate her with @Input, like so:

export class AppDetailComponent {
  
  @Input()
  hero: Hero;
}

Conditionals

<div *ngIf="variableOrCondition">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment