refactor: move angular source to /packages rather than modules/@angular

This commit is contained in:
Jason Aden
2017-03-02 10:48:42 -08:00
parent 5ad5301a3e
commit 3e51a19983
1051 changed files with 18 additions and 18 deletions

View File

@ -0,0 +1,56 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion Component
import {Component, NgModule, animate, state, style, transition, trigger} from '@angular/core';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
@Component({
selector: 'example-app',
styles: [`
.toggle-container {
background-color:white;
border:10px solid black;
width:200px;
text-align:center;
line-height:100px;
font-size:50px;
box-sizing:border-box;
overflow:hidden;
}
`],
animations: [trigger(
'openClose',
[
state('collapsed, void', style({height: '0px', color: 'maroon', borderColor: 'maroon'})),
state('expanded', style({height: '*', borderColor: 'green', color: 'green'})),
transition(
'collapsed <=> expanded', [animate(500, style({height: '250px'})), animate(500)])
])],
template: `
<button (click)="expand()">Open</button>
<button (click)="collapse()">Closed</button>
<hr />
<div class="toggle-container" [@openClose]="stateExpression">
Look at this box
</div>
`
})
export class MyExpandoCmp {
stateExpression: string;
constructor() { this.collapse(); }
expand() { this.stateExpression = 'expanded'; }
collapse() { this.stateExpression = 'collapsed'; }
}
@NgModule(
{imports: [BrowserAnimationsModule], declarations: [MyExpandoCmp], bootstrap: [MyExpandoCmp]})
export class AppModule {
}
// #enddocregion

View File

@ -0,0 +1,30 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {$, ExpectedConditions, browser, by, element} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../_common/e2e_util';
function waitForElement(selector: string) {
const EC = ExpectedConditions;
// Waits for the element with id 'abc' to be present on the dom.
browser.wait(EC.presenceOf($(selector)), 20000);
}
describe('animation example', () => {
afterEach(verifyNoBrowserErrors);
describe('index view', () => {
const URL = '/core/animation/ts/dsl/';
it('should list out the current collection of items', () => {
browser.get(URL);
waitForElement('.toggle-container');
expect(element.all(by.css('.toggle-container')).get(0).getText()).toEqual('Look at this box');
});
});
});

View File

@ -0,0 +1,8 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export {AppModule} from './animation_example';

View File

@ -0,0 +1,16 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {DebugElement} from '@angular/core';
let debugElement: DebugElement;
let predicate: any;
// #docregion scope_all
debugElement.query(predicate);
// #enddocregion

View File

@ -0,0 +1,43 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion Component
import {Component, ContentChild, Directive, Input} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
@Input() id: string;
}
@Component({
selector: 'tab',
template: `
<div>pane: {{pane?.id}}</div>
`
})
export class Tab {
@ContentChild(Pane) pane: Pane;
}
@Component({
selector: 'example-app',
template: `
<tab>
<pane id="1" *ngIf="shouldShow"></pane>
<pane id="2" *ngIf="!shouldShow"></pane>
</tab>
<button (click)="toggle()">Toggle</button>
`,
})
export class ContentChildComp {
shouldShow = true;
toggle() { this.shouldShow = !this.shouldShow; }
}
// #enddocregion

View File

@ -0,0 +1,24 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion HowTo
import {AfterContentInit, ContentChild, Directive} from '@angular/core';
@Directive({selector: 'child-directive'})
class ChildDirective {
}
@Directive({selector: 'someDir'})
class SomeDir implements AfterContentInit {
@ContentChild(ChildDirective) contentChild: ChildDirective;
ngAfterContentInit() {
// contentChild is set
}
}
// #enddocregion

View File

@ -0,0 +1,30 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ElementFinder, browser, by, element} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../_common/e2e_util';
describe('contentChild example', () => {
afterEach(verifyNoBrowserErrors);
let button: ElementFinder;
let result: ElementFinder;
beforeEach(() => {
browser.get('/core/di/ts/contentChild/index.html');
button = element(by.css('button'));
result = element(by.css('div'));
});
it('should query content child', () => {
expect(result.getText()).toEqual('pane: 1');
button.click();
expect(result.getText()).toEqual('pane: 2');
});
});

View File

@ -0,0 +1,19 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ContentChildComp, Pane, Tab} from './content_child_example';
@NgModule({
imports: [BrowserModule],
declarations: [ContentChildComp, Pane, Tab],
bootstrap: [ContentChildComp]
})
export class AppModule {
}

