Angular Cheat Sheet

Lifecycle Hooks

  • OnInit
    export class Component implements OnInit {
        ngOnInit() {}
    }
  • OnChanges
    export class Component implements OnChanges {
        ngOnChanges() {}
    }
  • AfterV­iewInit
    export class Component implements AfterV­iewInit {
        ngAfterViewInit() {}
    }
  • OnDestroy
    export class Component implements OnDestroy {
        ngOnDestroy() {}
    }

Structural Directives

  • *ngIf
    <p *ngIf="expression; else notExpression">
      Expression is true
    </p>
    <ng-template #notExpression>
      <p>
        Expression is false
      </p>
    </ng-template>
  • *ngFor
    <ul>
        <li *ngFor="let element of array"></li>
    </ul>
  • *ngSwitchCase
    <ng-container [ngSwitch]="switch_expression">
        <p *ngSwitchCase="match_expression_1"> 1 </p>
        <p *ngSwitchCase="match_expression_2"> 2 </p>
        <p *ngSwitchDefault> default </p>
    </ng-container>

Class Field Decorators

  • Input
    @Input() myProperty;
  • Output
    @Output() myEvent = new EventEmitter();
  • Host Binding
    @HostBinding('class.error') hasError;
  • Host Listener
    @HostListener('click', ['$event']) onClick(e) {...}
  • Content Child
    @ContentChild(myPredicate) myChildComponent;
  • Content Children
    @ContentChildren(myPredicate) myChildComponents;
  • View Child
    @ViewChild(myPredicate) myChildComponent;
  • View Children
    @ViewChildren(myPredicate) myChildComponents;

Data Binding

  • One Way Binding
    <p>{{ name }}</p>
  • Property Binding
    <input [value]="name" />
  • Attribute Binding
    <button [attr.aria-label]="OK">OK</button>
  • Two Way Binding
    <input [(ngModel)]="name"/>
  • Event Binding
    <input [value]="name" 
           (input)="name = $event.target.value" />

Styling

  • ngStyle
    <p [ngStyle]="{'color': 'blue'}">...</p>
  • ngClass
    <p [ngClass]="'first second'">...</p>
    
    <p [ngClass]="['first', 'second']">...</p>
      
    <p [ngClass]="{'first': true, 'second': false}">...</p>
      
    <p [ngClass]="stringExp|arrayExp|objExp">...</p>
      
    <p [ngClass]="{'class1 class2 class3' : true}">...</p>

Pipes

  • Lowercase
    <p> {{name | lowercase}}</p>
  • Uppercase
    <p> {{name | uppercase}}</p>
  • Date
    <p> {{ today | date: 'medium'}}</p>
  • Date Format
    <p> {{ today | date: 'y-MM­-d'}}</p>
  • Currency
    <p> {{ 3.5 | currency: '€'}}</p>
  • Percent
    <p> {{ 0.5 | percent: '1.2'}}</p>
  • Number
    <p> {{ 0.5 | number: '1.2'}}</p>

Routing

  • Router Outlet
    <router-outlet name="aux"></router-outlet>
  • Router Link
    <a routerLink="/path">
    
    <a [routerLink]="[ '/path', routeParam ]">
    
    <a [routerLink]="[ '/path', 
          { matrixParam: 'value' } ]">
    
    <a [routerLink]="[ '/path' ]" 
         [queryParams]="{ page: 1 }">
    
    <a [routerLink]="[ '/path' ]" 
         fragment="anchor">