docs(ngmodule): add chapter

This commit is contained in:
Ward Bell 2016-07-12 18:14:13 -07:00 committed by Naomi Black
parent fe35bc6c31
commit aef8aa94aa
78 changed files with 3355 additions and 6 deletions

View File

@ -0,0 +1,220 @@
/// <reference path='../_protractor/e2e.d.ts' />
'use strict';
describe('NgModule', function () {
// helpers
const gold = 'rgba(255, 215, 0, 1)';
const powderblue = 'rgba(176, 224, 230, 1)';
const lightgray = 'rgba(211, 211, 211, 1)';
function getCommonsSectionStruct() {
const buttons = element.all(by.css('nav a'));
return {
title: element.all(by.tagName('h1')).get(0),
subtitle: element.all(by.css('app-title p i')).get(0),
contactButton: buttons.get(0),
crisisButton: buttons.get(1),
heroesButton: buttons.get(2)
};
}
function getContactSectionStruct() {
const buttons = element.all(by.css('app-contact form button'));
return {
header: element.all(by.css('app-contact h2')).get(0),
popupMessage: element.all(by.css('app-contact div')).get(0),
contactNameHeader: element.all(by.css('app-contact form h3')).get(0),
input: element.all(by.css('app-contact form input')).get(0),
validationError: element.all(by.css('app-contact form .alert')).get(0),
saveButton: buttons.get(0), // can't be tested
nextContactButton: buttons.get(1),
newContactButton: buttons.get(2)
};
}
function getCrisisSectionStruct() {
return {
title: element.all(by.css('ng-component h3')).get(0),
items: element.all(by.css('ng-component a')),
itemId: element.all(by.css('ng-component div')).get(0),
listLink: element.all(by.css('ng-component a')).get(0),
};
}
function getHeroesSectionStruct() {
return {
header: element.all(by.css('ng-component h2')).get(0),
title: element.all(by.css('ng-component h3')).get(0),
items: element.all(by.css('ng-component a')),
itemId: element.all(by.css('ng-component ng-component div div')).get(0),
itemInput: element.all(by.css('ng-component ng-component input')).get(0),
listLink: element.all(by.css('ng-component ng-component a')).get(0),
};
}
// tests
function appTitleTests(color: string) {
return function() {
it('should have a gray header', function() {
const commons = getCommonsSectionStruct();
expect(commons.title.getCssValue('backgroundColor')).toBe(color);
});
it('should welcome us', function () {
const commons = getCommonsSectionStruct();
expect(commons.subtitle.getText()).toBe('Welcome, Sam Spade');
});
};
}
function contactTests(color: string) {
return function() {
it('shows the contact\'s owner', function() {
const contacts = getContactSectionStruct();
expect(contacts.header.getText()).toBe('Contact of Sam Spade');
});
it('can cycle between contacts', function () {
const contacts = getContactSectionStruct();
const nextButton = contacts.nextContactButton;
expect(contacts.contactNameHeader.getText()).toBe('Awesome Sam Spade');
expect(contacts.contactNameHeader.getCssValue('backgroundColor')).toBe(color);
nextButton.click().then(function () {
expect(contacts.contactNameHeader.getText()).toBe('Awesome Nick Danger');
return nextButton.click();
}).then(function () {
expect(contacts.contactNameHeader.getText()).toBe('Awesome Nancy Drew');
});
});
it('can change an existing contact', function () {
const contacts = getContactSectionStruct();
contacts.input.sendKeys('a');
expect(contacts.input.getCssValue('backgroundColor')).toBe(color);
expect(contacts.contactNameHeader.getText()).toBe('Awesome Sam Spadea');
});
it('can create a new contact', function () {
const contacts = getContactSectionStruct();
const newContactButton = contacts.newContactButton;
newContactButton.click().then(function () {
expect(contacts.validationError.getText()).toBe('Name is required');
contacts.input.sendKeys('John Doe');
expect(contacts.contactNameHeader.getText()).toBe('Awesome John Doe');
expect(contacts.validationError.getText()).toBe('');
});
});
};
}
describe('index.html', function () {
beforeEach(function () {
browser.get('');
});
describe('app-title', appTitleTests(lightgray));
describe('contact', contactTests(lightgray));
describe('crisis center', function () {
beforeEach(function () {
getCommonsSectionStruct().crisisButton.click();
});
it('shows a list of crisis', function () {
const crisis = getCrisisSectionStruct();
expect(crisis.title.getText()).toBe('Crisis List');
expect(crisis.items.count()).toBe(4);
expect(crisis.items.get(0).getText()).toBe('1 - Dragon Burning Cities');
});
it('can navigate to one crisis details', function () {
const crisis = getCrisisSectionStruct();
crisis.items.get(0).click().then(function() {
expect(crisis.itemId.getText()).toBe('Crisis id: 1');
return crisis.listLink.click();
}).then(function () {
// We are back to the list
expect(crisis.items.count()).toBe(4);
});
});
});
describe('heroes', function () {
beforeEach(function () {
getCommonsSectionStruct().heroesButton.click();
});
it('shows a list of heroes', function() {
const heroes = getHeroesSectionStruct();
expect(heroes.header.getText()).toBe('Heroes of Sam Spade');
expect(heroes.title.getText()).toBe('Hero List');
expect(heroes.items.count()).toBe(6);
expect(heroes.items.get(0).getText()).toBe('11 - Mr. Nice');
});
it('can navigate and edit one hero details', function () {
const heroes = getHeroesSectionStruct();
heroes.items.get(0).click().then(function () {
expect(heroes.itemId.getText()).toBe('Id: 11');
heroes.itemInput.sendKeys(' try');
return heroes.listLink.click();
}).then(function () {
// We are back to the list
expect(heroes.items.count()).toBe(6);
expect(heroes.items.get(0).getText()).toBe('11 - Mr. Nice try');
});
});
});
});
describe('index.0.html', function() {
beforeEach(function () {
browser.get('index.0.html');
});
it('has a title', function () {
const title = element.all(by.tagName('h1')).get(0);
expect(title.getText()).toBe('Minimal NgModule');
});
});
describe('index.1.html', function () {
beforeEach(function () {
browser.get('index.1.html');
});
describe('app-title', appTitleTests(powderblue));
});
describe('index.1b.html', function () {
beforeEach(function () {
browser.get('index.1b.html');
});
describe('app-title', appTitleTests(powderblue));
describe('contact', contactTests(powderblue));
});
describe('index.2.html', function () {
beforeEach(function () {
browser.get('index.2.html');
});
describe('app-title', appTitleTests(gold));
describe('contact', contactTests(powderblue));
});
describe('index.3.html', function () {
beforeEach(function () {
browser.get('index.3.html');
});
describe('app-title', appTitleTests(gold));
});
});

