Angular2 Intro

Overview

Breaking Changes

  • $scope is dead
  • Controller is dead
  • zones
  • DI
  • Simple API
  • service/factory/constant/value/provider

Main Concepts

  • Module
  • Component
  • Template
  • Metadata
  • Data Binding
  • Directive

Module

  • angular2 apps are modular
  • many modules
  • single purpose
  • optional
// app.component.ts
export class AppComponent { }
// main.ts
import {AppComponent} from './app.component';
import {Component} from 'angular2/core';

The Component

  • Everything is a directive

  • Main building block

  • mediator, expose data to its view

  • handle user interactions

  • reusable

// hero-list.component.ts

export class HeroListComponent implements OnInit {
     
  constructor(_service: HeroService){ }
  
  heroes:Hero[];
  selectedHero: Hero;

  ngOnInit(){
    this.heroes = this._service.getHeroes();
  }

  selectHero(hero: Hero) { this.selectedHero = hero; }
}

Template

  • combined with a component

  • complex component trees

<h2>Hero List</h2>
<p><i>Pick a hero from the list</i></p>

<div *ngFor="#hero of heroes" (click)="selectHero(hero)">
  {{hero.name}}
</div>

<button [disabled]="isUnchanged">Save</button>

<hero-detail *ngIf="selectedHero" [hero]="selectedHero"></hero-detail>

<video-player #player></video-player>
<button (click)="player.pause()">Pause</button>

Some More Examples

Metadata

  • tells Angular how to process a class

// hero-list.component.ts
import {Component} from 'angular2/core';

@Component({
  selector:    'hero-list',
  templateUrl: 'app/hero-list.component.html',
  directives:  [HeroDetailComponent],
  providers:   [HeroService]
})
export class HeroListComponent { ... }

// hero.service.ts

import {Injectable} from 'angular2/core';
import {HEROES}     from './mock-heroes';
import {Logger}     from '../logger.service';

@Injectable()
export class HeroService {
  constructor(private _logger: Logger) {  }
  getHeroes() {
    this._logger.log('Getting heroes ...')
    return HEROES;
  }
}

Data Binding

  • four forms of data binding syntax

// hero-list.component.html

<div>{{hero.name}}</div>
<hero-detail [hero]="selectedHero"></hero-detail>
<div (click)="selectHero(hero)"></div>
<input [(ngModel)]="hero.name">

Directive

  • Dynamic templates

  • Three types of directives

  • Structural directives alter layout by adding, removing, and replacing elements in DOM

  • Attribute directives alter the appearance or behavior of an existing element


// structural directive

<div *ngFor="#hero of heroes"></div>

// attribute directive

<div [ngClass]="setClasses()"></div>

// custom directive

@Directive({
    selector: "[log-on-click]",
    hostListeners: {
        'click': 'onClick()'
    }
})
class LogOnClick {

    constructor() {}

    onClick() { console.log('Element clicked!'); }
}

<button log-on-click>I log when clicked!</button>

Further Reading

angular2

By Ben Bakhar

angular2

  • 1,178