View File

@ -0,0 +1,46 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion Component
import {Component, ContentChildren, Directive, Input, QueryList} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
@Input() id: string;
}
@Component({
selector: 'tab',
template: `
<div>panes: {{serializedPanes}}</div>
`
})
export class Tab {
@ContentChildren(Pane) panes: QueryList<Pane>;
get serializedPanes(): string { return this.panes ? this.panes.map(p => p.id).join(', ') : ''; }
}
@Component({
selector: 'example-app',
template: `
<tab>
<pane id="1"></pane>
<pane id="2"></pane>
<pane id="3" *ngIf="shouldShow"></pane>
</tab>
<button (click)="show()">Show 3</button>
`,
})
export class ContentChildrenComp {
shouldShow = false;
show() { this.shouldShow = true; }
}
// #enddocregion

View File

@ -0,0 +1,24 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion HowTo
import {AfterContentInit, ContentChildren, Directive, QueryList} from '@angular/core';
@Directive({selector: 'child-directive'})
class ChildDirective {
}
@Directive({selector: 'someDir'})
class SomeDir implements AfterContentInit {
@ContentChildren(ChildDirective) contentChildren: QueryList<ChildDirective>;
ngAfterContentInit() {
// contentChildren is set
}
}
// #enddocregion

View File

@ -0,0 +1,30 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ElementFinder, browser, by, element} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../_common/e2e_util';
describe('contentChildren example', () => {
afterEach(verifyNoBrowserErrors);
let button: ElementFinder;
let result: ElementFinder;
beforeEach(() => {
browser.get('/core/di/ts/contentChildren/index.html');
button = element(by.css('button'));
result = element(by.css('div'));
});
it('should query content children', () => {
expect(result.getText()).toEqual('panes: 1, 2');
button.click();
expect(result.getText()).toEqual('panes: 1, 2, 3');
});
});

View File

@ -0,0 +1,19 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {ContentChildrenComp, Pane, Tab} from './content_children_example';
@NgModule({
imports: [BrowserModule],
declarations: [ContentChildrenComp, Pane, Tab],
bootstrap: [ContentChildrenComp]
})
export class AppModule {
}

View File

@ -0,0 +1,50 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Inject, ReflectiveInjector, forwardRef, resolveForwardRef} from '@angular/core';
export function main() {
describe('forwardRef examples', () => {
it('ForwardRefFn example works', () => {
// #docregion forward_ref_fn
const ref = forwardRef(() => Lock);
// #enddocregion
expect(ref).not.toBeNull();
class Lock {}
});
it('can be used to inject a class defined later', () => {
// #docregion forward_ref
class Door {
lock: Lock;
// Door attempts to inject Lock, despite it not being defined yet.
// forwardRef makes this possible.
constructor(@Inject(forwardRef(() => Lock)) lock: Lock) { this.lock = lock; }
}
// Only at this point Lock is defined.
class Lock {}
const injector = ReflectiveInjector.resolveAndCreate([Door, Lock]);
const door = injector.get(Door);
expect(door instanceof Door).toBeTruthy();
expect(door.lock instanceof Lock).toBeTruthy();
// #enddocregion
});
it('can be unwrapped', () => {
// #docregion resolve_forward_ref
const ref = forwardRef(() => 'refValue');
expect(resolveForwardRef(ref)).toEqual('refValue');
expect(resolveForwardRef('regularValue')).toEqual('regularValue');
// #enddocregion
});
});
}

View File

@ -0,0 +1,41 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {InjectionToken, Injector, ReflectiveInjector} from '@angular/core';
export function main() {
describe('injector metadata examples', () => {
it('works', () => {
// #docregion Injector
const injector: Injector =
ReflectiveInjector.resolveAndCreate([{provide: 'validToken', useValue: 'Value'}]);
expect(injector.get('validToken')).toEqual('Value');
expect(() => injector.get('invalidToken')).toThrowError();
expect(injector.get('invalidToken', 'notFound')).toEqual('notFound');
// #enddocregion
});
it('injects injector', () => {
// #docregion injectInjector
const injector = ReflectiveInjector.resolveAndCreate([]);
expect(injector.get(Injector)).toBe(injector);
// #enddocregion
});
it('should infer type', () => {
// #docregion InjectionToken
const BASE_URL = new InjectionToken<string>('BaseUrl');
const injector =
ReflectiveInjector.resolveAndCreate([{provide: BASE_URL, useValue: 'http://localhost'}]);
const url = injector.get(BASE_URL);
// here `url` is inferred to be `string` because `BASE_URL` is `InjectionToken<string>`.
expect(url).toBe('http://localhost');
// #enddocregion
});
});
}