View File

@ -0,0 +1,10 @@
// #docregion
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<h1>{{title}}</h1>',
})
export class AppComponent {
title = 'Minimal NgModule';
}

View File

@ -0,0 +1,19 @@
// #docplaster
// #docregion
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
// #enddocregion
/*
// #docregion template
template: '<h1 highlight>{{title}}</h1>'
// #enddocregion template
*/
// #docregion
template: '<app-title [subtitle]="subtitle"></app-title>'
})
export class AppComponent {
subtitle = '(v1)';
}
// #enddocregion

View File

@ -0,0 +1,15 @@
// #docregion
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
// #docregion template
template: `
<app-title [subtitle]="subtitle"></app-title>
<app-contact></app-contact>
`
// #enddocregion template
})
export class AppComponent {
subtitle = '(v1)';
}

View File

@ -0,0 +1,12 @@
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<app-title [subtitle]="subtitle"></app-title>
<app-contact></app-contact>
`
})
export class AppComponent {
subtitle = '(v2)';
}

View File

@ -0,0 +1,19 @@
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
// #docregion template
template: `
<app-title [subtitle]="subtitle"></app-title>
<nav>
<a routerLink="contact" routerLinkActive="active">Contact</a>
<a routerLink="crisis" routerLinkActive="active">Crisis Center</a>
<a routerLink="heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>
`
// #enddocregion template
})
export class AppComponent {
subtitle = '(v3)';
}

View File

@ -0,0 +1,19 @@
// #docplaster
// #docregion
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<app-title [subtitle]="subtitle"></app-title>
<nav>
<a routerLink="contact" routerLinkActive="active">Contact</a>
<a routerLink="crisis" routerLinkActive="active">Crisis Center</a>
<a routerLink="heroes" routerLinkActive="active">Heroes</a>
</nav>
<router-outlet></router-outlet>
`
})
export class AppComponent {
subtitle = '(Final)';
}

View File

@ -0,0 +1,23 @@
// #docplaster
// #docregion
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import
// #enddocregion
{ AppComponent } from './app.component.0';
/*
// #docregion
{ AppComponent } from './app.component';
// #enddocregion
*/
// #docregion
@NgModule({
// #docregion imports
imports: [ BrowserModule ],
// #enddocregion imports
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

View File

@ -0,0 +1,54 @@
// #docplaster
// #docregion
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import
// #enddocregion
{ AppComponent } from './app.component.1';
/*
// #docregion
{ AppComponent } from './app.component';
// #enddocregion
*/
// #docregion
import { HighlightDirective } from './highlight.directive';
import { TitleComponent } from './title.component';
import { UserService } from './user.service';
/* Contact Related Imports */
import { FormsModule } from '@angular/forms';
import { AwesomePipe } from './contact/awesome.pipe';
import { ContactComponent } from './contact/contact.component.3';
// #docregion import-contact-directive
import {
HighlightDirective as ContactHighlightDirective
} from './contact/highlight.directive';
// #enddocregion import-contact-directive
@NgModule({
// #docregion imports
imports: [ BrowserModule, FormsModule ],
// #enddocregion imports
// #docregion declarations, directive, component
declarations: [
AppComponent,
HighlightDirective,
// #enddocregion directive
TitleComponent,
// #enddocregion component
AwesomePipe,
ContactComponent,
ContactHighlightDirective
// #docregion declarations, directive, component
],
// #enddocregion declarations, directive, component
// #docregion providers
providers: [ UserService ],
// #enddocregion providers
bootstrap: [ AppComponent ]
})
export class AppModule { }

View File

@ -0,0 +1,53 @@
// #docplaster
// #docregion
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
/* App Root */
import
// #enddocregion
{ AppComponent } from './app.component.1b';
/*
// #docregion
{ AppComponent } from './app.component';
// #enddocregion
*/
// #docregion
import { HighlightDirective } from './highlight.directive';
import { TitleComponent } from './title.component';
import { UserService } from './user.service';
/* Contact Imports */
import
// #enddocregion
{ ContactComponent } from './contact/contact.component.3';
/*
// #docregion
{ ContactComponent } from './contact/contact.component';
// #enddocregion
*/
// #docregion
import { ContactService } from './contact/contact.service';
import { AwesomePipe } from './contact/awesome.pipe';
// #docregion import-alias
import {
HighlightDirective as ContactHighlightDirective
} from './contact/highlight.directive';
// #enddocregion import-alias
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [ BrowserModule, FormsModule ],
// #docregion declarations
declarations: [
AppComponent, HighlightDirective, TitleComponent,
AwesomePipe, ContactComponent, ContactHighlightDirective
],
// #docregion providers
providers: [ ContactService, UserService ],
// #enddocregion providers
bootstrap: [ AppComponent ]
})
export class AppModule { }

