Angular Cheat Sheet

Some common ngCode that I always seem to be looking up....

Looping In Angular

Create your item/object/list to loop over in the component....
//test.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  constructor() { }
  ngOnInit() { }
  
  courses = [
      {id:1, name: 'course1'},
      {id:2, name: 'course2'},
      {id:3, name: 'course3'}
  ];
  
}
... in your HTML use 'let index of listname', data binding occurs on {{course}}....
<!--test.component.html-->
<ul>
    <li *ngFor="let course of courses">
        {{course}}
    </li>
</ul>

Services In Angular

Basic syntax for declaring, calling and injecting a service using dependency injection.
//services
//courses.service.ts
//Remember there is no decorator for a service; it's just a plain Typescript class!
/*Also, don't forget to add a reference to this service in this component's module, 
under providers*/
export class CoursesService{
    getCourses() {
        return ["course 1","course 2", "course 3"];
    }
}

//courses.component.ts
export class CoursesComponent {
    title = "My Courses";

    constructor(service:CoursesService){
        this.courses = service.getCourses();
    }
}

Class Binding

//in component
    export class CoursesComponent {
        isActive="true";
    }
<!--in html template-->
<button class="btn btn-primary" [class.isActive]="isActive">Save</button>

Style Binding

//in component
    export class CoursesComponent {
        isActive="true";
    }
<!--in html template-->
<button class="btn btn-primary" [style.backgroundColor]="isActive ? 'blue' : 'white'">
Save</button>

Event Binding

//in component
    export class CoursesComponent {
        onSave($event){
            console.log("button was clicked!")
        }
    }
<!--in html template-->
<button (click)="onSave($event)">Save</button>

Event Bubbling (Propagation)

//event bubbling (event propagation)
An event bubbles up the DOM tree until the event hits the target handler. 
How can you stop it? 
onSave(){
    $event.stopPropagation();
    console.log("Here is my event");
}

2 Way Data Binding [(ngModel)] "banana in a box"

//in component
//(import FormsModule from @angular/forms in app.module.ts)
export class CoursesComponent {
    email = "me@example.com";
    onKeyUp(){
        console.log("this.email")
    }
}
<!--in html template-->
<input [(ngModel)]="email" (keyup.enter)="onKeyUp()" />

Input Properties

//in favorite.component.ts
import {Component, OnInit, Input} from '@angular/core';
@component({
    selector: 'favorite',
    templateUrl: './favorite.component.html',
    styleUrls: ['./favorite.component.css']
})

export class FavoriteComponent implements OnInit {
    @Input('isFavorite') isSelected:boolean; //isFavorite is an alias (used in app.component.html) so you can rename 'isSelected' 
    //whatever and the contract of the component (API) will continue to work
    
    constructor (){} 
    
    ngOnInit() {}
    
    onClick() {
    this.isSelected = !this.isSelected;
    }    
}
//in app.component.ts
import {Component} from '@angular/core';
@component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent {
    post ={
    title: "Title",
    isFavorite: true
    } 
}
<!--in app.component.html template-->
<favorite [isFavorite]="post.isFavorite"></isFavorite>
<!--in favorite.component.html template-->
<span
    class="glyphicon"
    [class.glyphicon-star]="isFavorite"
    [class.glyphicon-star-empty]="!isFavorite"
    (click)="onClick()"></span>

ngContent - Make components reusable

<!--in panel.component.html template-->
<div class="panel panel-default">
    <div class="panel-heading">
        <ng-content select=".heading"></ng-content>
    </div>
    <div class="panel-body">
        <ng-content select=".body"></ng-content>
    </div>
</div>
<!--in app.component.html template-->
//make sure to use the same class name in your content as is defined 
//in the select attribute of the ng-content tag
<bootstrap-panel>
    <div class="heading">Heading to be injected</div>
    <div class="body">
        <h2>body</h2>
        <p>Some content here (which will get injected)</p>
    </div>
</bootstrap-panel>

HTTP Services

<!--in posts.component.ts template-->
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})

export class PostsComponent implements OnInit {

    posts=: any[];
    
    constructor(private http:Http) { };

    ngOnInit() {
        this.http.get('http://jsonplaceholder.typicode.com/posts').
        subscribe(response => {
        this.posts=response.json();
      }
}
<!--in posts.component.html template-->
<ul>
    <li *ngFor='post of posts'>
        {{posts.title}}
    </li>
</ul>

Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/angular2/angular-cheat-sheet/