View File

@ -0,0 +1,185 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, Directive, Host, Inject, Injectable, Optional, ReflectiveInjector, Self, SkipSelf} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
export function main() {
describe('di metadata examples', () => {
describe('Inject', () => {
it('works', () => {
// #docregion Inject
class Engine {}
@Injectable()
class Car {
constructor(@Inject('MyEngine') public engine: Engine) {}
}
const injector =
ReflectiveInjector.resolveAndCreate([{provide: 'MyEngine', useClass: Engine}, Car]);
expect(injector.get(Car).engine instanceof Engine).toBe(true);
// #enddocregion
});
it('works without decorator', () => {
// #docregion InjectWithoutDecorator
class Engine {}
@Injectable()
class Car {
constructor(public engine: Engine) {
} // same as constructor(@Inject(Engine) engine:Engine)
}
const injector = ReflectiveInjector.resolveAndCreate([Engine, Car]);
expect(injector.get(Car).engine instanceof Engine).toBe(true);
// #enddocregion
});
});
describe('Optional', () => {
it('works', () => {
// #docregion Optional
class Engine {}
@Injectable()
class Car {
constructor(@Optional() public engine: Engine) {}
}
const injector = ReflectiveInjector.resolveAndCreate([Car]);
expect(injector.get(Car).engine).toBeNull();
// #enddocregion
});
});
describe('Injectable', () => {
it('works', () => {
// #docregion Injectable
@Injectable()
class UsefulService {
}
@Injectable()
class NeedsService {
constructor(public service: UsefulService) {}
}
const injector = ReflectiveInjector.resolveAndCreate([NeedsService, UsefulService]);
expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);
// #enddocregion
});
it('throws without Injectable', () => {
// #docregion InjectableThrows
class UsefulService {}
class NeedsService {
constructor(public service: UsefulService) {}
}
expect(() => ReflectiveInjector.resolveAndCreate([NeedsService, UsefulService])).toThrow();
// #enddocregion
});
});
describe('Self', () => {
it('works', () => {
// #docregion Self
class Dependency {}
@Injectable()
class NeedsDependency {
constructor(@Self() public dependency: Dependency) {}
}
let inj = ReflectiveInjector.resolveAndCreate([Dependency, NeedsDependency]);
const nd = inj.get(NeedsDependency);
expect(nd.dependency instanceof Dependency).toBe(true);
inj = ReflectiveInjector.resolveAndCreate([Dependency]);
const child = inj.resolveAndCreateChild([NeedsDependency]);
expect(() => child.get(NeedsDependency)).toThrowError();
// #enddocregion
});
});
describe('SkipSelf', () => {
it('works', () => {
// #docregion SkipSelf
class Dependency {}
@Injectable()
class NeedsDependency {
constructor(@SkipSelf() public dependency: Dependency) { this.dependency = dependency; }
}
const parent = ReflectiveInjector.resolveAndCreate([Dependency]);
const child = parent.resolveAndCreateChild([NeedsDependency]);
expect(child.get(NeedsDependency).dependency instanceof Dependency).toBe(true);
const inj = ReflectiveInjector.resolveAndCreate([Dependency, NeedsDependency]);
expect(() => inj.get(NeedsDependency)).toThrowError();
// #enddocregion
});
});
describe('Host', () => {
it('works', () => {
// #docregion Host
class OtherService {}
class HostService {}
@Directive({selector: 'child-directive'})
class ChildDirective {
logs: string[] = [];
constructor(@Optional() @Host() os: OtherService, @Optional() @Host() hs: HostService) {
// os is null: true
this.logs.push(`os is null: ${os === null}`);
// hs is an instance of HostService: true
this.logs.push(`hs is an instance of HostService: ${hs instanceof HostService}`);
}
}
@Component({
selector: 'parent-cmp',
viewProviders: [HostService],
template: '<child-directive></child-directive>',
})
class ParentCmp {
}
@Component({
selector: 'app',
viewProviders: [OtherService],
template: '<parent-cmp></parent-cmp>',
})
class App {
}
// #enddocregion
TestBed.configureTestingModule({
declarations: [App, ParentCmp, ChildDirective],
});
let cmp: ComponentFixture<App>;
expect(() => cmp = TestBed.createComponent(App)).not.toThrow();
expect(cmp.debugElement.children[0].children[0].injector.get(ChildDirective).logs).toEqual([
'os is null: true',
'hs is an instance of HostService: true',
]);
});
});
});
}