View File

@ -0,0 +1,37 @@
// #docplaster
// #docregion
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
/* App Root */
import
// #enddocregion
{ AppComponent } from './app.component.2';
/*
// #docregion
{ AppComponent } from './app.component';
// #enddocregion
*/
// #docregion
import { HighlightDirective } from './highlight.directive';
import { TitleComponent } from './title.component';
import { UserService } from './user.service';
/* Contact Imports */
import
// #enddocregion
{ ContactModule } from './contact/contact.module.2';
/*
// #docregion
{ ContactModule } from './contact/contact.module';
// #enddocregion
*/
// #docregion
@NgModule({
imports: [ BrowserModule, ContactModule ],
declarations: [ AppComponent, HighlightDirective, TitleComponent ],
providers: [ UserService ],
bootstrap: [ AppComponent ],
})
export class AppModule { }

View File

@ -0,0 +1,31 @@
// #docplaster
// #docregion
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
/* App Root */
import { AppComponent } from './app.component.3';
import { HighlightDirective } from './highlight.directive';
import { TitleComponent } from './title.component';
import { UserService } from './user.service';
/* Feature Modules */
import { ContactModule } from './contact/contact.module.3';
import { routing } from './app.routing.3';
@NgModule({
// #docregion imports
imports: [
BrowserModule,
ContactModule,
routing
],
// #enddocregion imports
declarations: [ AppComponent, HighlightDirective, TitleComponent ],
providers: [ UserService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

View File

@ -0,0 +1,29 @@
// #docplaster
// #docregion
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
/* App Root */
import { AppComponent } from './app.component';
/* Feature Modules */
import { ContactModule } from './contact/contact.module';
import { SharedModule } from './shared/shared.module';
import { routing } from './app.routing';
@NgModule({
imports: [
BrowserModule,
ContactModule,
routing,
SharedModule.forRoot()
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

View File

@ -0,0 +1,10 @@
import { Routes,
RouterModule } from '@angular/router';
export const routes: Routes = [
{ path: '', redirectTo: 'contact', pathMatch: 'full'},
{ path: 'crisis', loadChildren: 'app/crisis/crisis.module' },
{ path: 'heroes', loadChildren: 'app/hero/hero.module.3' }
];
export const routing = RouterModule.forRoot(routes);

View File

@ -0,0 +1,15 @@
// #docregion
import { Routes,
RouterModule } from '@angular/router';
export const routes: Routes = [
{ path: '', redirectTo: 'contact', pathMatch: 'full'},
// #docregion lazy-routes
{ path: 'crisis', loadChildren: 'app/crisis/crisis.module' },
{ path: 'heroes', loadChildren: 'app/hero/hero.module' }
// #enddocregion lazy-routes
];
// #docregion forRoot
export const routing = RouterModule.forRoot(routes);
// #enddocregion forRoot

View File

@ -0,0 +1,10 @@
// #docregion
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'awesome' })
/** Precede the input string with the word "Awesome " */
export class AwesomePipe implements PipeTransform {
transform(phrase: string) {
return phrase ? 'Awesome ' + phrase : '';
}
}

View File

@ -0,0 +1,54 @@
// #docregion
import { Component, OnInit } from '@angular/core';
import { Contact, ContactService } from './contact.service';
import { UserService } from '../user.service';
@Component({
moduleId: module.id,
selector: 'app-contact',
templateUrl: 'contact.component.html',
styleUrls: ['contact.component.css']
})
export class ContactComponent implements OnInit {
contact: Contact;
contacts: Contact[];
msg = 'Loading contacts ...';
userName = '';
constructor(private contactService: ContactService, userService: UserService) {
this.userName = userService.userName;
}
ngOnInit() {
this.contactService.getContacts().then(contacts => {
this.msg = '';
this.contacts = contacts;
this.contact = contacts[0];
});
}
next() {
let ix = 1 + this.contacts.indexOf(this.contact);
if (ix >= this.contacts.length) { ix = 0; }
this.contact = this.contacts[ix];
}
onSubmit() {
// TODO: do something like save it
this.displayMessage('Saved ' + this.contact.name);
}
newContact() {
this.displayMessage('New contact');
this.contact = {id: 42, name: ''};
this.contacts.push(this.contact);
}
/** Display a message briefly, then remove it. */
displayMessage(msg: string) {
this.msg = msg;
setTimeout(() => this.msg = '', 1500);
}
}

View File

@ -0,0 +1,29 @@
/* #docregion */
.ng-valid[required] {
border-left: 5px solid #42A948; /* green */
}
.ng-invalid {
border-left: 5px solid #a94442; /* red */
}
.alert {
padding: 15px;
margin: 8px 0;
border: 1px solid transparent;
border-radius: 4px;
}
.alert-danger {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.msg {
color: blue;
background-color: whitesmoke;
border: 1px solid transparent;
border-radius: 4px;
margin-bottom: 20px;
}

View File

@ -0,0 +1,23 @@
<!-- #docregion -->
<h2>Contact of {{userName}}</h2>
<div *ngIf="msg" class="msg">{{msg}}</div>
<form *ngIf="contacts" (ngSubmit)="onSubmit()" #contactForm="ngForm">
<!-- #docregion awesome -->
<h3 highlight>{{ contact.name | awesome }}</h3>
<!-- #enddocregion awesome -->
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" required
[(ngModel)]="contact.name"
name="name" #name="ngModel" >
<div [hidden]="name.valid" class="alert alert-danger">
Name is required
</div>
</div>
<br>
<button type="submit" class="btn btn-default" [disabled]="!contactForm.form.valid">Save</button>
<button type="button" class="btn" (click)="next()" [disabled]="!contactForm.form.valid">Next Contact</button>
<button type="button" class="btn" (click)="newContact()">New Contact</button>
</form>
<!-- #enddocregion -->

View File

@ -0,0 +1,55 @@
// Exact copy except import UserService from shared
// #docregion
import { Component, OnInit } from '@angular/core';
import { Contact, ContactService } from './contact.service';
import { UserService } from '../shared/user.service';
@Component({
moduleId: module.id,
selector: 'app-contact',
templateUrl: 'contact.component.html',
styleUrls: ['contact.component.css']
})
export class ContactComponent implements OnInit {
contact: Contact;
contacts: Contact[];
msg = 'Loading contacts ...';
userName = '';
constructor(private contactService: ContactService, userService: UserService) {
this.userName = userService.userName;
}
ngOnInit() {
this.contactService.getContacts().then(contacts => {
this.msg = '';
this.contacts = contacts;
this.contact = contacts[0];
});
}
next() {
let ix = 1 + this.contacts.indexOf(this.contact);
if (ix >= this.contacts.length) { ix = 0; }
this.contact = this.contacts[ix];
}
onSubmit() {
// TODO: do something like save it
this.displayMessage('Saved ' + this.contact.name);
}
newContact() {
this.displayMessage('New contact');
this.contact = {id: 42, name: ''};
this.contacts.push(this.contact);
}
/** Display a message briefly, then remove it. */
displayMessage(msg: string) {
this.msg = msg;
setTimeout(() => this.msg = '', 1500);
}
}

View File

@ -0,0 +1,30 @@
// #docplaster
// #docregion
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AwesomePipe } from './awesome.pipe';
import
// #enddocregion
{ ContactComponent } from './contact.component.3';
/*
// #docregion
{ ContactComponent } from './contact.component';
// #enddocregion
*/
// #docregion
import { ContactService } from './contact.service';
import { HighlightDirective } from './highlight.directive';
// #docregion class
@NgModule({
imports: [ CommonModule, FormsModule ],
declarations: [ ContactComponent, HighlightDirective, AwesomePipe ],
exports: [ ContactComponent ],
providers: [ ContactService ]
})
export class ContactModule { }
// #enddocregion class
// #enddocregion

View File

@ -0,0 +1,23 @@
// #docregion
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AwesomePipe } from './awesome.pipe';
import { ContactComponent } from './contact.component.3';
import { ContactService } from './contact.service';
import { HighlightDirective } from './highlight.directive';
import { routing } from './contact.routing.3';
// #docregion class
@NgModule({
imports: [ CommonModule, FormsModule, routing ],
declarations: [ ContactComponent, HighlightDirective, AwesomePipe ],
providers: [ ContactService ]
})
export class ContactModule { }
// #enddocregion class
// #enddocregion

View File

@ -0,0 +1,16 @@
// #docregion
import { NgModule } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { ContactComponent } from './contact.component';
import { ContactService } from './contact.service';
import { routing } from './contact.routing';
// #docregion class
@NgModule({
imports: [ SharedModule, routing ],
declarations: [ ContactComponent ],
providers: [ ContactService ]
})
export class ContactModule { }
// #enddocregion class

View File

@ -0,0 +1,7 @@
import { RouterModule } from '@angular/router';
import { ContactComponent } from './contact.component.3';
export const routing = RouterModule.forChild([
{ path: 'contact', component: ContactComponent}
]);

View File

@ -0,0 +1,9 @@
import { RouterModule } from '@angular/router';
import { ContactComponent } from './contact.component';
// #docregion routing
export const routing = RouterModule.forChild([
{ path: 'contact', component: ContactComponent}
]);
// #enddocregion

View File

@ -0,0 +1,29 @@
// #docregion
import { Injectable } from '@angular/core';
export class Contact {
constructor(public id: number, public name: string) { }
}
const CONTACTS: Contact[] = [
new Contact(21, 'Sam Spade'),
new Contact(22, 'Nick Danger'),
new Contact(23, 'Nancy Drew')
];
const FETCH_LATENCY = 500;
@Injectable()
export class ContactService {
getContacts() {
return new Promise<Contact[]>(resolve => {
setTimeout(() => { resolve(CONTACTS); }, FETCH_LATENCY);
});
}
getContact(id: number | string) {
return this.getContacts()
.then(heroes => heroes.find(hero => hero.id === +id));
}
}

View File

@ -0,0 +1,18 @@
/* tslint:disable */
// Same directive name and selector as
// HighlightDirective in parent AppModule
// It selects for both input boxes and 'highlight' attr
// and it highlights in blue instead of gold
// #docregion
import { Directive, ElementRef, Renderer } from '@angular/core';
@Directive({ selector: '[highlight], input' })
/** Highlight the attached element or an InputElement in blue */
export class HighlightDirective {
constructor(renderer: Renderer, el: ElementRef) {
renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'powderblue');
console.log(
`* Contact highlight called for ${el.nativeElement.tagName}`);
}
}

View File

@ -0,0 +1,19 @@
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
template: `
<h3 highlight>Crisis Detail</h3>
<div>Crisis id: {{id}}</div>
<br>
<a routerLink="../list">Crisis List</a>
`
})
export class CrisisDetailComponent implements OnInit {
id: number;
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.id = parseInt(this.route.snapshot.params['id'], 10);
}
}

View File

@ -0,0 +1,22 @@
import { Component, OnInit } from '@angular/core';
import { Crisis,
CrisisService } from './crisis.service';
@Component({
template: `
<h3 highlight>Crisis List</h3>
<div *ngFor='let crisis of crisises | async'>
<a routerLink="{{'../' + crisis.id}}">{{crisis.id}} - {{crisis.name}}</a>
</div>
`
})
export class CrisisListComponent implements OnInit {
crisises: Promise<Crisis[]>;
constructor(private crisisService: CrisisService) { }
ngOnInit() {
this.crisises = this.crisisService.getCrises();
}
}

View File

@ -0,0 +1,16 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CrisisListComponent } from './crisis-list.component';
import { CrisisDetailComponent } from './crisis-detail.component';
import { CrisisService } from './crisis.service';
import { routing } from './crisis.routing';
@NgModule({
imports: [ CommonModule, routing ],
declarations: [ CrisisDetailComponent, CrisisListComponent ],
providers: [ CrisisService ]
})
// #docregion export-default
export default class CrisisModule {}
// #enddocregion export-default

View File

@ -0,0 +1,13 @@
import { Routes,
RouterModule } from '@angular/router';
import { CrisisListComponent } from './crisis-list.component';
import { CrisisDetailComponent } from './crisis-detail.component';
const routes: Routes = [
{ path: '', redirectTo: 'list', pathMatch: 'full'},
{ path: 'list', component: CrisisListComponent },
{ path: ':id', component: CrisisDetailComponent }
];
export const routing = RouterModule.forChild(routes);