View File

@ -0,0 +1,149 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Inject, Injectable, InjectionToken, Optional, ReflectiveInjector} from '@angular/core';
export function main() {
describe('Provider examples', () => {
describe('TypeProvider', () => {
it('works', () => {
// #docregion TypeProvider
@Injectable()
class Greeting {
salutation = 'Hello';
}
const injector = ReflectiveInjector.resolveAndCreate([
Greeting, // Shorthand for { provide: Greeting, useClass: Greeting }
]);
expect(injector.get(Greeting).salutation).toBe('Hello');
// #enddocregion
});
});
describe('ValueProvider', () => {
it('works', () => {
// #docregion ValueProvider
const injector =
ReflectiveInjector.resolveAndCreate([{provide: String, useValue: 'Hello'}]);
expect(injector.get(String)).toEqual('Hello');
// #enddocregion
});
});
describe('MultiProviderAspect', () => {
it('works', () => {
// #docregion MultiProviderAspect
const injector = ReflectiveInjector.resolveAndCreate([
{provide: 'local', multi: true, useValue: 'en'},
{provide: 'local', multi: true, useValue: 'sk'},
]);
const locales: string[] = injector.get('local');
expect(locales).toEqual(['en', 'sk']);
// #enddocregion
});
});
describe('ClassProvider', () => {
it('works', () => {
// #docregion ClassProvider
abstract class Shape { name: string; }
class Square extends Shape {
name = 'square';
}
const injector = ReflectiveInjector.resolveAndCreate([{provide: Shape, useClass: Square}]);
const shape: Shape = injector.get(Shape);
expect(shape.name).toEqual('square');
expect(shape instanceof Square).toBe(true);
// #enddocregion
});
it('is different then useExisting', () => {
// #docregion ClassProviderDifference
class Greeting {
salutation = 'Hello';
}
class FormalGreeting extends Greeting {
salutation = 'Greetings';
}
const injector = ReflectiveInjector.resolveAndCreate(
[FormalGreeting, {provide: Greeting, useClass: FormalGreeting}]);
// The injector returns different instances.
// See: {provide: ?, useExisting: ?} if you want the same instance.
expect(injector.get(FormalGreeting)).not.toBe(injector.get(Greeting));
// #enddocregion
});
});
describe('ExistingProvider', () => {
it('works', () => {
// #docregion ExistingProvider
class Greeting {
salutation = 'Hello';
}
class FormalGreeting extends Greeting {
salutation = 'Greetings';
}
const injector = ReflectiveInjector.resolveAndCreate(
[FormalGreeting, {provide: Greeting, useExisting: FormalGreeting}]);
expect(injector.get(Greeting).salutation).toEqual('Greetings');
expect(injector.get(FormalGreeting).salutation).toEqual('Greetings');
expect(injector.get(FormalGreeting)).toBe(injector.get(Greeting));
// #enddocregion
});
});
describe('FactoryProvider', () => {
it('works', () => {
// #docregion FactoryProvider
const Location = new InjectionToken('location');
const Hash = new InjectionToken('hash');
const injector = ReflectiveInjector.resolveAndCreate([
{provide: Location, useValue: 'http://angular.io/#someLocation'}, {
provide: Hash,
useFactory: (location: string) => location.split('#')[1],
deps: [Location]
}
]);
expect(injector.get(Hash)).toEqual('someLocation');
// #enddocregion
});
it('supports optional dependencies', () => {
// #docregion FactoryProviderOptionalDeps
const Location = new InjectionToken('location');
const Hash = new InjectionToken('hash');
const injector = ReflectiveInjector.resolveAndCreate([{
provide: Hash,
useFactory: (location: string) => `Hash for: ${location}`,
// use a nested array to define metadata for dependencies.
deps: [[new Optional(), Location]]
}]);
expect(injector.get(Hash)).toEqual('Hash for: null');
// #enddocregion
});
});
});
}

View File

@ -0,0 +1,30 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ElementFinder, browser, by, element} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../_common/e2e_util';
describe('viewChild example', () => {
afterEach(verifyNoBrowserErrors);
let button: ElementFinder;
let result: ElementFinder;
beforeEach(() => {
browser.get('/core/di/ts/viewChild/index.html');
button = element(by.css('button'));
result = element(by.css('div'));
});
it('should query view child', () => {
expect(result.getText()).toEqual('Selected: 1');
button.click();
expect(result.getText()).toEqual('Selected: 2');
});
});