View File

@ -0,0 +1,30 @@
import { Injectable } from '@angular/core';
export class Crisis {
constructor(public id: number, public name: string) { }
}
const CRISES: Crisis[] = [
new Crisis(1, 'Dragon Burning Cities'),
new Crisis(2, 'Sky Rains Great White Sharks'),
new Crisis(3, 'Giant Asteroid Heading For Earth'),
new Crisis(4, 'Procrastinators Meeting Delayed Again'),
];
const FETCH_LATENCY = 500;
@Injectable()
export class CrisisService {
getCrises() {
return new Promise<Crisis[]>(resolve => {
setTimeout(() => { resolve(CRISES); }, FETCH_LATENCY);
});
}
getCrisis(id: number | string) {
return this.getCrises()
.then(heroes => heroes.find(hero => hero.id === +id));
}
}

View File

@ -0,0 +1,31 @@
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Hero,
HeroService } from './hero.service';
@Component({
template: `
<h3 highlight>Hero Detail</h3>
<div *ngIf="hero">
<div>Id: {{hero.id}}</div><br>
<label>Name:
<input [(ngModel)]="hero.name">
</label>
</div>
<br>
<a routerLink="../">Hero List</a>
`
})
export class HeroDetailComponent implements OnInit {
hero: Hero;
constructor(
private route: ActivatedRoute,
private heroService: HeroService) { }
ngOnInit() {
let id = parseInt(this.route.snapshot.params['id'], 10);
this.heroService.getHero(id).then(hero => this.hero = hero);
}
}

View File

@ -0,0 +1,21 @@
import { Component, OnInit } from '@angular/core';
import { Hero,
HeroService } from './hero.service';
@Component({
template: `
<h3 highlight>Hero List</h3>
<div *ngFor='let hero of heroes | async'>
<a routerLink="{{hero.id}}">{{hero.id}} - {{hero.name}}</a>
</div>
`
})
export class HeroListComponent implements OnInit {
heroes: Promise<Hero[]>;
constructor(private heroService: HeroService) { }
ngOnInit() {
this.heroes = this.heroService.getHeroes();
}
}

View File

@ -0,0 +1,18 @@
import { Component } from '@angular/core';
import { HeroService } from './hero.service';
import { UserService } from '../user.service';
@Component({
template: `
<h2>Heroes of {{userName}}</h2>
<router-outlet></router-outlet>
`,
providers: [ HeroService ]
})
export class HeroComponent {
userName = '';
constructor(userService: UserService) {
this.userName = userService.userName;
}
}

View File

@ -0,0 +1,19 @@
// Exact copy except import UserService from shared
import { Component } from '@angular/core';
import { HeroService } from './hero.service';
import { UserService } from '../shared/user.service';
@Component({
template: `
<h2>Heroes of {{userName}}</h2>
<router-outlet></router-outlet>
`,
providers: [ HeroService ]
})
export class HeroComponent {
userName = '';
constructor(userService: UserService) {
this.userName = userService.userName;
}
}

View File

@ -0,0 +1,20 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HeroComponent } from './hero.component.3';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroListComponent } from './hero-list.component';
import { HighlightDirective } from './highlight.directive';
import { routing } from './hero.routing.3';
// #docregion class
@NgModule({
imports: [ CommonModule, FormsModule, routing ],
declarations: [
HeroComponent, HeroDetailComponent, HeroListComponent,
HighlightDirective
]
})
export default class HeroModule { }
// #enddocregion class

View File

@ -0,0 +1,23 @@
import { NgModule } from '@angular/core';
import { SharedModule } from '../shared/shared.module';
import { HeroComponent } from './hero.component';
import { HeroDetailComponent } from './hero-detail.component';
import { HeroListComponent } from './hero-list.component';
import { routing } from './hero.routing';
/*
* TODO: Remove THE HeroService class and provider after
* https://github.com/angular/angular/pull/10579 lands
*/
import { HeroService } from './hero.service';
@NgModule({
imports: [ SharedModule, routing ],
providers: [ HeroService ],
declarations: [
HeroComponent, HeroDetailComponent, HeroListComponent,
]
})
export default class HeroModule { }

View File

@ -0,0 +1,18 @@
import { Routes,
RouterModule } from '@angular/router';
import { HeroComponent } from './hero.component.3';
import { HeroListComponent } from './hero-list.component';
import { HeroDetailComponent } from './hero-detail.component';
const routes: Routes = [
{ path: '',
component: HeroComponent,
children: [
{ path: '', component: HeroListComponent },
{ path: ':id', component: HeroDetailComponent }
]
}
];
export const routing = RouterModule.forChild(routes);

View File

@ -0,0 +1,18 @@
import { Routes,
RouterModule } from '@angular/router';
import { HeroComponent } from './hero.component';
import { HeroListComponent } from './hero-list.component';
import { HeroDetailComponent } from './hero-detail.component';
const routes: Routes = [
{ path: '',
component: HeroComponent,
children: [
{ path: '', component: HeroListComponent },
{ path: ':id', component: HeroDetailComponent }
]
}
];
export const routing = RouterModule.forChild(routes);

View File

@ -0,0 +1,32 @@
import { Injectable } from '@angular/core';
export class Hero {
constructor(public id: number, public name: string) { }
}
const HEROES: Hero[] = [
new Hero(11, 'Mr. Nice'),
new Hero(12, 'Narco'),
new Hero(13, 'Bombasto'),
new Hero(14, 'Celeritas'),
new Hero(15, 'Magneta'),
new Hero(16, 'RubberMan')
];
const FETCH_LATENCY = 500;
@Injectable()
export class HeroService {
getHeroes() {
return new Promise<Hero[]>(resolve => {
setTimeout(() => { resolve(HEROES); }, FETCH_LATENCY);
});
}
getHero(id: number | string) {
return this.getHeroes()
.then(heroes => heroes.find(hero => hero.id === +id));
}
}

View File

@ -0,0 +1,14 @@
// #docregion
import { Directive, ElementRef, Renderer } from '@angular/core';
// Same directive name and selector as
// HighlightDirective in parent AppRootModule
// It selects for both input boxes and 'highlight' attr
// and it highlights in beige instead of yellow
@Directive({ selector: '[highlight]' })
export class HighlightDirective {
constructor(renderer: Renderer, el: ElementRef) {
renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'beige');
console.log(`* Hero highlight called for ${el.nativeElement.tagName}`);
}
}

View File

@ -0,0 +1,12 @@
// #docregion
import { Directive, ElementRef, Renderer } from '@angular/core';
@Directive({ selector: '[highlight]' })
/** Highlight the attached element in gold */
export class HighlightDirective {
constructor(renderer: Renderer, el: ElementRef) {
renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'gold');
console.log(
`* AppRoot highlight called for ${el.nativeElement.tagName}`);
}
}

View File

@ -0,0 +1,13 @@
// #docplaster
/*
// #docregion
// The browser platform without a compiler
import { platformBrowser } from '@angular/platform-browser';
// The app module factory produced by the static offline compiler
import { AppModuleNgFactory } from './app.module.ngfactory';
// Launch with the app module factory.
platformBrowser().bootstrapModuleFactory(AppModuleNgFactory);
// #enddocregion
*/

View File

@ -0,0 +1,4 @@
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module.0';
platformBrowserDynamic().bootstrapModule(AppModule);

View File

@ -0,0 +1,4 @@
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module.1';
platformBrowserDynamic().bootstrapModule(AppModule);

View File

@ -0,0 +1,4 @@
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module.1b';
platformBrowserDynamic().bootstrapModule(AppModule);

View File