View File

@ -0,0 +1,17 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Pane, ViewChildComp} from './view_child_example';
@NgModule(
{imports: [BrowserModule], declarations: [ViewChildComp, Pane], bootstrap: [ViewChildComp]})
export class AppModule {
}

View File

@ -0,0 +1,37 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion Component
import {Component, Directive, Input, ViewChild} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
@Input() id: string;
}
@Component({
selector: 'example-app',
template: `
<pane id="1" *ngIf="shouldShow"></pane>
<pane id="2" *ngIf="!shouldShow"></pane>
<button (click)="toggle()">Toggle</button>
<div>Selected: {{selectedPane}}</div>
`,
})
export class ViewChildComp {
@ViewChild(Pane)
set pane(v: Pane) {
setTimeout(() => { this.selectedPane = v.id; }, 0);
}
selectedPane: string = '';
shouldShow = true;
toggle() { this.shouldShow = !this.shouldShow; }
}
// #enddocregion

View File

@ -0,0 +1,24 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion HowTo
import {AfterViewInit, Component, Directive, ViewChild} from '@angular/core';
@Directive({selector: 'child-directive'})
class ChildDirective {
}
@Component({selector: 'someCmp', templateUrl: 'someCmp.html'})
class SomeCmp implements AfterViewInit {
@ViewChild(ChildDirective) child: ChildDirective;
ngAfterViewInit() {
// child is set
}
}
// #enddocregion

View File

@ -0,0 +1,31 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {ElementFinder, browser, by, element} from 'protractor';
import {verifyNoBrowserErrors} from '../../../../../_common/e2e_util';
describe('viewChildren example', () => {
afterEach(verifyNoBrowserErrors);
let button: ElementFinder;
let result: ElementFinder;
beforeEach(() => {
browser.get('/core/di/ts/viewChildren/index.html');
button = element(by.css('button'));
result = element(by.css('div'));
});
it('should query view children', () => {
expect(result.getText()).toEqual('panes: 1, 2');
button.click();
expect(result.getText()).toEqual('panes: 1, 2, 3');
});
});

View File

@ -0,0 +1,20 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Pane, ViewChildrenComp} from './view_children_example';
@NgModule({
imports: [BrowserModule],
declarations: [ViewChildrenComp, Pane],
bootstrap: [ViewChildrenComp]
})
export class AppModule {
}

View File

@ -0,0 +1,46 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion Component
import {AfterViewInit, Component, Directive, Input, QueryList, ViewChildren} from '@angular/core';
@Directive({selector: 'pane'})
export class Pane {
@Input() id: string;
}
@Component({
selector: 'example-app',
template: `
<pane id="1"></pane>
<pane id="2"></pane>
<pane id="3" *ngIf="shouldShow"></pane>
<button (click)="show()">Show 3</button>
<div>panes: {{serializedPanes}}</div>
`,
})
export class ViewChildrenComp implements AfterViewInit {
@ViewChildren(Pane) panes: QueryList<Pane>;
serializedPanes: string = '';
shouldShow = false;
show() { this.shouldShow = true; }
ngAfterViewInit() {
this.calculateSerializedPanes();
this.panes.changes.subscribe((r) => { this.calculateSerializedPanes(); });
}
calculateSerializedPanes() {
setTimeout(() => { this.serializedPanes = this.panes.map(p => p.id).join(', '); }, 0);
}
}
// #enddocregion

View File

@ -0,0 +1,24 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion HowTo
import {AfterViewInit, Component, Directive, QueryList, ViewChildren} from '@angular/core';
@Directive({selector: 'child-directive'})
class ChildDirective {
}
@Component({selector: 'someCmp', templateUrl: 'someCmp.html'})
class SomeCmp implements AfterViewInit {
@ViewChildren(ChildDirective) viewChildren: QueryList<ChildDirective>;
ngAfterViewInit() {
// viewChildren is set
}
}
// #enddocregion

View File

View File

@ -0,0 +1,27 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
// #docregion bootstrap
@Component({selector: 'my-app', template: 'Hello {{ name }}!'})
class MyApp {
name: string = 'World';
}
@NgModule({imports: [BrowserModule], bootstrap: [MyApp]})
class AppModule {
}
export function main() {
platformBrowserDynamic().bootstrapModule(AppModule);
}
// #enddocregion