@ -0,0 +1,4 @@
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module.2';
platformBrowserDynamic().bootstrapModule(AppModule);

View File

@ -0,0 +1,4 @@
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module.3';
platformBrowserDynamic().bootstrapModule(AppModule);

View File

@ -0,0 +1,9 @@
// #docregion
// The browser platform with a compiler
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
// The app module
import { AppModule } from './app.module';
// Compile and launch the module
platformBrowserDynamic().bootstrapModule(AppModule);

View File

@ -0,0 +1,10 @@
// Exact copy of contact.awesome.pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'awesome' })
/** Precede the input string with the word "Awesome " */
export class AwesomePipe implements PipeTransform {
transform(phrase: string) {
return phrase ? 'Awesome ' + phrase : '';
}
}

View File

@ -0,0 +1,13 @@
/* tslint:disable */
// Exact copy of contact/highlight.directive except for color and message
import { Directive, ElementRef, Renderer } from '@angular/core';
@Directive({ selector: '[highlight], input' })
/** Highlight the attached element or an InputElement in gray */
export class HighlightDirective {
constructor(renderer: Renderer, el: ElementRef) {
renderer.setElementStyle(el.nativeElement, 'backgroundColor', 'lightgray');
console.log(
`* Shared highlight called for ${el.nativeElement.tagName}`);
}
}

View File

@ -0,0 +1,40 @@
// #docregion
import { NgModule,
ModuleWithProviders } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AwesomePipe } from './awesome.pipe';
import { HighlightDirective } from './highlight.directive';
import { TitleComponent } from './title.component';
import { UserService } from './user.service';
// #docregion shared-module
@NgModule({
imports: [ CommonModule ],
declarations: [ AwesomePipe, HighlightDirective, TitleComponent ],
exports: [ AwesomePipe, HighlightDirective, TitleComponent,
CommonModule, FormsModule ]
})
export class SharedModule {
// #docregion for-root
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [ UserService ]
};
}
// #enddocregion for-root
}
// #enddocregion shared-module
// #enddocregion
// #docregion shared-root-module
@NgModule({
exports: [ SharedModule ],
providers: [ UserService ]
})
export class SharedRootModule { }
// #enddocregion shared-root-module

View File

@ -0,0 +1,6 @@
<!-- Exact copy from app.component.html -->
<h1 highlight>{{title}} {{subtitle}}</h1>
<p *ngIf="user">
<i>Welcome, {{user}}</i>
<p>

View File

@ -0,0 +1,18 @@
// Exact copy of app/title.component.ts except import UserService from shared
import { Component, Input } from '@angular/core';
import { UserService } from './user.service';
@Component({
moduleId: module.id,
selector: 'app-title',
templateUrl: 'title.component.html',
})
export class TitleComponent {
@Input() subtitle = '';
title = 'Angular Modules';
user = '';
constructor(userService: UserService) {
this.user = userService.userName;
}
}

View File

@ -0,0 +1,20 @@
// Crazy copy of the app/user.service
// Proves that UserService is an app-wide singleton and only instantiated once
// IFF shared.module follows the `forRoot` pattern
//
// If it didn't, a new instance of UserService would be created
// after each lazy load and the userName would double up.
import { Injectable } from '@angular/core';
@Injectable()
export class UserService {
static userName = '';
constructor() {
UserService.userName += UserService.userName || 'Sam Spade';
}
get userName() { return UserService.userName; }
}

View File

@ -0,0 +1,10 @@
<!-- #docregion -->
<!-- #docregion v1 -->
<h1 highlight>{{title}} {{subtitle}}</h1>
<!-- #enddocregion v1 -->
<!-- #docregion ngIf -->
<p *ngIf="user">
<i>Welcome, {{user}}</i>
<p>
<!-- #enddocregion ngIf -->

View File

@ -0,0 +1,25 @@
// #docplaster
// #docregion
// #docregion v1
import { Component, Input } from '@angular/core';
// #enddocregion v1
import { UserService } from './user.service';
// #docregion v1
@Component({
moduleId: module.id,
selector: 'app-title',
templateUrl: 'title.component.html',
})
export class TitleComponent {
@Input() subtitle = '';
title = 'Angular Modules';
// #enddocregion v1
user = '';
constructor(userService: UserService) {
this.user = userService.userName;
}
// #docregion v1
}
// #enddocregion v1

View File

@ -0,0 +1,8 @@
// #docregion
import { Injectable } from '@angular/core';
@Injectable()
/** Dummy version of an authenticated user service */
export class UserService {
userName = 'Sam Spade';
}

View File

@ -0,0 +1,23 @@
{
"description": "Contact NgModule v.1",
"files": [
"app/app.component.1b.ts",
"app/app.module.1b.ts",
"app/main.1b.ts",
"app/highlight.directive.ts",
"app/title.component.html",
"app/title.component.ts",
"app/user.service.ts",
"app/contact/*.css",
"app/contact/*.html",
"app/contact/*.ts",
"!app/contact/contact.component.ts",
"!app/contact/contact.module.ts",
"styles.css",
"index.1b.html"
],
"main": "index.1b.html",
"tags": ["NgModule"]
}

View File

@ -0,0 +1,24 @@
{
"description": "Contact NgModule v.2",
"files": [
"app/app.component.2.ts",
"app/app.module.2.ts",
"app/main.2.ts",
"app/highlight.directive.ts",
"app/title.component.html",
"app/title.component.ts",
"app/user.service.ts",
"app/contact/*.css",
"app/contact/*.html",
"app/contact/*.ts",
"!app/contact/contact.component.ts",
"!app/contact/contact.module.ts",
"!app/contact/contact.module.3.ts",
"styles.css",
"index.2.html"
],
"main": "index.2.html",
"tags": ["NgModule"]
}

View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>NgModule Minimal</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app/main.0').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>

View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>NgModule - Contact</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app/main.1').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>

View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>NgModule - Contact</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app/main.1b').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>

View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>NgModule - Contact</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app/main.2').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>

View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>NgModule - Contact</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app/main.3').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>

View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>NgModule Deluxe</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>

View File

@ -0,0 +1,12 @@
{
"description": "Minimal NgModule",
"files": [
"app/app.component.0.ts",
"app/app.module.0.ts",
"app/main.0.ts",
"styles.css",
"index.0.html"
],
"main": "index.0.html",
"tags": ["NgModule"]
}

View File

@ -0,0 +1,34 @@
{
"description": "NgModule Final",
"files": [
"app/app.component.ts",
"app/app.module.ts",
"app/app.routing.ts",
"app/main.ts",
"app/contact/contact.component.css",
"app/contact/contact.component.html",
"app/contact/contact.component.ts",
"app/contact/contact.module.ts",
"app/contact/contact.routing.ts",
"app/contact/contact.service.ts",
"app/crisis/*.ts",
"app/hero/*.ts",
"!app/hero/hero.component.3.ts",
"!app/hero/hero.module.3.ts",
"!app/hero/hero.routing.3.ts",
"!app/hero/highlight.directive.ts",
"app/shared/*.css",
"app/shared/*.html",
"app/shared/*.ts",
"styles.css",
"index.html"
],
"main": "index.html",
"tags": ["NgModule"]
}

View File

@ -0,0 +1,35 @@
{
"description": "NgModule v.3",
"files": [
"app/app.component.3.ts",
"app/app.module.3.ts",
"app/app.routing.3.ts",
"app/main.3.ts",
"app/highlight.directive.ts",
"app/title.component.html",
"app/title.component.ts",
"app/user.service.ts",
"app/contact/*.css",
"app/contact/*.html",
"app/contact/*.ts",
"!app/contact/contact.component.ts",
"!app/contact/contact.module.ts",
"!app/contact/contact.routing.ts",
"app/crisis/*.ts",
"app/hero/*.ts",
"!app/hero/hero.component.ts",
"!app/hero/hero.module.ts",
"!app/hero/hero.routing.ts",
"styles.css",
"index.3.html"
],
"main": "index.3.html",
"tags": ["NgModule"]
}

View File

@ -70,9 +70,16 @@
"basics": true
},
"ngmodule": {
"title": "Angular Modules (NgModule)",
"intro": "Define application modules with @NgModule",
"hide": true
},
"animations": {
"title": "Animations",
"intro": "A guide to Angular's animation system."
"intro": "A guide to Angular's animation system.",
"hide": true
},
"attribute-directives": {

View File

@ -0,0 +1 @@
!= partial("../../../_includes/_ts-temp")

View File

@ -63,6 +63,12 @@
"basics": true
},
"ngmodule": {
"title": "Angular Modules (NgModule)",
"intro": "Define application modules with @NgModule",
"hide": true
},
"attribute-directives": {
"title": "Attribute Directives",
"intro": "Attribute directives attach behavior to elements."

View File

@ -0,0 +1 @@
!= partial("../../../_includes/_ts-temp")

View File

@ -71,6 +71,11 @@
"basics": true
},
"ngmodule": {
"title": "Angular Modules (NgModule)",
"intro": "Define application modules with @NgModule"
},
"animations": {
"title": "Animations",
"intro": "A guide to Angular's animation system."

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,21 @@
/*
/**
* Angular.io Live Example Directive
*
* Renders a link to a live/host example of the doc chapter
* app this directive is contained in.
*
*
* Usage:
* <live-example [name="..."] [noSource] [srcText="..."]>text</live-example>
* <live-example [name="..."] [plnkr='...'] [noSource] [srcText="..."]>text</live-example>
* Example:
* <p>Run <live-example name="toh-1">this chapter's example</live-example></p>.
* <p>Run <live-example>Try the live example</live-example></p>.
* // ~/resources/live-examples/{chapter}/ts/plnkr.html
*
* <p>Run <live-example name="toh-1">this example</live-example></p>.
* // ~/resources/live-examples/toh-1/ts/minimal.plnkr.html
*
* <p>Run <live-example plnkr="minimal"></live-example></p>.
* // ~/resources/live-examples/{chapter}/ts/minimal.plnkr.html
*/
angularIO.directive('liveExample', ['$location', function ($location) {
function a(text, attrs) {
@ -26,6 +32,7 @@ angularIO.directive('liveExample', ['$location', function ($location) {
compile: function (tElement, attrs) {
var text = tElement.text() || 'live example';
var ex = attrs.name || NgIoUtil.getExampleName($location);
var plnkr = attrs.plnkr || '';
var href, template;
var isForDart = attrs.lang === 'dart' || NgIoUtil.isDoc($location, 'dart');