View File

@ -0,0 +1,150 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, DoCheck, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, Type} from '@angular/core';
import {TestBed} from '@angular/core/testing';
export function main() {
describe('lifecycle hooks examples', () => {
it('should work with ngOnInit', () => {
// #docregion OnInit
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnInit {
ngOnInit() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngOnInit', []]]);
});
it('should work with ngDoCheck', () => {
// #docregion DoCheck
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements DoCheck {
ngDoCheck() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngDoCheck', []]]);
});
it('should work with ngAfterContentChecked', () => {
// #docregion AfterContentChecked
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements AfterContentChecked {
ngAfterContentChecked() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterContentChecked', []]]);
});
it('should work with ngAfterContentInit', () => {
// #docregion AfterContentInit
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements AfterContentInit {
ngAfterContentInit() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterContentInit', []]]);
});
it('should work with ngAfterViewChecked', () => {
// #docregion AfterViewChecked
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements AfterViewChecked {
ngAfterViewChecked() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterViewChecked', []]]);
});
it('should work with ngAfterViewInit', () => {
// #docregion AfterViewInit
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements AfterViewInit {
ngAfterViewInit() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterViewInit', []]]);
});
it('should work with ngOnDestroy', () => {
// #docregion OnDestroy
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnDestroy {
ngOnDestroy() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngOnDestroy', []]]);
});
it('should work with ngOnChanges', () => {
// #docregion OnChanges
@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnChanges {
@Input()
prop: number;
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
}
// #enddocregion
const log = createAndLogComponent(MyComponent, ['prop']);
expect(log.length).toBe(1);
expect(log[0][0]).toBe('ngOnChanges');
const changes: SimpleChanges = log[0][1][0];
expect(changes['prop'].currentValue).toBe(true);
});
});
function createAndLogComponent(clazz: Type<any>, inputs: string[] = []): any[] {
const log: any[] = [];
createLoggingSpiesFromProto(clazz, log);
const inputBindings = inputs.map(input => `[${input}] = true`).join(' ');
@Component({template: `<my-cmp ${inputBindings}></my-cmp>`})
class ParentComponent {
}
const fixture = TestBed.configureTestingModule({declarations: [ParentComponent, clazz]})
.createComponent(ParentComponent);
fixture.detectChanges();
fixture.destroy();
return log;
}
function createLoggingSpiesFromProto(clazz: Type<any>, log: any[]) {
const proto = clazz.prototype;
Object.keys(proto).forEach((method) => {
proto[method] = (...args: any[]) => { log.push([method, args]); };
});
}
}

View File

@ -0,0 +1,51 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Attribute, Component, Directive, Pipe} from '@angular/core';
class CustomDirective {};
// #docregion component
@Component({selector: 'greet', template: 'Hello {{name}}!'})
class Greet {
name: string = 'World';
}
// #enddocregion
// #docregion attributeFactory
@Component({selector: 'page', template: 'Title: {{title}}'})
class Page {
title: string;
constructor(@Attribute('title') title: string) { this.title = title; }
}
// #enddocregion
// #docregion attributeMetadata
@Directive({selector: 'input'})
class InputAttrDirective {
constructor(@Attribute('type') type: string) {
// type would be 'text' in this example
}
}
// #enddocregion
// #docregion directive
@Directive({selector: 'input'})
class InputDirective {
constructor() {
// Add some logic.
}
}
// #enddocregion
// #docregion pipe
@Pipe({name: 'lowercase'})
class Lowercase {
transform(v: string, args: any[]) { return v.toLowerCase(); }
}
// #enddocregion

View File

@ -0,0 +1,19 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, createPlatformFactory} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
// #docregion longform
@Component({selector: 'my-app', template: 'Hello World'})
class MyApp {
}
const myPlatformFactory = createPlatformFactory(platformBrowserDynamic, 'myPlatform');
myPlatformFactory().bootstrapModule(MyApp);
// #enddocregion

View File

@ -0,0 +1,13 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component} from '@angular/core';
@Component({selector: 'my-component', template: '<h1>My Component</h1>'})
export class MyComponent {
}

View File

@ -0,0 +1,20 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// #docregion enableProdMode
import {NgModule, enableProdMode} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {MyComponent} from './my_component';
enableProdMode();
@NgModule({imports: [BrowserModule], bootstrap: [MyComponent]})
class AppModule {
}
platformBrowserDynamic().bootstrapModule(AppModule);
// #enddocregion