Template Upload

This commit is contained in:
SOUTHERNCO\x2mjbyrn
2017-05-17 13:45:25 -04:00
parent 415b9c25f3
commit 7efe7605b8
11476 changed files with 2170865 additions and 34 deletions

6
node_modules/angular2/es6/prod/README.dart.md generated vendored Normal file
View File

@ -0,0 +1,6 @@
Angular2
=========
The sources for this package are in the main [Angular2](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo. This is the repository for the upcoming 2.0 version. If you're looking for the current official version of Angular you should go to [angular/angular.js](https://github.com/angular/angular.js)
License: Apache MIT 2.0

15
node_modules/angular2/es6/prod/README.js.md generated vendored Normal file
View File

@ -0,0 +1,15 @@
Angular2
=========
The sources for this package are in the main [Angular2](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo. This is the repository for the upcoming 2.0 version. If you're looking for the current official version of Angular you should go to [angular/angular.js](https://github.com/angular/angular.js)
This package contains different sources for different users:
1. The files located in the root folder can be consumed using CommonJS.
2. The files under `/es6` are es6 compatible files that can be transpiled to
es5 using any transpiler. This contains:
* `dev/`: a development version that includes runtime type assertions
* `prod/`: a production version that does not include runtime type assertions
3. The files under `/ts` are the TypeScript source files.
License: Apache MIT 2.0

5
node_modules/angular2/es6/prod/animate.js generated vendored Normal file
View File

@ -0,0 +1,5 @@
export { Animation } from './src/animate/animation';
export { AnimationBuilder } from './src/animate/animation_builder';
export { BrowserDetails } from './src/animate/browser_details';
export { CssAnimationBuilder } from './src/animate/css_animation_builder';
export { CssAnimationOptions } from './src/animate/css_animation_options';

1
node_modules/angular2/es6/prod/animate/testing.js generated vendored Normal file
View File

@ -0,0 +1 @@
export * from 'angular2/src/mock/animation_builder_mock';

6
node_modules/angular2/es6/prod/bootstrap.js generated vendored Normal file
View File

@ -0,0 +1,6 @@
/**
* See {@link bootstrap} for more information.
* @deprecated
*/
export { bootstrap } from 'angular2/platform/browser';
export { AngularEntrypoint } from 'angular2/src/core/angular_entrypoint';

6
node_modules/angular2/es6/prod/bootstrap_static.js generated vendored Normal file
View File

@ -0,0 +1,6 @@
/**
* See {@link bootstrap} for more information.
* @deprecated
*/
export { bootstrapStatic } from 'angular2/platform/browser_static';
export { AngularEntrypoint } from 'angular2/src/core/angular_entrypoint';

4
node_modules/angular2/es6/prod/common.js generated vendored Normal file
View File

@ -0,0 +1,4 @@
export * from './src/common/pipes';
export * from './src/common/directives';
export * from './src/common/forms';
export * from './src/common/common_directives';

8
node_modules/angular2/es6/prod/compiler.js generated vendored Normal file
View File

@ -0,0 +1,8 @@
/**
* @module
* @description
* Starting point to import all compiler APIs.
*/
export * from './src/compiler/url_resolver';
export * from './src/compiler/xhr';
export * from './src/compiler/compiler';

23
node_modules/angular2/es6/prod/core.js generated vendored Normal file
View File

@ -0,0 +1,23 @@
/**
* @module
* @description
* Starting point to import all public core APIs.
*/
export * from './src/core/metadata';
export * from './src/core/util';
export * from './src/core/prod_mode';
export * from './src/core/di';
export * from './src/facade/facade';
export { enableProdMode } from 'angular2/src/facade/lang';
export { platform, createNgZone, PlatformRef, ApplicationRef } from './src/core/application_ref';
export { APP_ID, APP_COMPONENT, APP_INITIALIZER, PACKAGE_ROOT_URL, PLATFORM_INITIALIZER } from './src/core/application_tokens';
export * from './src/core/zone';
export * from './src/core/render';
export * from './src/core/linker';
export { DebugElement, DebugNode, asNativeElements } from './src/core/debug/debug_node';
export * from './src/core/testability/testability';
export * from './src/core/change_detection';
export * from './src/core/platform_directives_and_pipes';
export * from './src/core/platform_common_providers';
export * from './src/core/application_common_providers';
export * from './src/core/reflection/reflection';

6
node_modules/angular2/es6/prod/examples/README.md generated vendored Normal file
View File

@ -0,0 +1,6 @@
# API Examples
This folder contains small example apps that get in-lined into our API docs.
These examples are written with idiomatic TypeScript, and are not transpiled to Dart.
Each example contains tests for application behavior (as opposed to testing Angular's
behavior) just like an Angular application developer would write.

View File

@ -0,0 +1,43 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
import { MinLengthValidator, MaxLengthValidator } from 'angular2/common';
// #docregion min
let MinLengthTestComponent = class {
};
MinLengthTestComponent = __decorate([
Component({
selector: 'min-cmp',
directives: [MinLengthValidator],
template: `
<form>
<p>Year: <input ngControl="year" minlength="2"></p>
</form>
`
}),
__metadata('design:paramtypes', [])
], MinLengthTestComponent);
// #enddocregion
// #docregion max
let MaxLengthTestComponent = class {
};
MaxLengthTestComponent = __decorate([
Component({
selector: 'max-cmp',
directives: [MaxLengthValidator],
template: `
<form>
<p>Year: <input ngControl="year" maxlength="4"></p>
</form>
`
}),
__metadata('design:paramtypes', [])
], MaxLengthTestComponent);
// #enddocregion

View File

@ -0,0 +1,16 @@
import { provide } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
import { UrlResolver } from 'angular2/compiler';
var MyApp;
// #docregion url_resolver
class MyUrlResolver extends UrlResolver {
resolve(baseUrl, url) {
// Serve CSS files from a special CDN.
if (url.substr(-4) === '.css') {
return super.resolve('http://cdn.myapp.com/css/', url);
}
return super.resolve(baseUrl, url);
}
}
bootstrap(MyApp, [provide(UrlResolver, { useClass: MyUrlResolver })]);
// #enddocregion

View File

@ -0,0 +1,5 @@
var debugElement;
var predicate;
// #docregion scope_all
debugElement.query(predicate);
// #enddocregion

View File

@ -0,0 +1,39 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { Inject, Injector, forwardRef, resolveForwardRef } from 'angular2/core';
// #docregion forward_ref_fn
var ref = forwardRef(() => Lock);
// #enddocregion
// #docregion forward_ref
class Door {
constructor(lock) {
this.lock = lock;
}
}
Door = __decorate([
__param(0, Inject(forwardRef(() => Lock))),
__metadata('design:paramtypes', [Lock])
], Door);
// Only at this point Lock is defined.
class Lock {
}
var injector = Injector.resolveAndCreate([Door, Lock]);
var door = injector.get(Door);
expect(door instanceof Door).toBe(true);
expect(door.lock instanceof Lock).toBe(true);
// #enddocregion
// #docregion resolve_forward_ref
var ref = forwardRef(() => "refValue");
expect(resolveForwardRef(ref)).toEqual("refValue");
expect(resolveForwardRef("regularValue")).toEqual("regularValue");
// #enddocregion

View File

@ -0,0 +1,8 @@
import { bootstrap } from 'angular2/platform/browser';
import { NG_VALIDATORS } from 'angular2/common';
import { Provider } from 'angular2/core';
let MyApp = null;
let myValidator = null;
// #docregion ng_validators
bootstrap(MyApp, [new Provider(NG_VALIDATORS, { useValue: myValidator, multi: true })]);
// #enddocregion

View File

@ -0,0 +1,74 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
import { Observable } from 'rxjs/Rx';
// #docregion AsyncPipe
export let AsyncPipeExample = class {
constructor() {
this.greeting = null;
this.arrived = false;
this.resolve = null;
this.reset();
}
reset() {
this.arrived = false;
this.greeting = new Promise((resolve, reject) => { this.resolve = resolve; });
}
clicked() {
if (this.arrived) {
this.reset();
}
else {
this.resolve("hi there!");
this.arrived = true;
}
}
};
AsyncPipeExample = __decorate([
Component({
selector: 'async-example',
template: `<div>
<p>Wait for it... {{ greeting | async }}</p>
<button (click)="clicked()">{{ arrived ? 'Reset' : 'Resolve' }}</button>
</div>`
}),
__metadata('design:paramtypes', [])
], AsyncPipeExample);
// #enddocregion
// #docregion AsyncPipeObservable
let Task = class {
constructor() {
this.time = new Observable((observer) => {
setInterval(() => observer.next(new Date().getTime()), 500);
});
}
};
Task = __decorate([
Component({ selector: "task-cmp", template: "Time: {{ time | async }}" }),
__metadata('design:paramtypes', [])
], Task);
// #enddocregion
export let AppCmp = class {
};
AppCmp = __decorate([
Component({
selector: 'example-app',
directives: [AsyncPipeExample],
template: `
<h1>AsyncPipe Example</h1>
<async-example></async-example>
`
}),
__metadata('design:paramtypes', [])
], AppCmp);
export function main() {
bootstrap(AppCmp);
}

View File

@ -0,0 +1,45 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
// #docregion DatePipe
export let DatePipeExample = class {
constructor() {
this.today = Date.now();
}
};
DatePipeExample = __decorate([
Component({
selector: 'date-example',
template: `<div>
<p>Today is {{today | date}}</p>
<p>Or if you prefer, {{today | date:'fullDate'}}</p>
<p>The time is {{today | date:'jmZ'}}</p>
</div>`
}),
__metadata('design:paramtypes', [])
], DatePipeExample);
// #enddocregion
export let AppCmp = class {
};
AppCmp = __decorate([
Component({
selector: 'example-app',
directives: [DatePipeExample],
template: `
<h1>DatePipe Example</h1>
<date-example></date-example>
`
}),
__metadata('design:paramtypes', [])
], AppCmp);
export function main() {
bootstrap(AppCmp);
}

View File

@ -0,0 +1,46 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
// #docregion JsonPipe
export let JsonPipeExample = class {
constructor() {
this.object = { foo: 'bar', baz: 'qux', nested: { xyz: 3, numbers: [1, 2, 3, 4, 5] } };
}
};
JsonPipeExample = __decorate([
Component({
selector: 'json-example',
template: `<div>
<p>Without JSON pipe:</p>
<pre>{{object}}</pre>
<p>With JSON pipe:</p>
<pre>{{object | json}}</pre>
</div>`
}),
__metadata('design:paramtypes', [])
], JsonPipeExample);
// #enddocregion
export let AppCmp = class {
};
AppCmp = __decorate([
Component({
selector: 'example-app',
directives: [JsonPipeExample],
template: `
<h1>JsonPipe Example</h1>
<json-example></json-example>
`
}),
__metadata('design:paramtypes', [])
], AppCmp);
export function main() {
bootstrap(AppCmp);
}

View File

@ -0,0 +1,43 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
// #docregion LowerUpperPipe
export let LowerUpperPipeExample = class {
change(value) { this.value = value; }
};
LowerUpperPipeExample = __decorate([
Component({
selector: 'lowerupper-example',
template: `<div>
<label>Name: </label><input #name (keyup)="change(name.value)" type="text">
<p>In lowercase: <pre>'{{value | lowercase}}'</pre></p>
<p>In uppercase: <pre>'{{value | uppercase}}'</pre></p>
</div>`
}),
__metadata('design:paramtypes', [])
], LowerUpperPipeExample);
// #enddocregion
export let AppCmp = class {
};
AppCmp = __decorate([
Component({
selector: 'example-app',
directives: [LowerUpperPipeExample],
template: `
<h1>LowercasePipe &amp; UppercasePipe Example</h1>
<lowerupper-example></lowerupper-example>
`
}),
__metadata('design:paramtypes', [])
], AppCmp);
export function main() {
bootstrap(AppCmp);
}

View File

@ -0,0 +1,88 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
// #docregion NumberPipe
export let NumberPipeExample = class {
constructor() {
this.pi = 3.141;
this.e = 2.718281828459045;
}
};
NumberPipeExample = __decorate([
Component({
selector: 'number-example',
template: `<div>
<p>e (no formatting): {{e}}</p>
<p>e (3.1-5): {{e | number:'3.1-5'}}</p>
<p>pi (no formatting): {{pi}}</p>
<p>pi (3.5-5): {{pi | number:'3.5-5'}}</p>
</div>`
}),
__metadata('design:paramtypes', [])
], NumberPipeExample);
// #enddocregion
// #docregion PercentPipe
export let PercentPipeExample = class {
constructor() {
this.a = 0.259;
this.b = 1.3495;
}
};
PercentPipeExample = __decorate([
Component({
selector: 'percent-example',
template: `<div>
<p>A: {{a | percent}}</p>
<p>B: {{b | percent:'4.3-5'}}</p>
</div>`
}),
__metadata('design:paramtypes', [])
], PercentPipeExample);
// #enddocregion
// #docregion CurrencyPipe
export let CurrencyPipeExample = class {
constructor() {
this.a = 0.259;
this.b = 1.3495;
}
};
CurrencyPipeExample = __decorate([
Component({
selector: 'currency-example',
template: `<div>
<p>A: {{a | currency:'USD':false}}</p>
<p>B: {{b | currency:'USD':true:'4.2-2'}}</p>
</div>`
}),
__metadata('design:paramtypes', [])
], CurrencyPipeExample);
// #enddocregion
export let AppCmp = class {
};
AppCmp = __decorate([
Component({
selector: 'example-app',
directives: [NumberPipeExample, PercentPipeExample, CurrencyPipeExample],
template: `
<h1>Numeric Pipe Examples</h1>
<h2>NumberPipe Example</h2>
<number-example></number-example>
<h2>PercentPipe Example</h2>
<percent-example></percent-example>
<h2>CurrencyPipeExample</h2>
<currency-example></currency-example>
`
}),
__metadata('design:paramtypes', [])
], AppCmp);
export function main() {
bootstrap(AppCmp);
}

View File

@ -0,0 +1,65 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
// #docregion SlicePipe_string
export let SlicePipeStringExample = class {
constructor() {
this.str = 'abcdefghij';
}
};
SlicePipeStringExample = __decorate([
Component({
selector: 'slice-string-example',
template: `<div>
<p>{{str}}[0:4]: '{{str | slice:0:4}}' - output is expected to be 'abcd'</p>
<p>{{str}}[4:0]: '{{str | slice:4:0}}' - output is expected to be ''</p>
<p>{{str}}[-4]: '{{str | slice:-4}}' - output is expected to be 'ghij'</p>
<p>{{str}}[-4:-2]: '{{str | slice:-4:-2}}' - output is expected to be 'gh'</p>
<p>{{str}}[-100]: '{{str | slice:-100}}' - output is expected to be 'abcdefghij'</p>
<p>{{str}}[100]: '{{str | slice:100}}' - output is expected to be ''</p>
</div>`
}),
__metadata('design:paramtypes', [])
], SlicePipeStringExample);
// #enddocregion
// #docregion SlicePipe_list
export let SlicePipeListExample = class {
constructor() {
this.collection = ['a', 'b', 'c', 'd'];
}
};
SlicePipeListExample = __decorate([
Component({
selector: 'slice-list-example',
template: `<div>
<li *ngFor="var i of collection | slice:1:3">{{i}}</li>
</div>`
}),
__metadata('design:paramtypes', [])
], SlicePipeListExample);
// #enddocregion
export let AppCmp = class {
};
AppCmp = __decorate([
Component({
selector: 'example-app',
directives: [SlicePipeListExample, SlicePipeStringExample],
template: `
<h1>SlicePipe Examples</h1>
<slice-list-example></slice-list-example>
<slice-string-example></slice-string-example>
`
}),
__metadata('design:paramtypes', [])
], AppCmp);
export function main() {
bootstrap(AppCmp);
}

View File

@ -0,0 +1,25 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
// #docregion bootstrap
let MyApp = class {
constructor() {
this.name = 'World';
}
};
MyApp = __decorate([
Component({ selector: 'my-app', template: 'Hello {{ name }}!' }),
__metadata('design:paramtypes', [])
], MyApp);
function main() {
return bootstrap(MyApp);
}
// #enddocregion

View File

@ -0,0 +1,69 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { Component, Attribute, Directive, Pipe } from 'angular2/core';
var CustomDirective;
// #docregion component
let Greet = class {
constructor() {
this.name = 'World';
}
};
Greet = __decorate([
Component({ selector: 'greet', template: 'Hello {{name}}!', directives: [CustomDirective] }),
__metadata('design:paramtypes', [])
], Greet);
// #enddocregion
// #docregion attributeFactory
let Page = class {
constructor(title) {
this.title = title;
}
};
Page = __decorate([
Component({ selector: 'page', template: 'Title: {{title}}' }),
__param(0, Attribute('title')),
__metadata('design:paramtypes', [String])
], Page);
// #enddocregion
// #docregion attributeMetadata
let InputAttrDirective = class {
constructor(type) {
// type would be 'text' in this example
}
};
InputAttrDirective = __decorate([
Directive({ selector: 'input' }),
__param(0, Attribute('type')),
__metadata('design:paramtypes', [String])
], InputAttrDirective);
// #enddocregion
// #docregion directive
let InputDirective = class {
constructor() {
// Add some logic.
}
};
InputDirective = __decorate([
Directive({ selector: 'input' }),
__metadata('design:paramtypes', [])
], InputDirective);
// #enddocregion
// #docregion pipe
let Lowercase = class {
transform(v, args) { return v.toLowerCase(); }
};
Lowercase = __decorate([
Pipe({ name: 'lowercase' }),
__metadata('design:paramtypes', [])
], Lowercase);
// #enddocregion

View File

@ -0,0 +1,22 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component, platform } from 'angular2/core';
import { BROWSER_PROVIDERS, BROWSER_APP_PROVIDERS } from 'angular2/platform/browser';
var appProviders = [];
// #docregion longform
let MyApp = class {
};
MyApp = __decorate([
Component({ selector: 'my-app', template: 'Hello World' }),
__metadata('design:paramtypes', [])
], MyApp);
var app = platform(BROWSER_PROVIDERS).application([BROWSER_APP_PROVIDERS, appProviders]);
app.bootstrap(MyApp);
// #enddocregion

View File

@ -0,0 +1,16 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
export let MyComponent = class {
};
MyComponent = __decorate([
Component({ selector: 'my-component', template: '<h1>My Component</h1>' }),
__metadata('design:paramtypes', [])
], MyComponent);

View File

@ -0,0 +1,6 @@
import { enableProdMode } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
import { MyComponent } from './my_component';
enableProdMode();
bootstrap(MyComponent);
// #enddocregion

View File

@ -0,0 +1,7 @@
import { Observable } from 'rxjs/Rx';
var obs = new Observable((obs) => {
var i = 0;
setInterval(() => { obs.next(++i); }, 1000);
});
obs.subscribe(i => console.log(`${i} seconds elapsed`));
// #enddocregion

View File

@ -0,0 +1,2 @@
import 'rxjs';
// #enddocregion

View File

@ -0,0 +1,8 @@
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
var obs = new Observable((obs) => {
var i = 0;
setInterval(() => obs.next(++i), 1000);
});
obs.map((i) => `${i} seconds elapsed`).subscribe(msg => console.log(msg));
// #enddocregion

View File

@ -0,0 +1,8 @@
import { Observable } from 'rxjs/Rx';
import { map } from 'rxjs/operator/map';
var obs = new Observable((sub) => {
var i = 0;
setInterval(() => sub.next(++i), 1000);
});
map.call(obs, (i) => `${i} seconds elapsed`).subscribe((msg) => console.log(msg));
// #enddocregion

View File

@ -0,0 +1,13 @@
import { By } from 'angular2/platform/browser';
var debugElement;
class MyDirective {
}
// #docregion by_all
debugElement.query(By.all());
// #enddocregion
// #docregion by_css
debugElement.query(By.css('[attribute]'));
// #enddocregion
// #docregion by_directive
debugElement.query(By.directive(MyDirective));
// #enddocregion

View File

@ -0,0 +1,20 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component } from 'angular2/core';
import { bootstrap, ELEMENT_PROBE_PROVIDERS } from 'angular2/platform/browser';
let MyAppComponent = class {
};
MyAppComponent = __decorate([
Component({ selector: 'my-component' }),
__metadata('design:paramtypes', [])
], MyAppComponent);
// #docregion providers
bootstrap(MyAppComponent, [ELEMENT_PROBE_PROVIDERS]);
// #enddocregion

View File

@ -0,0 +1,60 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { provide, Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
import { CanActivate, RouteConfig, APP_BASE_HREF, ROUTER_DIRECTIVES } from 'angular2/router';
function checkIfWeHavePermission(instruction) {
return instruction.params['id'] == '1';
}
// #docregion canActivate
let ControlPanelCmp = class {
};
ControlPanelCmp = __decorate([
Component({ selector: 'control-panel-cmp', template: `<div>Settings: ...</div>` }),
CanActivate(checkIfWeHavePermission),
__metadata('design:paramtypes', [])
], ControlPanelCmp);
// #enddocregion
let HomeCmp = class {
};
HomeCmp = __decorate([
Component({
selector: 'home-cmp',
template: `
<h1>Welcome Home!</h1>
<div>
Edit <a [routerLink]="['/ControlPanelCmp', {id: 1}]" id="user-1-link">User 1</a> |
Edit <a [routerLink]="['/ControlPanelCmp', {id: 2}]" id="user-2-link">User 2</a>
</div>
`,
directives: [ROUTER_DIRECTIVES]
}),
__metadata('design:paramtypes', [])
], HomeCmp);
let AppCmp = class {
};
AppCmp = __decorate([
Component({
selector: 'example-app',
template: `
<h1>My App</h1>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
}),
RouteConfig([
{ path: '/user-settings/:id', component: ControlPanelCmp, name: 'ControlPanelCmp' },
{ path: '/', component: HomeCmp, name: 'HomeCmp' }
]),
__metadata('design:paramtypes', [])
], AppCmp);
export function main() {
return bootstrap(AppCmp, [provide(APP_BASE_HREF, { useValue: '/angular2/examples/router/ts/can_activate' })]);
}

View File

@ -0,0 +1,26 @@
import { verifyNoBrowserErrors, browser } from 'angular2/src/testing/e2e_util';
import { expect } from 'angular2/testing';
function waitForElement(selector) {
var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be present on the dom.
browser.wait(EC.presenceOf($(selector)), 20000);
}
describe('reuse example app', function () {
afterEach(verifyNoBrowserErrors);
var URL = 'angular2/examples/router/ts/can_activate/';
it('should navigate to user 1', function () {
browser.get(URL);
waitForElement('home-cmp');
element(by.css('#user-1-link')).click();
waitForElement('control-panel-cmp');
expect(browser.getCurrentUrl()).toMatch(/\/user-settings\/1$/);
expect(element(by.css('control-panel-cmp')).getText()).toContain('Settings');
});
it('should not navigate to user 2', function () {
browser.get(URL);
waitForElement('home-cmp');
element(by.css('#user-2-link')).click();
waitForElement('home-cmp');
expect(element(by.css('home-cmp')).getText()).toContain('Welcome Home!');
});
});

View File

@ -0,0 +1,69 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { provide, Component } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
import { RouteConfig, RouteParams, ROUTER_DIRECTIVES, APP_BASE_HREF } from 'angular2/router';
// #docregion routerCanDeactivate
let NoteCmp = class {
constructor(params) {
this.id = params.get('id');
}
routerCanDeactivate(next, prev) {
return confirm('Are you sure you want to leave?');
}
};
NoteCmp = __decorate([
Component({
selector: 'note-cmp',
template: `
<div>
<h2>id: {{id}}</h2>
<textarea cols="40" rows="10"></textarea>
</div>`
}),
__metadata('design:paramtypes', [RouteParams])
], NoteCmp);
// #enddocregion
let NoteIndexCmp = class {
};
NoteIndexCmp = __decorate([
Component({
selector: 'note-index-cmp',
template: `
<h1>Your Notes</h1>
<div>
Edit <a [routerLink]="['/NoteCmp', {id: 1}]" id="note-1-link">Note 1</a> |
Edit <a [routerLink]="['/NoteCmp', {id: 2}]" id="note-2-link">Note 2</a>
</div>
`,
directives: [ROUTER_DIRECTIVES]
}),
__metadata('design:paramtypes', [])
], NoteIndexCmp);
let AppCmp = class {
};
AppCmp = __decorate([
Component({
selector: 'example-app',
template: `
<h1>My App</h1>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
}),
RouteConfig([
{ path: '/note/:id', component: NoteCmp, name: 'NoteCmp' },
{ path: '/', component: NoteIndexCmp, name: 'NoteIndexCmp' }
]),
__metadata('design:paramtypes', [])
], AppCmp);
export function main() {
return bootstrap(AppCmp, [provide(APP_BASE_HREF, { useValue: '/angular2/examples/router/ts/can_deactivate' })]);
}

View File

@ -0,0 +1,36 @@
import { verifyNoBrowserErrors, browser } from 'angular2/src/testing/e2e_util';
import { expect } from 'angular2/testing';
function waitForElement(selector) {
var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be present on the dom.
browser.wait(EC.presenceOf($(selector)), 20000);
}
function waitForAlert() {
var EC = protractor.ExpectedConditions;
browser.wait(EC.alertIsPresent(), 1000);
}
describe('can deactivate example app', function () {
afterEach(verifyNoBrowserErrors);
var URL = 'angular2/examples/router/ts/can_deactivate/';
it('should not navigate away when prompt is cancelled', function () {
browser.get(URL);
waitForElement('note-index-cmp');
element(by.css('#note-1-link')).click();
waitForElement('note-cmp');
browser.navigate().back();
waitForAlert();
browser.switchTo().alert().dismiss(); // Use to simulate cancel button
expect(element(by.css('note-cmp')).getText()).toContain('id: 1');
});
it('should navigate away when prompt is confirmed', function () {
browser.get(URL);
waitForElement('note-index-cmp');
element(by.css('#note-1-link')).click();
waitForElement('note-cmp');
browser.navigate().back();
waitForAlert();
browser.switchTo().alert().accept();
waitForElement('note-index-cmp');
expect(element(by.css('note-index-cmp')).getText()).toContain('Your Notes');
});
});

View File

@ -0,0 +1,63 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component, provide } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
import { RouteConfig, ROUTER_DIRECTIVES, APP_BASE_HREF } from 'angular2/router';
// #docregion routerOnActivate
let ChildCmp = class {
};
ChildCmp = __decorate([
Component({ template: `Child` }),
__metadata('design:paramtypes', [])
], ChildCmp);
let ParentCmp = class {
constructor() {
this.log = '';
}
routerOnActivate(next, prev) {
this.log = `Finished navigating from "${prev ? prev.urlPath : 'null'}" to "${next.urlPath}"`;
return new Promise(resolve => {
// The ChildCmp gets instantiated only when the Promise is resolved
setTimeout(() => resolve(null), 1000);
});
}
};
ParentCmp = __decorate([
Component({
template: `
<h2>Parent</h2> (<router-outlet></router-outlet>)
<p>{{log}}</p>`,
directives: [ROUTER_DIRECTIVES]
}),
RouteConfig([{ path: '/child', name: 'Child', component: ChildCmp }]),
__metadata('design:paramtypes', [])
], ParentCmp);
// #enddocregion
export let AppCmp = class {
};
AppCmp = __decorate([
Component({
selector: 'example-app',
template: `
<h1>My app</h1>
<nav>
<a [routerLink]="['Parent', 'Child']">Child</a>
</nav>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
}),
RouteConfig([{ path: '/parent/...', name: 'Parent', component: ParentCmp }]),
__metadata('design:paramtypes', [])
], AppCmp);
export function main() {
return bootstrap(AppCmp, [provide(APP_BASE_HREF, { useValue: '/angular2/examples/router/ts/on_activate' })]);
}

View File

@ -0,0 +1,70 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component, Injectable, provide } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
import { RouteConfig, ROUTER_DIRECTIVES, APP_BASE_HREF } from 'angular2/router';
let LogService = class {
constructor() {
this.logs = [];
}
addLog(message) { this.logs.push(message); }
};
LogService = __decorate([
Injectable(),
__metadata('design:paramtypes', [])
], LogService);
// #docregion routerOnDeactivate
let MyCmp = class {
constructor(logService) {
this.logService = logService;
}
routerOnDeactivate(next, prev) {
this.logService.addLog(`Navigating from "${prev ? prev.urlPath : 'null'}" to "${next.urlPath}"`);
}
};
MyCmp = __decorate([
Component({ selector: 'my-cmp', template: `<div>hello</div>` }),
__metadata('design:paramtypes', [LogService])
], MyCmp);
// #enddocregion
let AppCmp = class {
constructor(logService) {
this.logService = logService;
}
};
AppCmp = __decorate([
Component({
selector: 'example-app',
template: `
<h1>My App</h1>
<nav>
<a [routerLink]="['/HomeCmp']" id="home-link">Navigate Home</a> |
<a [routerLink]="['/ParamCmp', {param: 1}]" id="param-link">Navigate with a Param</a>
</nav>
<router-outlet></router-outlet>
<div id="log">
<h2>Log:</h2>
<p *ngFor="#logItem of logService.logs">{{ logItem }}</p>
</div>
`,
directives: [ROUTER_DIRECTIVES]
}),
RouteConfig([
{ path: '/', component: MyCmp, name: 'HomeCmp' },
{ path: '/:param', component: MyCmp, name: 'ParamCmp' }
]),
__metadata('design:paramtypes', [LogService])
], AppCmp);
export function main() {
return bootstrap(AppCmp, [
provide(APP_BASE_HREF, { useValue: '/angular2/examples/router/ts/on_deactivate' }),
LogService
]);
}

View File

@ -0,0 +1,23 @@
import { verifyNoBrowserErrors, browser } from 'angular2/src/testing/e2e_util';
import { expect } from 'angular2/testing';
function waitForElement(selector) {
var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be present on the dom.
browser.wait(EC.presenceOf($(selector)), 20000);
}
describe('on activate example app', function () {
afterEach(verifyNoBrowserErrors);
var URL = 'angular2/examples/router/ts/on_deactivate/';
it('should update the text when navigating between routes', function () {
browser.get(URL);
waitForElement('my-cmp');
expect(element(by.css('#log')).getText()).toEqual('Log:');
element(by.css('#param-link')).click();
waitForElement('my-cmp');
expect(element(by.css('#log')).getText()).toEqual('Log:\nNavigating from "" to "1"');
browser.navigate().back();
waitForElement('my-cmp');
expect(element(by.css('#log')).getText())
.toEqual('Log:\nNavigating from "" to "1"\nNavigating from "1" to ""');
});
});

View File

@ -0,0 +1,55 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component, provide } from 'angular2/core';
import { bootstrap } from 'angular2/platform/browser';
import { RouteConfig, ROUTER_DIRECTIVES, APP_BASE_HREF, RouteParams } from 'angular2/router';
// #docregion reuseCmp
let MyCmp = class {
constructor(params) {
this.name = params.get('name') || 'NOBODY';
}
routerCanReuse(next, prev) { return true; }
routerOnReuse(next, prev) {
this.name = next.params['name'];
}
};
MyCmp = __decorate([
Component({
selector: 'my-cmp',
template: `
<div>hello {{name}}!</div>
<div>message: <input id="message"></div>
`
}),
__metadata('design:paramtypes', [RouteParams])
], MyCmp);
// #enddocregion
let AppCmp = class {
};
AppCmp = __decorate([
Component({
selector: 'example-app',
template: `
<h1>Say hi to...</h1>
<a [routerLink]="['/HomeCmp', {name: 'naomi'}]" id="naomi-link">Naomi</a> |
<a [routerLink]="['/HomeCmp', {name: 'brad'}]" id="brad-link">Brad</a>
<router-outlet></router-outlet>
`,
directives: [ROUTER_DIRECTIVES]
}),
RouteConfig([
{ path: '/', component: MyCmp, name: 'HomeCmp' },
{ path: '/:name', component: MyCmp, name: 'HomeCmp' }
]),
__metadata('design:paramtypes', [])
], AppCmp);
export function main() {
return bootstrap(AppCmp, [provide(APP_BASE_HREF, { useValue: '/angular2/examples/router/ts/reuse' })]);
}

View File

@ -0,0 +1,26 @@
import { verifyNoBrowserErrors, browser } from 'angular2/src/testing/e2e_util';
import { expect } from 'angular2/testing';
function waitForElement(selector) {
var EC = protractor.ExpectedConditions;
// Waits for the element with id 'abc' to be present on the dom.
browser.wait(EC.presenceOf($(selector)), 20000);
}
describe('reuse example app', function () {
afterEach(verifyNoBrowserErrors);
var URL = 'angular2/examples/router/ts/reuse/';
it('should build a link which points to the detail page', function () {
browser.get(URL);
waitForElement('my-cmp');
element(by.css('#naomi-link')).click();
waitForElement('my-cmp');
expect(browser.getCurrentUrl()).toMatch(/\/naomi$/);
// type something into input
element(by.css('#message')).sendKeys('long time no see!');
// navigate to Brad
element(by.css('#brad-link')).click();
waitForElement('my-cmp');
expect(browser.getCurrentUrl()).toMatch(/\/brad$/);
// check that typed input is the same
expect(element(by.css('#message')).getAttribute('value')).toEqual('long time no see!');
});
});

View File

@ -0,0 +1,26 @@
import { describe, it, fakeAsync, expect, tick, clearPendingTimers } from 'angular2/testing';
// #docregion basic
describe('this test', () => {
it('looks async but is synchronous', fakeAsync(() => {
var flag = false;
setTimeout(() => { flag = true; }, 100);
expect(flag).toBe(false);
tick(50);
expect(flag).toBe(false);
tick(50);
expect(flag).toBe(true);
}));
});
// #enddocregion
// #docregion pending
describe('this test', () => {
it('aborts a timer', fakeAsync(() => {
// This timer is scheduled but doesn't need to complete for the
// test to pass (maybe it's a timeout for some operation).
// Leaving it will cause the test to fail...
setTimeout(() => { }, 100);
// Unless we clean it up first.
clearPendingTimers();
}));
});
// #enddocregion

View File

@ -0,0 +1,32 @@
import { expect } from 'angular2/testing';
var value;
var element;
var exception;
class OtherClass {
}
class SomeClass {
}
// #docregion toBePromise
expect(value).toBePromise();
// #enddocregion
// #docregion toBeAnInstanceOf
expect(value).toBeAnInstanceOf(SomeClass);
// #enddocregion
// #docregion toHaveText
expect(element).toHaveText('Hello world!');
// #enddocregion
// #docregion toHaveCssClass
expect(element).toHaveCssClass('current');
// #enddocregion
// #docregion toHaveCssStyle
expect(element).toHaveCssStyle({ width: '100px', height: 'auto' });
// #enddocregion
// #docregion toContainError
expect(exception).toContainError('Failed to load');
// #enddocregion
// #docregion toThrowErrorWith
expect(() => { throw 'Failed to load'; }).toThrowErrorWith('Failed to load');
// #enddocregion
// #docregion toImplement
expect(SomeClass).toImplement(OtherClass);
// #enddocregion

View File

@ -0,0 +1,71 @@
import { describe, fdescribe, xdescribe, it, fit, xit, beforeEach, afterEach, beforeEachProviders, inject } from 'angular2/testing';
import { provide } from 'angular2/core';
var db;
class MyService {
}
class MyMockService {
}
// #docregion describeIt
describe('some component', () => {
it('does something', () => {
// This is a test.
});
});
// #enddocregion
// #docregion fdescribe
fdescribe('some component', () => {
it('has a test', () => {
// This test will run.
});
});
describe('another component', () => { it('also has a test', () => { throw 'This test will not run.'; }); });
// #enddocregion
// #docregion xdescribe
xdescribe('some component', () => { it('has a test', () => { throw 'This test will not run.'; }); });
describe('another component', () => {
it('also has a test', () => {
// This test will run.
});
});
// #enddocregion
// #docregion fit
describe('some component', () => {
fit('has a test', () => {
// This test will run.
});
it('has another test', () => { throw 'This test will not run.'; });
});
// #enddocregion
// #docregion xit
describe('some component', () => {
xit('has a test', () => { throw 'This test will not run.'; });
it('has another test', () => {
// This test will run.
});
});
// #enddocregion
// #docregion beforeEach
describe('some component', () => {
beforeEach(() => { db.connect(); });
it('uses the db', () => {
// Database is connected.
});
});
// #enddocregion
// #docregion beforeEachProviders
describe('some component', () => {
beforeEachProviders(() => [provide(MyService, { useClass: MyMockService })]);
it('uses MyService', inject([MyService], (service) => {
// service is an instance of MyMockService.
}));
});
// #enddocregion
// #docregion afterEach
describe('some component', () => {
afterEach((done) => { db.reset().then((_) => done()); });
it('uses the db', () => {
// This test can leave the database in a dirty state.
// The afterEach will ensure it gets reset.
});
});
// #enddocregion

280
node_modules/angular2/es6/prod/http.js generated vendored Normal file
View File

@ -0,0 +1,280 @@
import { provide } from 'angular2/core';
import { Http, Jsonp } from './src/http/http';
import { XHRBackend } from './src/http/backends/xhr_backend';
import { JSONPBackend, JSONPBackend_ } from './src/http/backends/jsonp_backend';
import { BrowserXhr } from './src/http/backends/browser_xhr';
import { BrowserJsonp } from './src/http/backends/browser_jsonp';
import { BaseRequestOptions, RequestOptions } from './src/http/base_request_options';
import { BaseResponseOptions, ResponseOptions } from './src/http/base_response_options';
export { Request } from './src/http/static_request';
export { Response } from './src/http/static_response';
export { Connection, ConnectionBackend } from './src/http/interfaces';
export { BrowserXhr } from './src/http/backends/browser_xhr';
export { BaseRequestOptions, RequestOptions } from './src/http/base_request_options';
export { BaseResponseOptions, ResponseOptions } from './src/http/base_response_options';
export { XHRBackend, XHRConnection } from './src/http/backends/xhr_backend';
export { JSONPBackend, JSONPConnection } from './src/http/backends/jsonp_backend';
export { Http, Jsonp } from './src/http/http';
export { Headers } from './src/http/headers';
export { ResponseType, ReadyState, RequestMethod } from './src/http/enums';
export { URLSearchParams } from './src/http/url_search_params';
/**
* Provides a basic set of injectables to use the {@link Http} service in any application.
*
* The `HTTP_PROVIDERS` should be included either in a component's injector,
* or in the root injector when bootstrapping an application.
*
* ### Example ([live demo](http://plnkr.co/edit/snj7Nv?p=preview))
*
* ```
* import {Component} from 'angular2/core';
* import {bootstrap} from 'angular2/platform/browser';
* import {NgFor} from 'angular2/common';
* import {HTTP_PROVIDERS, Http} from 'angular2/http';
*
* @Component({
* selector: 'app',
* providers: [HTTP_PROVIDERS],
* template: `
* <div>
* <h1>People</h1>
* <ul>
* <li *ngFor="#person of people">
* {{person.name}}
* </li>
* </ul>
* </div>
* `,
* directives: [NgFor]
* })
* export class App {
* people: Object[];
* constructor(http:Http) {
* http.get('people.json').subscribe(res => {
* this.people = res.json();
* });
* }
* active:boolean = false;
* toggleActiveState() {
* this.active = !this.active;
* }
* }
*
* bootstrap(App)
* .catch(err => console.error(err));
* ```
*
* The primary public API included in `HTTP_PROVIDERS` is the {@link Http} class.
* However, other providers required by `Http` are included,
* which may be beneficial to override in certain cases.
*
* The providers included in `HTTP_PROVIDERS` include:
* * {@link Http}
* * {@link XHRBackend}
* * `BrowserXHR` - Private factory to create `XMLHttpRequest` instances
* * {@link RequestOptions} - Bound to {@link BaseRequestOptions} class
* * {@link ResponseOptions} - Bound to {@link BaseResponseOptions} class
*
* There may be cases where it makes sense to extend the base request options,
* such as to add a search string to be appended to all URLs.
* To accomplish this, a new provider for {@link RequestOptions} should
* be added in the same injector as `HTTP_PROVIDERS`.
*
* ### Example ([live demo](http://plnkr.co/edit/aCMEXi?p=preview))
*
* ```
* import {provide} from 'angular2/core';
* import {bootstrap} from 'angular2/platform/browser';
* import {HTTP_PROVIDERS, BaseRequestOptions, RequestOptions} from 'angular2/http';
*
* class MyOptions extends BaseRequestOptions {
* search: string = 'coreTeam=true';
* }
*
* bootstrap(App, [HTTP_PROVIDERS, provide(RequestOptions, {useClass: MyOptions})])
* .catch(err => console.error(err));
* ```
*
* Likewise, to use a mock backend for unit tests, the {@link XHRBackend}
* provider should be bound to {@link MockBackend}.
*
* ### Example ([live demo](http://plnkr.co/edit/7LWALD?p=preview))
*
* ```
* import {provide} from 'angular2/core';
* import {bootstrap} from 'angular2/platform/browser';
* import {HTTP_PROVIDERS, Http, Response, XHRBackend} from 'angular2/http';
* import {MockBackend} from 'angular2/http/testing';
*
* var people = [{name: 'Jeff'}, {name: 'Tobias'}];
*
* var injector = Injector.resolveAndCreate([
* HTTP_PROVIDERS,
* MockBackend,
* provide(XHRBackend, {useExisting: MockBackend})
* ]);
* var http = injector.get(Http);
* var backend = injector.get(MockBackend);
*
* // Listen for any new requests
* backend.connections.observer({
* next: connection => {
* var response = new Response({body: people});
* setTimeout(() => {
* // Send a response to the request
* connection.mockRespond(response);
* });
* }
* });
*
* http.get('people.json').observer({
* next: res => {
* // Response came from mock backend
* console.log('first person', res.json()[0].name);
* }
* });
* ```
*/
export const HTTP_PROVIDERS = [
// TODO(pascal): use factory type annotations once supported in DI
// issue: https://github.com/angular/angular/issues/3183
provide(Http, {
useFactory: (xhrBackend, requestOptions) => new Http(xhrBackend, requestOptions),
deps: [XHRBackend, RequestOptions]
}),
BrowserXhr,
provide(RequestOptions, { useClass: BaseRequestOptions }),
provide(ResponseOptions, { useClass: BaseResponseOptions }),
XHRBackend
];
/**
* See {@link HTTP_PROVIDERS} instead.
*
* @deprecated
*/
export const HTTP_BINDINGS = HTTP_PROVIDERS;
/**
* Provides a basic set of providers to use the {@link Jsonp} service in any application.
*
* The `JSONP_PROVIDERS` should be included either in a component's injector,
* or in the root injector when bootstrapping an application.
*
* ### Example ([live demo](http://plnkr.co/edit/vmeN4F?p=preview))
*
* ```
* import {Component} from 'angular2/core';
* import {NgFor} from 'angular2/common';
* import {JSONP_PROVIDERS, Jsonp} from 'angular2/http';
*
* @Component({
* selector: 'app',
* providers: [JSONP_PROVIDERS],
* template: `
* <div>
* <h1>People</h1>
* <ul>
* <li *ngFor="#person of people">
* {{person.name}}
* </li>
* </ul>
* </div>
* `,
* directives: [NgFor]
* })
* export class App {
* people: Array<Object>;
* constructor(jsonp:Jsonp) {
* jsonp.request('people.json').subscribe(res => {
* this.people = res.json();
* })
* }
* }
* ```
*
* The primary public API included in `JSONP_PROVIDERS` is the {@link Jsonp} class.
* However, other providers required by `Jsonp` are included,
* which may be beneficial to override in certain cases.
*
* The providers included in `JSONP_PROVIDERS` include:
* * {@link Jsonp}
* * {@link JSONPBackend}
* * `BrowserJsonp` - Private factory
* * {@link RequestOptions} - Bound to {@link BaseRequestOptions} class
* * {@link ResponseOptions} - Bound to {@link BaseResponseOptions} class
*
* There may be cases where it makes sense to extend the base request options,
* such as to add a search string to be appended to all URLs.
* To accomplish this, a new provider for {@link RequestOptions} should
* be added in the same injector as `JSONP_PROVIDERS`.
*
* ### Example ([live demo](http://plnkr.co/edit/TFug7x?p=preview))
*
* ```
* import {provide} from 'angular2/core';
* import {bootstrap} from 'angular2/platform/browser';
* import {JSONP_PROVIDERS, BaseRequestOptions, RequestOptions} from 'angular2/http';
*
* class MyOptions extends BaseRequestOptions {
* search: string = 'coreTeam=true';
* }
*
* bootstrap(App, [JSONP_PROVIDERS, provide(RequestOptions, {useClass: MyOptions})])
* .catch(err => console.error(err));
* ```
*
* Likewise, to use a mock backend for unit tests, the {@link JSONPBackend}
* provider should be bound to {@link MockBackend}.
*
* ### Example ([live demo](http://plnkr.co/edit/HDqZWL?p=preview))
*
* ```
* import {provide, Injector} from 'angular2/core';
* import {JSONP_PROVIDERS, Jsonp, Response, JSONPBackend} from 'angular2/http';
* import {MockBackend} from 'angular2/http/testing';
*
* var people = [{name: 'Jeff'}, {name: 'Tobias'}];
* var injector = Injector.resolveAndCreate([
* JSONP_PROVIDERS,
* MockBackend,
* provide(JSONPBackend, {useExisting: MockBackend})
* ]);
* var jsonp = injector.get(Jsonp);
* var backend = injector.get(MockBackend);
*
* // Listen for any new requests
* backend.connections.observer({
* next: connection => {
* var response = new Response({body: people});
* setTimeout(() => {
* // Send a response to the request
* connection.mockRespond(response);
* });
* }
* });
* jsonp.get('people.json').observer({
* next: res => {
* // Response came from mock backend
* console.log('first person', res.json()[0].name);
* }
* });
* ```
*/
export const JSONP_PROVIDERS = [
// TODO(pascal): use factory type annotations once supported in DI
// issue: https://github.com/angular/angular/issues/3183
provide(Jsonp, {
useFactory: (jsonpBackend, requestOptions) => new Jsonp(jsonpBackend, requestOptions),
deps: [JSONPBackend, RequestOptions]
}),
BrowserJsonp,
provide(RequestOptions, { useClass: BaseRequestOptions }),
provide(ResponseOptions, { useClass: BaseResponseOptions }),
provide(JSONPBackend, { useClass: JSONPBackend_ })
];
/**
* See {@link JSONP_PROVIDERS} instead.
*
* @deprecated
*/
export const JSON_BINDINGS = JSONP_PROVIDERS;

1
node_modules/angular2/es6/prod/http/testing.js generated vendored Normal file
View File

@ -0,0 +1 @@
export * from 'angular2/src/http/backends/mock_backend';

9
node_modules/angular2/es6/prod/i18n.js generated vendored Normal file
View File

@ -0,0 +1,9 @@
/**
* @module
* @description
* Entry point to i18n
*/
export * from './src/i18n/message';
export * from './src/i18n/xmb_serializer';
export * from './src/i18n/message_extractor';
export * from './src/i18n/i18n_html_parser';

1
node_modules/angular2/es6/prod/instrumentation.js generated vendored Normal file
View File

@ -0,0 +1 @@
export { wtfCreateScope, wtfLeave, wtfStartTimeRange, wtfEndTimeRange } from './src/core/profile/profile';

17
node_modules/angular2/es6/prod/package.json generated vendored Normal file
View File

@ -0,0 +1,17 @@
{
"name": "angular2",
"version": "<%= packageJson.version %>",
"description": "Angular 2 - a web framework for modern web apps",
"homepage": "<%= packageJson.homepage %>",
"bugs": "<%= packageJson.bugs %>",
"contributors": <%= JSON.stringify(packageJson.contributors) %>,
"license": "<%= packageJson.license %>",
"repository": <%= JSON.stringify(packageJson.repository) %>,
"devDependencies": <%= JSON.stringify(packageJson.defaultDevDependencies) %>,
"peerDependencies": {
"es6-shim": "<%= packageJson.dependencies['es6-shim'] %>",
"reflect-metadata": "<%= packageJson.dependencies['reflect-metadata'] %>",
"rxjs": "<%= packageJson.dependencies['rxjs'] %>",
"zone.js": "<%= packageJson.dependencies['zone.js'] %>"
}
}

91
node_modules/angular2/es6/prod/platform/browser.js generated vendored Normal file
View File

@ -0,0 +1,91 @@
export { AngularEntrypoint } from 'angular2/src/core/angular_entrypoint';
export { BROWSER_PROVIDERS, ELEMENT_PROBE_PROVIDERS, ELEMENT_PROBE_PROVIDERS_PROD_MODE, inspectNativeElement, BrowserDomAdapter, By, Title, DOCUMENT, enableDebugTools, disableDebugTools } from 'angular2/src/platform/browser_common';
import { isPresent, CONST_EXPR } from 'angular2/src/facade/lang';
import { BROWSER_PROVIDERS, BROWSER_APP_COMMON_PROVIDERS } from 'angular2/src/platform/browser_common';
import { COMPILER_PROVIDERS } from 'angular2/compiler';
import { platform, reflector } from 'angular2/core';
import { ReflectionCapabilities } from 'angular2/src/core/reflection/reflection_capabilities';
import { XHRImpl } from "angular2/src/platform/browser/xhr_impl";
import { XHR } from 'angular2/compiler';
import { Provider } from 'angular2/src/core/di';
/**
* An array of providers that should be passed into `application()` when bootstrapping a component.
*/
export const BROWSER_APP_PROVIDERS = CONST_EXPR([
BROWSER_APP_COMMON_PROVIDERS,
COMPILER_PROVIDERS,
new Provider(XHR, { useClass: XHRImpl }),
]);
/**
* Bootstrapping for Angular applications.
*
* You instantiate an Angular application by explicitly specifying a component to use
* as the root component for your application via the `bootstrap()` method.
*
* ## Simple Example
*
* Assuming this `index.html`:
*
* ```html
* <html>
* <!-- load Angular script tags here. -->
* <body>
* <my-app>loading...</my-app>
* </body>
* </html>
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`.
* Unlike Angular 1, Angular 2 does not compile/process providers in `index.html`. This is
* mainly for security reasons, as well as architectural changes in Angular 2. This means
* that `index.html` can safely be processed using server-side technologies such as
* providers. Bindings can thus use double-curly `{{ syntax }}` without collision from
* Angular 2 component double-curly `{{ syntax }}`.
*
* We can use this script code:
*
* {@example core/ts/bootstrap/bootstrap.ts region='bootstrap'}
*
* When the app developer invokes `bootstrap()` with the root component `MyApp` as its
* argument, Angular performs the following tasks:
*
* 1. It uses the component's `selector` property to locate the DOM element which needs
* to be upgraded into the angular component.
* 2. It creates a new child injector (from the platform injector). Optionally, you can
* also override the injector configuration for an app by invoking `bootstrap` with the
* `componentInjectableBindings` argument.
* 3. It creates a new `Zone` and connects it to the angular application's change detection
* domain instance.
* 4. It creates an emulated or shadow DOM on the selected component's host element and loads the
* template into it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data providers for the
* application.
*
*
* ## Bootstrapping Multiple Applications
*
* When working within a browser window, there are many singleton resources: cookies, title,
* location, and others. Angular services that represent these resources must likewise be
* shared across all Angular applications that occupy the same browser window. For this
* reason, Angular creates exactly one global platform object which stores all shared
* services, and each angular application injector has the platform injector as its parent.
*
* Each application has its own private injector as well. When there are multiple
* applications on a page, Angular treats each application injector's services as private
* to that application.
*
* ## API
*
* - `appComponentType`: The root component which should act as the application. This is
* a reference to a `Type` which is annotated with `@Component(...)`.
* - `customProviders`: An additional set of providers that can be added to the
* app injector to override default injection behavior.
*
* Returns a `Promise` of {@link ComponentRef}.
*/
export function bootstrap(appComponentType, customProviders) {
reflector.reflectionCapabilities = new ReflectionCapabilities();
let appProviders = isPresent(customProviders) ? [BROWSER_APP_PROVIDERS, customProviders] : BROWSER_APP_PROVIDERS;
return platform(BROWSER_PROVIDERS).application(appProviders).bootstrap(appComponentType);
}

View File

@ -0,0 +1,21 @@
export { AngularEntrypoint } from 'angular2/src/core/angular_entrypoint';
export { BROWSER_PROVIDERS, ELEMENT_PROBE_PROVIDERS, ELEMENT_PROBE_PROVIDERS_PROD_MODE, inspectNativeElement, BrowserDomAdapter, By, Title, enableDebugTools, disableDebugTools } from 'angular2/src/platform/browser_common';
import { isPresent } from 'angular2/src/facade/lang';
import { BROWSER_PROVIDERS, BROWSER_APP_COMMON_PROVIDERS } from 'angular2/src/platform/browser_common';
import { platform } from 'angular2/core';
/**
* An array of providers that should be passed into `application()` when bootstrapping a component
* when all templates
* have been precompiled offline.
*/
export const BROWSER_APP_PROVIDERS = BROWSER_APP_COMMON_PROVIDERS;
/**
* See {@link bootstrap} for more information.
*/
export function bootstrapStatic(appComponentType, customProviders, initReflector) {
if (isPresent(initReflector)) {
initReflector();
}
let appProviders = isPresent(customProviders) ? [BROWSER_APP_PROVIDERS, customProviders] : BROWSER_APP_PROVIDERS;
return platform(BROWSER_PROVIDERS).application(appProviders).bootstrap(appComponentType);
}

11
node_modules/angular2/es6/prod/platform/common_dom.js generated vendored Normal file
View File

@ -0,0 +1,11 @@
/**
* This is a set of classes and objects that can be used both in the browser and on the server.
*/
export { DOM, setRootDomAdapter, DomAdapter } from 'angular2/src/platform/dom/dom_adapter';
export { DomRenderer } from 'angular2/src/platform/dom/dom_renderer';
export { DOCUMENT } from 'angular2/src/platform/dom/dom_tokens';
export { SharedStylesHost, DomSharedStylesHost } from 'angular2/src/platform/dom/shared_styles_host';
export { DomEventsPlugin } from 'angular2/src/platform/dom/events/dom_events';
export { EVENT_MANAGER_PLUGINS, EventManager, EventManagerPlugin } from 'angular2/src/platform/dom/events/event_manager';
export * from 'angular2/src/platform/dom/debug/by';
export * from 'angular2/src/platform/dom/debug/ng_probe';

2
node_modules/angular2/es6/prod/platform/server.js generated vendored Normal file
View File

@ -0,0 +1,2 @@
// TODO: vsavkin add SERVER_PROVIDERS and SERVER_APP_PROVIDERS
export { Parse5DomAdapter } from 'angular2/src/platform/server/parse5_adapter';

View File

@ -0,0 +1,11 @@
import { TEST_BROWSER_STATIC_PLATFORM_PROVIDERS, ADDITIONAL_TEST_BROWSER_PROVIDERS } from 'angular2/platform/testing/browser_static';
import { BROWSER_APP_PROVIDERS } from 'angular2/platform/browser';
import { CONST_EXPR } from 'angular2/src/facade/lang';
/**
* Default patform providers for testing.
*/
export const TEST_BROWSER_PLATFORM_PROVIDERS = CONST_EXPR([TEST_BROWSER_STATIC_PLATFORM_PROVIDERS]);
/**
* Default application providers for testing.
*/
export const TEST_BROWSER_APPLICATION_PROVIDERS = CONST_EXPR([BROWSER_APP_PROVIDERS, ADDITIONAL_TEST_BROWSER_PROVIDERS]);

View File

@ -0,0 +1,47 @@
import { APP_ID, DirectiveResolver, NgZone, Provider, ViewResolver, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER } from 'angular2/core';
import { BROWSER_APP_COMMON_PROVIDERS } from 'angular2/src/platform/browser_common';
import { BrowserDomAdapter } from 'angular2/src/platform/browser/browser_adapter';
import { AnimationBuilder } from 'angular2/src/animate/animation_builder';
import { MockAnimationBuilder } from 'angular2/src/mock/animation_builder_mock';
import { MockDirectiveResolver } from 'angular2/src/mock/directive_resolver_mock';
import { MockViewResolver } from 'angular2/src/mock/view_resolver_mock';
import { MockLocationStrategy } from 'angular2/src/mock/mock_location_strategy';
import { LocationStrategy } from 'angular2/src/router/location/location_strategy';
import { MockNgZone } from 'angular2/src/mock/ng_zone_mock';
import { XHRImpl } from "angular2/src/platform/browser/xhr_impl";
import { XHR } from 'angular2/compiler';
import { TestComponentBuilder } from 'angular2/src/testing/test_component_builder';
import { BrowserDetection } from 'angular2/src/testing/utils';
import { ELEMENT_PROBE_PROVIDERS } from 'angular2/platform/common_dom';
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { Log } from 'angular2/src/testing/utils';
function initBrowserTests() {
BrowserDomAdapter.makeCurrent();
BrowserDetection.setup();
}
/**
* Default patform providers for testing without a compiler.
*/
export const TEST_BROWSER_STATIC_PLATFORM_PROVIDERS = CONST_EXPR([
PLATFORM_COMMON_PROVIDERS,
new Provider(PLATFORM_INITIALIZER, { useValue: initBrowserTests, multi: true })
]);
export const ADDITIONAL_TEST_BROWSER_PROVIDERS = CONST_EXPR([
new Provider(APP_ID, { useValue: 'a' }),
ELEMENT_PROBE_PROVIDERS,
new Provider(DirectiveResolver, { useClass: MockDirectiveResolver }),
new Provider(ViewResolver, { useClass: MockViewResolver }),
Log,
TestComponentBuilder,
new Provider(NgZone, { useClass: MockNgZone }),
new Provider(LocationStrategy, { useClass: MockLocationStrategy }),
new Provider(AnimationBuilder, { useClass: MockAnimationBuilder }),
]);
/**
* Default application providers for testing without a compiler.
*/
export const TEST_BROWSER_STATIC_APPLICATION_PROVIDERS = CONST_EXPR([
BROWSER_APP_COMMON_PROVIDERS,
new Provider(XHR, { useClass: XHRImpl }),
ADDITIONAL_TEST_BROWSER_PROVIDERS
]);

View File

@ -0,0 +1,66 @@
import { APP_ID, DirectiveResolver, NgZone, Provider, ViewResolver, PLATFORM_COMMON_PROVIDERS, PLATFORM_INITIALIZER, APPLICATION_COMMON_PROVIDERS } from 'angular2/core';
import { Parse5DomAdapter } from 'angular2/src/platform/server/parse5_adapter';
import { AnimationBuilder } from 'angular2/src/animate/animation_builder';
import { MockAnimationBuilder } from 'angular2/src/mock/animation_builder_mock';
import { MockDirectiveResolver } from 'angular2/src/mock/directive_resolver_mock';
import { MockViewResolver } from 'angular2/src/mock/view_resolver_mock';
import { MockLocationStrategy } from 'angular2/src/mock/mock_location_strategy';
import { LocationStrategy } from 'angular2/src/router/location/location_strategy';
import { MockNgZone } from 'angular2/src/mock/ng_zone_mock';
import { TestComponentBuilder } from 'angular2/src/testing/test_component_builder';
import { XHR } from 'angular2/src/compiler/xhr';
import { BrowserDetection } from 'angular2/src/testing/utils';
import { COMPILER_PROVIDERS } from 'angular2/src/compiler/compiler';
import { DOCUMENT } from 'angular2/src/platform/dom/dom_tokens';
import { DOM } from 'angular2/src/platform/dom/dom_adapter';
import { RootRenderer } from 'angular2/src/core/render/api';
import { DomRootRenderer, DomRootRenderer_ } from 'angular2/src/platform/dom/dom_renderer';
import { DomSharedStylesHost } from 'angular2/src/platform/dom/shared_styles_host';
import { EventManager, EVENT_MANAGER_PLUGINS, ELEMENT_PROBE_PROVIDERS } from 'angular2/platform/common_dom';
import { DomEventsPlugin } from 'angular2/src/platform/dom/events/dom_events';
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { Log } from 'angular2/src/testing/utils';
function initServerTests() {
Parse5DomAdapter.makeCurrent();
BrowserDetection.setup();
}
/**
* Default patform providers for testing.
*/
export const TEST_SERVER_PLATFORM_PROVIDERS = CONST_EXPR([
PLATFORM_COMMON_PROVIDERS,
new Provider(PLATFORM_INITIALIZER, { useValue: initServerTests, multi: true })
]);
function appDoc() {
try {
return DOM.defaultDoc();
}
catch (e) {
return null;
}
}
/**
* Default application providers for testing.
*/
export const TEST_SERVER_APPLICATION_PROVIDERS = CONST_EXPR([
// TODO(julie): when angular2/platform/server is available, use that instead of making our own
// list here.
APPLICATION_COMMON_PROVIDERS,
COMPILER_PROVIDERS,
new Provider(DOCUMENT, { useFactory: appDoc }),
new Provider(DomRootRenderer, { useClass: DomRootRenderer_ }),
new Provider(RootRenderer, { useExisting: DomRootRenderer }),
EventManager,
new Provider(EVENT_MANAGER_PLUGINS, { useClass: DomEventsPlugin, multi: true }),
new Provider(XHR, { useClass: XHR }),
new Provider(APP_ID, { useValue: 'a' }),
DomSharedStylesHost,
ELEMENT_PROBE_PROVIDERS,
new Provider(DirectiveResolver, { useClass: MockDirectiveResolver }),
new Provider(ViewResolver, { useClass: MockViewResolver }),
Log,
TestComponentBuilder,
new Provider(NgZone, { useClass: MockNgZone }),
new Provider(LocationStrategy, { useClass: MockLocationStrategy }),
new Provider(AnimationBuilder, { useClass: MockAnimationBuilder }),
]);

View File

@ -0,0 +1,8 @@
export { WORKER_APP_PLATFORM, WORKER_APP_APPLICATION_COMMON } from 'angular2/src/platform/worker_app_common';
export { WORKER_APP_APPLICATION } from 'angular2/src/platform/worker_app';
export { ClientMessageBroker, ClientMessageBrokerFactory, FnArg, UiArguments } from 'angular2/src/web_workers/shared/client_message_broker';
export { ReceivedMessage, ServiceMessageBroker, ServiceMessageBrokerFactory } from 'angular2/src/web_workers/shared/service_message_broker';
export { PRIMITIVE } from 'angular2/src/web_workers/shared/serializer';
export * from 'angular2/src/web_workers/shared/message_bus';
export { AngularEntrypoint } from 'angular2/src/core/angular_entrypoint';
export { WORKER_APP_ROUTER } from 'angular2/src/web_workers/worker/router_providers';

View File

@ -0,0 +1,12 @@
export { WORKER_SCRIPT, WORKER_RENDER_PLATFORM, initializeGenericWorkerRenderer, WORKER_RENDER_APPLICATION_COMMON } from 'angular2/src/platform/worker_render_common';
export { WORKER_RENDER_APPLICATION, WebWorkerInstance } from 'angular2/src/platform/worker_render';
export { ClientMessageBroker, ClientMessageBrokerFactory, FnArg, UiArguments } from '../src/web_workers/shared/client_message_broker';
export { ReceivedMessage, ServiceMessageBroker, ServiceMessageBrokerFactory } from '../src/web_workers/shared/service_message_broker';
export { PRIMITIVE } from '../src/web_workers/shared/serializer';
export * from '../src/web_workers/shared/message_bus';
import { WORKER_RENDER_APPLICATION } from 'angular2/src/platform/worker_render';
/**
* @deprecated Use WORKER_RENDER_APPLICATION
*/
export const WORKER_RENDER_APP = WORKER_RENDER_APPLICATION;
export { WORKER_RENDER_ROUTER } from 'angular2/src/web_workers/ui/router_providers';

35
node_modules/angular2/es6/prod/pubspec.yaml generated vendored Normal file
View File

@ -0,0 +1,35 @@
name: angular2
version: <%= packageJson.version %>
authors:
<%= Object.keys(packageJson.contributors).map(function(name) {
return '- '+name+' <'+packageJson.contributors[name]+'>';
}).join('\n') %>
description: Angular 2 for Dart - a web framework for modern web apps
homepage: <%= packageJson.homepage %>
environment:
sdk: '>=1.10.0 <2.0.0'
dependencies:
analyzer: '>=0.24.4 <0.28.0'
barback: '^0.15.2+2'
dart_style: '>=0.1.8 <0.3.0'
glob: '^1.0.0'
html: '^0.12.0'
intl: '^0.12.4'
logging: '>=0.9.0 <0.12.0'
observe: '^0.13.1'
path: '^1.0.0'
protobuf: '^0.5.0'
source_span: '^1.0.0'
stack_trace: '^1.1.1'
build: '>=0.0.1'
dev_dependencies:
transformer_test: '^0.2.0'
guinness: '^0.1.18'
guinness2: '0.0.5'
quiver: '^0.21.4'
test: '^0.12.6'
transformers:
- angular2/transform/codegen
- $dart2js:
commandLineOptions:
- --show-package-warnings

48
node_modules/angular2/es6/prod/router.js generated vendored Normal file
View File

@ -0,0 +1,48 @@
/**
* @module
* @description
* Maps application URLs into application states, to support deep-linking and navigation.
*/
export { Router } from './src/router/router';
export { RouterOutlet } from './src/router/directives/router_outlet';
export { RouterLink } from './src/router/directives/router_link';
export { RouteParams, RouteData } from './src/router/instruction';
export { PlatformLocation } from './src/router/location/platform_location';
export { RouteRegistry, ROUTER_PRIMARY_COMPONENT } from './src/router/route_registry';
export { LocationStrategy, APP_BASE_HREF } from './src/router/location/location_strategy';
export { HashLocationStrategy } from './src/router/location/hash_location_strategy';
export { PathLocationStrategy } from './src/router/location/path_location_strategy';
export { Location } from './src/router/location/location';
export * from './src/router/route_config/route_config_decorator';
export * from './src/router/route_definition';
export { CanActivate } from './src/router/lifecycle/lifecycle_annotations';
export { Instruction, ComponentInstruction } from './src/router/instruction';
export { OpaqueToken } from 'angular2/core';
export { ROUTER_PROVIDERS_COMMON } from 'angular2/src/router/router_providers_common';
export { ROUTER_PROVIDERS, ROUTER_BINDINGS } from 'angular2/src/router/router_providers';
import { RouterOutlet } from './src/router/directives/router_outlet';
import { RouterLink } from './src/router/directives/router_link';
import { CONST_EXPR } from './src/facade/lang';
/**
* A list of directives. To use the router directives like {@link RouterOutlet} and
* {@link RouterLink}, add this to your `directives` array in the {@link View} decorator of your
* component.
*
* ### Example ([live demo](http://plnkr.co/edit/iRUP8B5OUbxCWQ3AcIDm))
*
* ```
* import {Component} from 'angular2/core';
* import {ROUTER_DIRECTIVES, ROUTER_PROVIDERS, RouteConfig} from 'angular2/router';
*
* @Component({directives: [ROUTER_DIRECTIVES]})
* @RouteConfig([
* {...},
* ])
* class AppCmp {
* // ...
* }
*
* bootstrap(AppCmp, [ROUTER_PROVIDERS]);
* ```
*/
export const ROUTER_DIRECTIVES = CONST_EXPR([RouterOutlet, RouterLink]);

View File

@ -0,0 +1,32 @@
import { TEMPLATE_TRANSFORMS } from 'angular2/compiler';
import { Provider } from 'angular2/core';
import { RouterLinkTransform } from 'angular2/src/router/directives/router_link_transform';
import { CONST_EXPR } from 'angular2/src/facade/lang';
export { RouterLinkTransform } from 'angular2/src/router/directives/router_link_transform';
/**
* Enables the router link DSL.
*
* Warning. This feature is experimental and can change.
*
* To enable the transformer pass the router link DSL provider to `bootstrap`.
*
* ## Example:
* ```
* import {bootstrap} from 'angular2/platform/browser';
* import {ROUTER_LINK_DSL_PROVIDER} from 'angular2/router/router_link_dsl';
*
* bootstrap(CustomApp, [ROUTER_LINK_DSL_PROVIDER]);
* ```
*
* The DSL allows you to express router links as follows:
* ```
* <a [routerLink]="route:User"> <!-- Same as <a [routerLink]="['User']"> -->
* <a [routerLink]="route:/User"> <!-- Same as <a [routerLink]="['User']"> -->
* <a [routerLink]="route:./User"> <!-- Same as <a [routerLink]="['./User']"> -->
* <a [routerLink]="./User(id: value, name: 'Bob')"> <!-- Same as <a [routerLink]="['./User', {id:
* value, name: 'Bob'}]"> -->
* <a [routerLink]="/User/Modal"> <!-- Same as <a [routerLink]="['/User', 'Modal']"> -->
* <a [routerLink]="User[Modal]"> <!-- Same as <a [routerLink]="['User', ['Modal']]"> -->
* ```
*/
export const ROUTER_LINK_DSL_PROVIDER = CONST_EXPR(new Provider(TEMPLATE_TRANSFORMS, { useClass: RouterLinkTransform, multi: true }));

2
node_modules/angular2/es6/prod/router/testing.js generated vendored Normal file
View File

@ -0,0 +1,2 @@
export * from 'angular2/src/mock/mock_location_strategy';
export * from 'angular2/src/mock/location_mock';

172
node_modules/angular2/es6/prod/src/animate/animation.js generated vendored Normal file
View File

@ -0,0 +1,172 @@
import { DateWrapper, StringWrapper, RegExpWrapper, NumberWrapper, isPresent } from 'angular2/src/facade/lang';
import { Math } from 'angular2/src/facade/math';
import { camelCaseToDashCase } from 'angular2/src/platform/dom/util';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import { DOM } from 'angular2/src/platform/dom/dom_adapter';
export class Animation {
/**
* Stores the start time and starts the animation
* @param element
* @param data
* @param browserDetails
*/
constructor(element, data, browserDetails) {
this.element = element;
this.data = data;
this.browserDetails = browserDetails;
/** functions to be called upon completion */
this.callbacks = [];
/** functions for removing event listeners */
this.eventClearFunctions = [];
/** flag used to track whether or not the animation has finished */
this.completed = false;
this._stringPrefix = '';
this.startTime = DateWrapper.toMillis(DateWrapper.now());
this._stringPrefix = DOM.getAnimationPrefix();
this.setup();
this.wait((timestamp) => this.start());
}
/** total amount of time that the animation should take including delay */
get totalTime() {
let delay = this.computedDelay != null ? this.computedDelay : 0;
let duration = this.computedDuration != null ? this.computedDuration : 0;
return delay + duration;
}
wait(callback) {
// Firefox requires 2 frames for some reason
this.browserDetails.raf(callback, 2);
}
/**
* Sets up the initial styles before the animation is started
*/
setup() {
if (this.data.fromStyles != null)
this.applyStyles(this.data.fromStyles);
if (this.data.duration != null)
this.applyStyles({ 'transitionDuration': this.data.duration.toString() + 'ms' });
if (this.data.delay != null)
this.applyStyles({ 'transitionDelay': this.data.delay.toString() + 'ms' });
}
/**
* After the initial setup has occurred, this method adds the animation styles
*/
start() {
this.addClasses(this.data.classesToAdd);
this.addClasses(this.data.animationClasses);
this.removeClasses(this.data.classesToRemove);
if (this.data.toStyles != null)
this.applyStyles(this.data.toStyles);
var computedStyles = DOM.getComputedStyle(this.element);
this.computedDelay =
Math.max(this.parseDurationString(computedStyles.getPropertyValue(this._stringPrefix + 'transition-delay')), this.parseDurationString(this.element.style.getPropertyValue(this._stringPrefix + 'transition-delay')));
this.computedDuration = Math.max(this.parseDurationString(computedStyles.getPropertyValue(this._stringPrefix + 'transition-duration')), this.parseDurationString(this.element.style.getPropertyValue(this._stringPrefix + 'transition-duration')));
this.addEvents();
}
/**
* Applies the provided styles to the element
* @param styles
*/
applyStyles(styles) {
StringMapWrapper.forEach(styles, (value, key) => {
var dashCaseKey = camelCaseToDashCase(key);
if (isPresent(DOM.getStyle(this.element, dashCaseKey))) {
DOM.setStyle(this.element, dashCaseKey, value.toString());
}
else {
DOM.setStyle(this.element, this._stringPrefix + dashCaseKey, value.toString());
}
});
}
/**
* Adds the provided classes to the element
* @param classes
*/
addClasses(classes) {
for (let i = 0, len = classes.length; i < len; i++)
DOM.addClass(this.element, classes[i]);
}
/**
* Removes the provided classes from the element
* @param classes
*/
removeClasses(classes) {
for (let i = 0, len = classes.length; i < len; i++)
DOM.removeClass(this.element, classes[i]);
}
/**
* Adds events to track when animations have finished
*/
addEvents() {
if (this.totalTime > 0) {
this.eventClearFunctions.push(DOM.onAndCancel(this.element, DOM.getTransitionEnd(), (event) => this.handleAnimationEvent(event)));
}
else {
this.handleAnimationCompleted();
}
}
handleAnimationEvent(event) {
let elapsedTime = Math.round(event.elapsedTime * 1000);
if (!this.browserDetails.elapsedTimeIncludesDelay)
elapsedTime += this.computedDelay;
event.stopPropagation();
if (elapsedTime >= this.totalTime)
this.handleAnimationCompleted();
}
/**
* Runs all animation callbacks and removes temporary classes
*/
handleAnimationCompleted() {
this.removeClasses(this.data.animationClasses);
this.callbacks.forEach(callback => callback());
this.callbacks = [];
this.eventClearFunctions.forEach(fn => fn());
this.eventClearFunctions = [];
this.completed = true;
}
/**
* Adds animation callbacks to be called upon completion
* @param callback
* @returns {Animation}
*/
onComplete(callback) {
if (this.completed) {
callback();
}
else {
this.callbacks.push(callback);
}
return this;
}
/**
* Converts the duration string to the number of milliseconds
* @param duration
* @returns {number}
*/
parseDurationString(duration) {
var maxValue = 0;
// duration must have at least 2 characters to be valid. (number + type)
if (duration == null || duration.length < 2) {
return maxValue;
}
else if (duration.substring(duration.length - 2) == 'ms') {
let value = NumberWrapper.parseInt(this.stripLetters(duration), 10);
if (value > maxValue)
maxValue = value;
}
else if (duration.substring(duration.length - 1) == 's') {
let ms = NumberWrapper.parseFloat(this.stripLetters(duration)) * 1000;
let value = Math.floor(ms);
if (value > maxValue)
maxValue = value;
}
return maxValue;
}
/**
* Strips the letters from the duration string
* @param str
* @returns {string}
*/
stripLetters(str) {
return StringWrapper.replaceAll(str, RegExpWrapper.create('[^0-9]+$', ''), '');
}
}

View File

@ -0,0 +1,30 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Injectable } from 'angular2/src/core/di';
import { CssAnimationBuilder } from './css_animation_builder';
import { BrowserDetails } from './browser_details';
export let AnimationBuilder = class {
/**
* Used for DI
* @param browserDetails
*/
constructor(browserDetails) {
this.browserDetails = browserDetails;
}
/**
* Creates a new CSS Animation
* @returns {CssAnimationBuilder}
*/
css() { return new CssAnimationBuilder(this.browserDetails); }
};
AnimationBuilder = __decorate([
Injectable(),
__metadata('design:paramtypes', [BrowserDetails])
], AnimationBuilder);

View File

@ -0,0 +1,68 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Injectable } from 'angular2/src/core/di';
import { Math } from 'angular2/src/facade/math';
import { DOM } from 'angular2/src/platform/dom/dom_adapter';
export let BrowserDetails = class {
constructor() {
this.elapsedTimeIncludesDelay = false;
this.doesElapsedTimeIncludesDelay();
}
/**
* Determines if `event.elapsedTime` includes transition delay in the current browser. At this
* time, Chrome and Opera seem to be the only browsers that include this.
*/
doesElapsedTimeIncludesDelay() {
var div = DOM.createElement('div');
DOM.setAttribute(div, 'style', `position: absolute; top: -9999px; left: -9999px; width: 1px;
height: 1px; transition: all 1ms linear 1ms;`);
// Firefox requires that we wait for 2 frames for some reason
this.raf((timestamp) => {
DOM.on(div, 'transitionend', (event) => {
var elapsed = Math.round(event.elapsedTime * 1000);
this.elapsedTimeIncludesDelay = elapsed == 2;
DOM.remove(div);
});
DOM.setStyle(div, 'width', '2px');
}, 2);
}
raf(callback, frames = 1) {
var queue = new RafQueue(callback, frames);
return () => queue.cancel();
}
};
BrowserDetails = __decorate([
Injectable(),
__metadata('design:paramtypes', [])
], BrowserDetails);
class RafQueue {
constructor(callback, frames) {
this.callback = callback;
this.frames = frames;
this._raf();
}
_raf() {
this.currentFrameId =
DOM.requestAnimationFrame((timestamp) => this._nextFrame(timestamp));
}
_nextFrame(timestamp) {
this.frames--;
if (this.frames > 0) {
this._raf();
}
else {
this.callback(timestamp);
}
}
cancel() {
DOM.cancelAnimationFrame(this.currentFrameId);
this.currentFrameId = null;
}
}

View File

@ -0,0 +1,83 @@
import { CssAnimationOptions } from './css_animation_options';
import { Animation } from './animation';
export class CssAnimationBuilder {
/**
* Accepts public properties for CssAnimationBuilder
*/
constructor(browserDetails) {
this.browserDetails = browserDetails;
/** @type {CssAnimationOptions} */
this.data = new CssAnimationOptions();
}
/**
* Adds a temporary class that will be removed at the end of the animation
* @param className
*/
addAnimationClass(className) {
this.data.animationClasses.push(className);
return this;
}
/**
* Adds a class that will remain on the element after the animation has finished
* @param className
*/
addClass(className) {
this.data.classesToAdd.push(className);
return this;
}
/**
* Removes a class from the element
* @param className
*/
removeClass(className) {
this.data.classesToRemove.push(className);
return this;
}
/**
* Sets the animation duration (and overrides any defined through CSS)
* @param duration
*/
setDuration(duration) {
this.data.duration = duration;
return this;
}
/**
* Sets the animation delay (and overrides any defined through CSS)
* @param delay
*/
setDelay(delay) {
this.data.delay = delay;
return this;
}
/**
* Sets styles for both the initial state and the destination state
* @param from
* @param to
*/
setStyles(from, to) {
return this.setFromStyles(from).setToStyles(to);
}
/**
* Sets the initial styles for the animation
* @param from
*/
setFromStyles(from) {
this.data.fromStyles = from;
return this;
}
/**
* Sets the destination styles for the animation
* @param to
*/
setToStyles(to) {
this.data.toStyles = to;
return this;
}
/**
* Starts the animation and returns a promise
* @param element
*/
start(element) {
return new Animation(element, this.data, this.browserDetails);
}
}

View File

@ -0,0 +1,10 @@
export class CssAnimationOptions {
constructor() {
/** classes to be added to the element */
this.classesToAdd = [];
/** classes to be removed from the element */
this.classesToRemove = [];
/** classes to be added for the duration of the animation */
this.animationClasses = [];
}
}

View File

@ -0,0 +1,47 @@
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { FORM_DIRECTIVES } from './forms';
import { CORE_DIRECTIVES } from './directives';
/**
* A collection of Angular core directives that are likely to be used in each and every Angular
* application. This includes core directives (e.g., NgIf and NgFor), and forms directives (e.g.,
* NgModel).
*
* This collection can be used to quickly enumerate all the built-in directives in the `directives`
* property of the `@Component` decorator.
*
* ### Example
*
* Instead of writing:
*
* ```typescript
* import {NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault, NgModel, NgForm} from
* 'angular2/common';
* import {OtherDirective} from './myDirectives';
*
* @Component({
* selector: 'my-component',
* templateUrl: 'myComponent.html',
* directives: [NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault, NgModel, NgForm,
* OtherDirective]
* })
* export class MyComponent {
* ...
* }
* ```
* one could import all the common directives at once:
*
* ```typescript
* import {COMMON_DIRECTIVES} from 'angular2/common';
* import {OtherDirective} from './myDirectives';
*
* @Component({
* selector: 'my-component',
* templateUrl: 'myComponent.html',
* directives: [COMMON_DIRECTIVES, OtherDirective]
* })
* export class MyComponent {
* ...
* }
* ```
*/
export const COMMON_DIRECTIVES = CONST_EXPR([CORE_DIRECTIVES, FORM_DIRECTIVES]);

View File

@ -0,0 +1,13 @@
/**
* @module
* @description
* Common directives shipped with Angular.
*/
export { NgClass } from './directives/ng_class';
export { NgFor } from './directives/ng_for';
export { NgIf } from './directives/ng_if';
export { NgStyle } from './directives/ng_style';
export { NgSwitch, NgSwitchWhen, NgSwitchDefault } from './directives/ng_switch';
export { NgPlural, NgPluralCase, NgLocalization } from './directives/ng_plural';
export * from './directives/observable_list_diff';
export { CORE_DIRECTIVES } from './directives/core_directives';

View File

@ -0,0 +1,58 @@
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { NgClass } from './ng_class';
import { NgFor } from './ng_for';
import { NgIf } from './ng_if';
import { NgStyle } from './ng_style';
import { NgSwitch, NgSwitchWhen, NgSwitchDefault } from './ng_switch';
import { NgPlural, NgPluralCase } from './ng_plural';
/**
* A collection of Angular core directives that are likely to be used in each and every Angular
* application.
*
* This collection can be used to quickly enumerate all the built-in directives in the `directives`
* property of the `@Component` annotation.
*
* ### Example ([live demo](http://plnkr.co/edit/yakGwpCdUkg0qfzX5m8g?p=preview))
*
* Instead of writing:
*
* ```typescript
* import {NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault} from 'angular2/common';
* import {OtherDirective} from './myDirectives';
*
* @Component({
* selector: 'my-component',
* templateUrl: 'myComponent.html',
* directives: [NgClass, NgIf, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault, OtherDirective]
* })
* export class MyComponent {
* ...
* }
* ```
* one could import all the core directives at once:
*
* ```typescript
* import {CORE_DIRECTIVES} from 'angular2/common';
* import {OtherDirective} from './myDirectives';
*
* @Component({
* selector: 'my-component',
* templateUrl: 'myComponent.html',
* directives: [CORE_DIRECTIVES, OtherDirective]
* })
* export class MyComponent {
* ...
* }
* ```
*/
export const CORE_DIRECTIVES = CONST_EXPR([
NgClass,
NgFor,
NgIf,
NgStyle,
NgSwitch,
NgSwitchWhen,
NgSwitchDefault,
NgPlural,
NgPluralCase
]);

View File

@ -0,0 +1,172 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { isPresent, isString, isArray } from 'angular2/src/facade/lang';
import { Directive, ElementRef, IterableDiffers, KeyValueDiffers, Renderer } from 'angular2/core';
import { StringMapWrapper, isListLikeIterable } from 'angular2/src/facade/collection';
/**
* The `NgClass` directive conditionally adds and removes CSS classes on an HTML element based on
* an expression's evaluation result.
*
* The result of an expression evaluation is interpreted differently depending on type of
* the expression evaluation result:
* - `string` - all the CSS classes listed in a string (space delimited) are added
* - `Array` - all the CSS classes (Array elements) are added
* - `Object` - each key corresponds to a CSS class name while values are interpreted as expressions
* evaluating to `Boolean`. If a given expression evaluates to `true` a corresponding CSS class
* is added - otherwise it is removed.
*
* While the `NgClass` directive can interpret expressions evaluating to `string`, `Array`
* or `Object`, the `Object`-based version is the most often used and has an advantage of keeping
* all the CSS class names in a template.
*
* ### Example ([live demo](http://plnkr.co/edit/a4YdtmWywhJ33uqfpPPn?p=preview)):
*
* ```
* import {Component} from 'angular2/core';
* import {NgClass} from 'angular2/common';
*
* @Component({
* selector: 'toggle-button',
* inputs: ['isDisabled'],
* template: `
* <div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
* (click)="toggle(!isOn)">
* Click me!
* </div>`,
* styles: [`
* .button {
* width: 120px;
* border: medium solid black;
* }
*
* .active {
* background-color: red;
* }
*
* .disabled {
* color: gray;
* border: medium solid gray;
* }
* `]
* directives: [NgClass]
* })
* class ToggleButton {
* isOn = false;
* isDisabled = false;
*
* toggle(newState) {
* if (!this.isDisabled) {
* this.isOn = newState;
* }
* }
* }
* ```
*/
export let NgClass = class {
constructor(_iterableDiffers, _keyValueDiffers, _ngEl, _renderer) {
this._iterableDiffers = _iterableDiffers;
this._keyValueDiffers = _keyValueDiffers;
this._ngEl = _ngEl;
this._renderer = _renderer;
this._initialClasses = [];
}
set initialClasses(v) {
this._applyInitialClasses(true);
this._initialClasses = isPresent(v) && isString(v) ? v.split(' ') : [];
this._applyInitialClasses(false);
this._applyClasses(this._rawClass, false);
}
set rawClass(v) {
this._cleanupClasses(this._rawClass);
if (isString(v)) {
v = v.split(' ');
}
this._rawClass = v;
this._iterableDiffer = null;
this._keyValueDiffer = null;
if (isPresent(v)) {
if (isListLikeIterable(v)) {
this._iterableDiffer = this._iterableDiffers.find(v).create(null);
}
else {
this._keyValueDiffer = this._keyValueDiffers.find(v).create(null);
}
}
}
ngDoCheck() {
if (isPresent(this._iterableDiffer)) {
var changes = this._iterableDiffer.diff(this._rawClass);
if (isPresent(changes)) {
this._applyIterableChanges(changes);
}
}
if (isPresent(this._keyValueDiffer)) {
var changes = this._keyValueDiffer.diff(this._rawClass);
if (isPresent(changes)) {
this._applyKeyValueChanges(changes);
}
}
}
ngOnDestroy() { this._cleanupClasses(this._rawClass); }
_cleanupClasses(rawClassVal) {
this._applyClasses(rawClassVal, true);
this._applyInitialClasses(false);
}
_applyKeyValueChanges(changes) {
changes.forEachAddedItem((record) => { this._toggleClass(record.key, record.currentValue); });
changes.forEachChangedItem((record) => { this._toggleClass(record.key, record.currentValue); });
changes.forEachRemovedItem((record) => {
if (record.previousValue) {
this._toggleClass(record.key, false);
}
});
}
_applyIterableChanges(changes) {
changes.forEachAddedItem((record) => { this._toggleClass(record.item, true); });
changes.forEachRemovedItem((record) => { this._toggleClass(record.item, false); });
}
_applyInitialClasses(isCleanup) {
this._initialClasses.forEach(className => this._toggleClass(className, !isCleanup));
}
_applyClasses(rawClassVal, isCleanup) {
if (isPresent(rawClassVal)) {
if (isArray(rawClassVal)) {
rawClassVal.forEach(className => this._toggleClass(className, !isCleanup));
}
else if (rawClassVal instanceof Set) {
rawClassVal.forEach(className => this._toggleClass(className, !isCleanup));
}
else {
StringMapWrapper.forEach(rawClassVal, (expVal, className) => {
if (isPresent(expVal))
this._toggleClass(className, !isCleanup);
});
}
}
}
_toggleClass(className, enabled) {
className = className.trim();
if (className.length > 0) {
if (className.indexOf(' ') > -1) {
var classes = className.split(/\s+/g);
for (var i = 0, len = classes.length; i < len; i++) {
this._renderer.setElementClass(this._ngEl.nativeElement, classes[i], enabled);
}
}
else {
this._renderer.setElementClass(this._ngEl.nativeElement, className, enabled);
}
}
}
};
NgClass = __decorate([
Directive({ selector: '[ngClass]', inputs: ['rawClass: ngClass', 'initialClasses: class'] }),
__metadata('design:paramtypes', [IterableDiffers, KeyValueDiffers, ElementRef, Renderer])
], NgClass);

View File

@ -0,0 +1,160 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Directive, ChangeDetectorRef, IterableDiffers, ViewContainerRef, TemplateRef } from 'angular2/core';
import { isPresent, isBlank, getTypeNameForDebugging } from 'angular2/src/facade/lang';
import { BaseException } from "../../facade/exceptions";
/**
* The `NgFor` directive instantiates a template once per item from an iterable. The context for
* each instantiated template inherits from the outer context with the given loop variable set
* to the current item from the iterable.
*
* # Local Variables
*
* `NgFor` provides several exported values that can be aliased to local variables:
*
* * `index` will be set to the current loop iteration for each template context.
* * `last` will be set to a boolean value indicating whether the item is the last one in the
* iteration.
* * `even` will be set to a boolean value indicating whether this item has an even index.
* * `odd` will be set to a boolean value indicating whether this item has an odd index.
*
* # Change Propagation
*
* When the contents of the iterator changes, `NgFor` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
* * Otherwise, the DOM element for that item will remain the same.
*
* Angular uses object identity to track insertions and deletions within the iterator and reproduce
* those changes in the DOM. This has important implications for animations and any stateful
* controls
* (such as `<input>` elements which accept user input) that are present. Inserted rows can be
* animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state such
* as user input.
*
* It is possible for the identities of elements in the iterator to change while the data does not.
* This can happen, for example, if the iterator produced from an RPC to the server, and that
* RPC is re-run. Even if the data hasn't changed, the second response will produce objects with
* different identities, and Angular will tear down the entire DOM and rebuild it (as if all old
* elements were deleted and all new elements inserted). This is an expensive operation and should
* be avoided if possible.
*
* # Syntax
*
* - `<li *ngFor="#item of items; #i = index">...</li>`
* - `<li template="ngFor #item of items; #i = index">...</li>`
* - `<template ngFor #item [ngForOf]="items" #i="index"><li>...</li></template>`
*
* ### Example
*
* See a [live demo](http://plnkr.co/edit/KVuXxDp0qinGDyo307QW?p=preview) for a more detailed
* example.
*/
export let NgFor = class {
constructor(_viewContainer, _templateRef, _iterableDiffers, _cdr) {
this._viewContainer = _viewContainer;
this._templateRef = _templateRef;
this._iterableDiffers = _iterableDiffers;
this._cdr = _cdr;
}
set ngForOf(value) {
this._ngForOf = value;
if (isBlank(this._differ) && isPresent(value)) {
try {
this._differ = this._iterableDiffers.find(value).create(this._cdr, this._ngForTrackBy);
}
catch (e) {
throw new BaseException(`Cannot find a differ supporting object '${value}' of type '${getTypeNameForDebugging(value)}'. NgFor only supports binding to Iterables such as Arrays.`);
}
}
}
set ngForTemplate(value) {
if (isPresent(value)) {
this._templateRef = value;
}
}
set ngForTrackBy(value) { this._ngForTrackBy = value; }
ngDoCheck() {
if (isPresent(this._differ)) {
var changes = this._differ.diff(this._ngForOf);
if (isPresent(changes))
this._applyChanges(changes);
}
}
_applyChanges(changes) {
// TODO(rado): check if change detection can produce a change record that is
// easier to consume than current.
var recordViewTuples = [];
changes.forEachRemovedItem((removedRecord) => recordViewTuples.push(new RecordViewTuple(removedRecord, null)));
changes.forEachMovedItem((movedRecord) => recordViewTuples.push(new RecordViewTuple(movedRecord, null)));
var insertTuples = this._bulkRemove(recordViewTuples);
changes.forEachAddedItem((addedRecord) => insertTuples.push(new RecordViewTuple(addedRecord, null)));
this._bulkInsert(insertTuples);
for (var i = 0; i < insertTuples.length; i++) {
this._perViewChange(insertTuples[i].view, insertTuples[i].record);
}
for (var i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
var viewRef = this._viewContainer.get(i);
viewRef.setLocal('last', i === ilen - 1);
}
changes.forEachIdentityChange((record) => {
var viewRef = this._viewContainer.get(record.currentIndex);
viewRef.setLocal('\$implicit', record.item);
});
}
_perViewChange(view, record) {
view.setLocal('\$implicit', record.item);
view.setLocal('index', record.currentIndex);
view.setLocal('even', (record.currentIndex % 2 == 0));
view.setLocal('odd', (record.currentIndex % 2 == 1));
}
_bulkRemove(tuples) {
tuples.sort((a, b) => a.record.previousIndex - b.record.previousIndex);
var movedTuples = [];
for (var i = tuples.length - 1; i >= 0; i--) {
var tuple = tuples[i];
// separate moved views from removed views.
if (isPresent(tuple.record.currentIndex)) {
tuple.view = this._viewContainer.detach(tuple.record.previousIndex);
movedTuples.push(tuple);
}
else {
this._viewContainer.remove(tuple.record.previousIndex);
}
}
return movedTuples;
}
_bulkInsert(tuples) {
tuples.sort((a, b) => a.record.currentIndex - b.record.currentIndex);
for (var i = 0; i < tuples.length; i++) {
var tuple = tuples[i];
if (isPresent(tuple.view)) {
this._viewContainer.insert(tuple.view, tuple.record.currentIndex);
}
else {
tuple.view =
this._viewContainer.createEmbeddedView(this._templateRef, tuple.record.currentIndex);
}
}
return tuples;
}
};
NgFor = __decorate([
Directive({ selector: '[ngFor][ngForOf]', inputs: ['ngForTrackBy', 'ngForOf', 'ngForTemplate'] }),
__metadata('design:paramtypes', [ViewContainerRef, TemplateRef, IterableDiffers, ChangeDetectorRef])
], NgFor);
class RecordViewTuple {
constructor(record, view) {
this.record = record;
this.view = view;
}
}

View File

@ -0,0 +1,54 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Directive, ViewContainerRef, TemplateRef } from 'angular2/core';
import { isBlank } from 'angular2/src/facade/lang';
/**
* Removes or recreates a portion of the DOM tree based on an {expression}.
*
* If the expression assigned to `ngIf` evaluates to a false value then the element
* is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
*
* ### Example ([live demo](http://plnkr.co/edit/fe0kgemFBtmQOY31b4tw?p=preview)):
*
* ```
* <div *ngIf="errorCount > 0" class="error">
* <!-- Error message displayed when the errorCount property on the current context is greater
* than 0. -->
* {{errorCount}} errors detected
* </div>
* ```
*
* ### Syntax
*
* - `<div *ngIf="condition">...</div>`
* - `<div template="ngIf condition">...</div>`
* - `<template [ngIf]="condition"><div>...</div></template>`
*/
export let NgIf = class {
constructor(_viewContainer, _templateRef) {
this._viewContainer = _viewContainer;
this._templateRef = _templateRef;
this._prevCondition = null;
}
set ngIf(newCondition /* boolean */) {
if (newCondition && (isBlank(this._prevCondition) || !this._prevCondition)) {
this._prevCondition = true;
this._viewContainer.createEmbeddedView(this._templateRef);
}
else if (!newCondition && (isBlank(this._prevCondition) || this._prevCondition)) {
this._prevCondition = false;
this._viewContainer.clear();
}
}
};
NgIf = __decorate([
Directive({ selector: '[ngIf]', inputs: ['ngIf'] }),
__metadata('design:paramtypes', [ViewContainerRef, TemplateRef])
], NgIf);

View File

@ -0,0 +1,149 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { Directive, ViewContainerRef, TemplateRef, ContentChildren, QueryList, Attribute, Input } from 'angular2/core';
import { isPresent, NumberWrapper } from 'angular2/src/facade/lang';
import { Map } from 'angular2/src/facade/collection';
import { SwitchView } from './ng_switch';
const _CATEGORY_DEFAULT = 'other';
export class NgLocalization {
}
/**
* `ngPlural` is an i18n directive that displays DOM sub-trees that match the switch expression
* value, or failing that, DOM sub-trees that match the switch expression's pluralization category.
*
* To use this directive, you must provide an extension of `NgLocalization` that maps values to
* category names. You then define a container element that sets the `[ngPlural]` attribute to a
* switch expression.
* - Inner elements defined with an `[ngPluralCase]` attribute will display based on their
* expression.
* - If `[ngPluralCase]` is set to a value starting with `=`, it will only display if the value
* matches the switch expression exactly.
* - Otherwise, the view will be treated as a "category match", and will only display if exact
* value matches aren't found and the value maps to its category using the `getPluralCategory`
* function provided.
*
* If no matching views are found for a switch expression, inner elements marked
* `[ngPluralCase]="other"` will be displayed.
*
* ```typescript
* class MyLocalization extends NgLocalization {
* getPluralCategory(value: any) {
* if(value < 5) {
* return 'few';
* }
* }
* }
*
* @Component({
* selector: 'app',
* providers: [provide(NgLocalization, {useClass: MyLocalization})]
* })
* @View({
* template: `
* <p>Value = {{value}}</p>
* <button (click)="inc()">Increment</button>
*
* <div [ngPlural]="value">
* <template ngPluralCase="=0">there is nothing</template>
* <template ngPluralCase="=1">there is one</template>
* <template ngPluralCase="few">there are a few</template>
* <template ngPluralCase="other">there is some number</template>
* </div>
* `,
* directives: [NgPlural, NgPluralCase]
* })
* export class App {
* value = 'init';
*
* inc() {
* this.value = this.value === 'init' ? 0 : this.value + 1;
* }
* }
*
* ```
*/
export let NgPluralCase = class {
constructor(value, template, viewContainer) {
this.value = value;
this._view = new SwitchView(viewContainer, template);
}
};
NgPluralCase = __decorate([
Directive({ selector: '[ngPluralCase]' }),
__param(0, Attribute('ngPluralCase')),
__metadata('design:paramtypes', [String, TemplateRef, ViewContainerRef])
], NgPluralCase);
export let NgPlural = class {
constructor(_localization) {
this._localization = _localization;
this._caseViews = new Map();
this.cases = null;
}
set ngPlural(value) {
this._switchValue = value;
this._updateView();
}
ngAfterContentInit() {
this.cases.forEach((pluralCase) => {
this._caseViews.set(this._formatValue(pluralCase), pluralCase._view);
});
this._updateView();
}
/** @internal */
_updateView() {
this._clearViews();
var view = this._caseViews.get(this._switchValue);
if (!isPresent(view))
view = this._getCategoryView(this._switchValue);
this._activateView(view);
}
/** @internal */
_clearViews() {
if (isPresent(this._activeView))
this._activeView.destroy();
}
/** @internal */
_activateView(view) {
if (!isPresent(view))
return;
this._activeView = view;
this._activeView.create();
}
/** @internal */
_getCategoryView(value) {
var category = this._localization.getPluralCategory(value);
var categoryView = this._caseViews.get(category);
return isPresent(categoryView) ? categoryView : this._caseViews.get(_CATEGORY_DEFAULT);
}
/** @internal */
_isValueView(pluralCase) { return pluralCase.value[0] === "="; }
/** @internal */
_formatValue(pluralCase) {
return this._isValueView(pluralCase) ? this._stripValue(pluralCase.value) : pluralCase.value;
}
/** @internal */
_stripValue(value) { return NumberWrapper.parseInt(value.substring(1), 10); }
};
__decorate([
ContentChildren(NgPluralCase),
__metadata('design:type', QueryList)
], NgPlural.prototype, "cases", void 0);
__decorate([
Input(),
__metadata('design:type', Number),
__metadata('design:paramtypes', [Number])
], NgPlural.prototype, "ngPlural", null);
NgPlural = __decorate([
Directive({ selector: '[ngPlural]' }),
__metadata('design:paramtypes', [NgLocalization])
], NgPlural);

View File

@ -0,0 +1,95 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { KeyValueDiffers, ElementRef, Directive, Renderer } from 'angular2/core';
import { isPresent, isBlank } from 'angular2/src/facade/lang';
/**
* The `NgStyle` directive changes styles based on a result of expression evaluation.
*
* An expression assigned to the `ngStyle` property must evaluate to an object and the
* corresponding element styles are updated based on changes to this object. Style names to update
* are taken from the object's keys, and values - from the corresponding object's values.
*
* ### Syntax
*
* - `<div [ngStyle]="{'font-style': style}"></div>`
* - `<div [ngStyle]="styleExp"></div>` - here the `styleExp` must evaluate to an object
*
* ### Example ([live demo](http://plnkr.co/edit/YamGS6GkUh9GqWNQhCyM?p=preview)):
*
* ```
* import {Component} from 'angular2/core';
* import {NgStyle} from 'angular2/common';
*
* @Component({
* selector: 'ngStyle-example',
* template: `
* <h1 [ngStyle]="{'font-style': style, 'font-size': size, 'font-weight': weight}">
* Change style of this text!
* </h1>
*
* <hr>
*
* <label>Italic: <input type="checkbox" (change)="changeStyle($event)"></label>
* <label>Bold: <input type="checkbox" (change)="changeWeight($event)"></label>
* <label>Size: <input type="text" [value]="size" (change)="size = $event.target.value"></label>
* `,
* directives: [NgStyle]
* })
* export class NgStyleExample {
* style = 'normal';
* weight = 'normal';
* size = '20px';
*
* changeStyle($event: any) {
* this.style = $event.target.checked ? 'italic' : 'normal';
* }
*
* changeWeight($event: any) {
* this.weight = $event.target.checked ? 'bold' : 'normal';
* }
* }
* ```
*
* In this example the `font-style`, `font-size` and `font-weight` styles will be updated
* based on the `style` property's value changes.
*/
export let NgStyle = class {
constructor(_differs, _ngEl, _renderer) {
this._differs = _differs;
this._ngEl = _ngEl;
this._renderer = _renderer;
}
set rawStyle(v) {
this._rawStyle = v;
if (isBlank(this._differ) && isPresent(v)) {
this._differ = this._differs.find(this._rawStyle).create(null);
}
}
ngDoCheck() {
if (isPresent(this._differ)) {
var changes = this._differ.diff(this._rawStyle);
if (isPresent(changes)) {
this._applyChanges(changes);
}
}
}
_applyChanges(changes) {
changes.forEachAddedItem((record) => { this._setStyle(record.key, record.currentValue); });
changes.forEachChangedItem((record) => { this._setStyle(record.key, record.currentValue); });
changes.forEachRemovedItem((record) => { this._setStyle(record.key, null); });
}
_setStyle(name, val) {
this._renderer.setElementStyle(this._ngEl.nativeElement, name, val);
}
};
NgStyle = __decorate([
Directive({ selector: '[ngStyle]', inputs: ['rawStyle: ngStyle'] }),
__metadata('design:paramtypes', [KeyValueDiffers, ElementRef, Renderer])
], NgStyle);

View File

@ -0,0 +1,208 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { Directive, Host, ViewContainerRef, TemplateRef } from 'angular2/core';
import { isPresent, isBlank, normalizeBlank, CONST_EXPR } from 'angular2/src/facade/lang';
import { ListWrapper, Map } from 'angular2/src/facade/collection';
const _WHEN_DEFAULT = CONST_EXPR(new Object());
export class SwitchView {
constructor(_viewContainerRef, _templateRef) {
this._viewContainerRef = _viewContainerRef;
this._templateRef = _templateRef;
}
create() { this._viewContainerRef.createEmbeddedView(this._templateRef); }
destroy() { this._viewContainerRef.clear(); }
}
/**
* Adds or removes DOM sub-trees when their match expressions match the switch expression.
*
* Elements within `NgSwitch` but without `NgSwitchWhen` or `NgSwitchDefault` directives will be
* preserved at the location as specified in the template.
*
* `NgSwitch` simply inserts nested elements based on which match expression matches the value
* obtained from the evaluated switch expression. In other words, you define a container element
* (where you place the directive with a switch expression on the
* **`[ngSwitch]="..."` attribute**), define any inner elements inside of the directive and
* place a `[ngSwitchWhen]` attribute per element.
*
* The `ngSwitchWhen` property is used to inform `NgSwitch` which element to display when the
* expression is evaluated. If a matching expression is not found via a `ngSwitchWhen` property
* then an element with the `ngSwitchDefault` attribute is displayed.
*
* ### Example ([live demo](http://plnkr.co/edit/DQMTII95CbuqWrl3lYAs?p=preview))
*
* ```typescript
* @Component({
* selector: 'app',
* template: `
* <p>Value = {{value}}</p>
* <button (click)="inc()">Increment</button>
*
* <div [ngSwitch]="value">
* <p *ngSwitchWhen="'init'">increment to start</p>
* <p *ngSwitchWhen="0">0, increment again</p>
* <p *ngSwitchWhen="1">1, increment again</p>
* <p *ngSwitchWhen="2">2, stop incrementing</p>
* <p *ngSwitchDefault>&gt; 2, STOP!</p>
* </div>
*
* <!-- alternate syntax -->
*
* <p [ngSwitch]="value">
* <template ngSwitchWhen="init">increment to start</template>
* <template [ngSwitchWhen]="0">0, increment again</template>
* <template [ngSwitchWhen]="1">1, increment again</template>
* <template [ngSwitchWhen]="2">2, stop incrementing</template>
* <template ngSwitchDefault>&gt; 2, STOP!</template>
* </p>
* `,
* directives: [NgSwitch, NgSwitchWhen, NgSwitchDefault]
* })
* export class App {
* value = 'init';
*
* inc() {
* this.value = this.value === 'init' ? 0 : this.value + 1;
* }
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export let NgSwitch = class {
constructor() {
this._useDefault = false;
this._valueViews = new Map();
this._activeViews = [];
}
set ngSwitch(value) {
// Empty the currently active ViewContainers
this._emptyAllActiveViews();
// Add the ViewContainers matching the value (with a fallback to default)
this._useDefault = false;
var views = this._valueViews.get(value);
if (isBlank(views)) {
this._useDefault = true;
views = normalizeBlank(this._valueViews.get(_WHEN_DEFAULT));
}
this._activateViews(views);
this._switchValue = value;
}
/** @internal */
_onWhenValueChanged(oldWhen, newWhen, view) {
this._deregisterView(oldWhen, view);
this._registerView(newWhen, view);
if (oldWhen === this._switchValue) {
view.destroy();
ListWrapper.remove(this._activeViews, view);
}
else if (newWhen === this._switchValue) {
if (this._useDefault) {
this._useDefault = false;
this._emptyAllActiveViews();
}
view.create();
this._activeViews.push(view);
}
// Switch to default when there is no more active ViewContainers
if (this._activeViews.length === 0 && !this._useDefault) {
this._useDefault = true;
this._activateViews(this._valueViews.get(_WHEN_DEFAULT));
}
}
/** @internal */
_emptyAllActiveViews() {
var activeContainers = this._activeViews;
for (var i = 0; i < activeContainers.length; i++) {
activeContainers[i].destroy();
}
this._activeViews = [];
}
/** @internal */
_activateViews(views) {
// TODO(vicb): assert(this._activeViews.length === 0);
if (isPresent(views)) {
for (var i = 0; i < views.length; i++) {
views[i].create();
}
this._activeViews = views;
}
}
/** @internal */
_registerView(value, view) {
var views = this._valueViews.get(value);
if (isBlank(views)) {
views = [];
this._valueViews.set(value, views);
}
views.push(view);
}
/** @internal */
_deregisterView(value, view) {
// `_WHEN_DEFAULT` is used a marker for non-registered whens
if (value === _WHEN_DEFAULT)
return;
var views = this._valueViews.get(value);
if (views.length == 1) {
this._valueViews.delete(value);
}
else {
ListWrapper.remove(views, view);
}
}
};
NgSwitch = __decorate([
Directive({ selector: '[ngSwitch]', inputs: ['ngSwitch'] }),
__metadata('design:paramtypes', [])
], NgSwitch);
/**
* Insert the sub-tree when the `ngSwitchWhen` expression evaluates to the same value as the
* enclosing switch expression.
*
* If multiple match expression match the switch expression value, all of them are displayed.
*
* See {@link NgSwitch} for more details and example.
*/
export let NgSwitchWhen = class {
constructor(viewContainer, templateRef, ngSwitch) {
// `_WHEN_DEFAULT` is used as a marker for a not yet initialized value
/** @internal */
this._value = _WHEN_DEFAULT;
this._switch = ngSwitch;
this._view = new SwitchView(viewContainer, templateRef);
}
set ngSwitchWhen(value) {
this._switch._onWhenValueChanged(this._value, value, this._view);
this._value = value;
}
};
NgSwitchWhen = __decorate([
Directive({ selector: '[ngSwitchWhen]', inputs: ['ngSwitchWhen'] }),
__param(2, Host()),
__metadata('design:paramtypes', [ViewContainerRef, TemplateRef, NgSwitch])
], NgSwitchWhen);
/**
* Default case statements are displayed when no match expression matches the switch expression
* value.
*
* See {@link NgSwitch} for more details and example.
*/
export let NgSwitchDefault = class {
constructor(viewContainer, templateRef, sswitch) {
sswitch._registerView(_WHEN_DEFAULT, new SwitchView(viewContainer, templateRef));
}
};
NgSwitchDefault = __decorate([
Directive({ selector: '[ngSwitchDefault]' }),
__param(2, Host()),
__metadata('design:paramtypes', [ViewContainerRef, TemplateRef, NgSwitch])
], NgSwitchDefault);

View File

@ -0,0 +1,6 @@
// TS does not have Observables
/**
* This module exists in Dart, but not in Typescript. This exported symbol
* is only here to help Typescript think this is a module.
*/
export var workaround_empty_observable_list_diff;

51
node_modules/angular2/es6/prod/src/common/forms.js generated vendored Normal file
View File

@ -0,0 +1,51 @@
/**
* @module
* @description
* This module is used for handling user input, by defining and building a {@link ControlGroup} that
* consists of
* {@link Control} objects, and mapping them onto the DOM. {@link Control} objects can then be used
* to read information
* from the form DOM elements.
*
* This module is not included in the `angular2` module; you must import the forms module
* explicitly.
*
*/
export { AbstractControl, Control, ControlGroup, ControlArray } from './forms/model';
export { AbstractControlDirective } from './forms/directives/abstract_control_directive';
export { ControlContainer } from './forms/directives/control_container';
export { NgControlName } from './forms/directives/ng_control_name';
export { NgFormControl } from './forms/directives/ng_form_control';
export { NgModel } from './forms/directives/ng_model';
export { NgControl } from './forms/directives/ng_control';
export { NgControlGroup } from './forms/directives/ng_control_group';
export { NgFormModel } from './forms/directives/ng_form_model';
export { NgForm } from './forms/directives/ng_form';
export { NG_VALUE_ACCESSOR } from './forms/directives/control_value_accessor';
export { DefaultValueAccessor } from './forms/directives/default_value_accessor';
export { NgControlStatus } from './forms/directives/ng_control_status';
export { CheckboxControlValueAccessor } from './forms/directives/checkbox_value_accessor';
export { NgSelectOption, SelectControlValueAccessor } from './forms/directives/select_control_value_accessor';
export { FORM_DIRECTIVES, RadioButtonState } from './forms/directives';
export { NG_VALIDATORS, NG_ASYNC_VALIDATORS, Validators } from './forms/validators';
export { RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator } from './forms/directives/validators';
export { FormBuilder } from './forms/form_builder';
import { FormBuilder } from './forms/form_builder';
import { RadioControlRegistry } from './forms/directives/radio_control_value_accessor';
import { CONST_EXPR } from 'angular2/src/facade/lang';
/**
* Shorthand set of providers used for building Angular forms.
*
* ### Example
*
* ```typescript
* bootstrap(MyApp, [FORM_PROVIDERS]);
* ```
*/
export const FORM_PROVIDERS = CONST_EXPR([FormBuilder, RadioControlRegistry]);
/**
* See {@link FORM_PROVIDERS} instead.
*
* @deprecated
*/
export const FORM_BINDINGS = FORM_PROVIDERS;

View File

@ -0,0 +1,63 @@
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { NgControlName } from './directives/ng_control_name';
import { NgFormControl } from './directives/ng_form_control';
import { NgModel } from './directives/ng_model';
import { NgControlGroup } from './directives/ng_control_group';
import { NgFormModel } from './directives/ng_form_model';
import { NgForm } from './directives/ng_form';
import { DefaultValueAccessor } from './directives/default_value_accessor';
import { CheckboxControlValueAccessor } from './directives/checkbox_value_accessor';
import { NumberValueAccessor } from './directives/number_value_accessor';
import { RadioControlValueAccessor } from './directives/radio_control_value_accessor';
import { NgControlStatus } from './directives/ng_control_status';
import { SelectControlValueAccessor, NgSelectOption } from './directives/select_control_value_accessor';
import { RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator } from './directives/validators';
export { NgControlName } from './directives/ng_control_name';
export { NgFormControl } from './directives/ng_form_control';
export { NgModel } from './directives/ng_model';
export { NgControlGroup } from './directives/ng_control_group';
export { NgFormModel } from './directives/ng_form_model';
export { NgForm } from './directives/ng_form';
export { DefaultValueAccessor } from './directives/default_value_accessor';
export { CheckboxControlValueAccessor } from './directives/checkbox_value_accessor';
export { RadioControlValueAccessor, RadioButtonState } from './directives/radio_control_value_accessor';
export { NumberValueAccessor } from './directives/number_value_accessor';
export { NgControlStatus } from './directives/ng_control_status';
export { SelectControlValueAccessor, NgSelectOption } from './directives/select_control_value_accessor';
export { RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator } from './directives/validators';
export { NgControl } from './directives/ng_control';
/**
*
* A list of all the form directives used as part of a `@Component` annotation.
*
* This is a shorthand for importing them each individually.
*
* ### Example
*
* ```typescript
* @Component({
* selector: 'my-app',
* directives: [FORM_DIRECTIVES]
* })
* class MyApp {}
* ```
*/
export const FORM_DIRECTIVES = CONST_EXPR([
NgControlName,
NgControlGroup,
NgFormControl,
NgModel,
NgFormModel,
NgForm,
NgSelectOption,
DefaultValueAccessor,
NumberValueAccessor,
CheckboxControlValueAccessor,
SelectControlValueAccessor,
RadioControlValueAccessor,
NgControlStatus,
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator
]);

View File

@ -0,0 +1,20 @@
import { isPresent } from 'angular2/src/facade/lang';
import { unimplemented } from 'angular2/src/facade/exceptions';
/**
* Base class for control directives.
*
* Only used internally in the forms module.
*/
export class AbstractControlDirective {
get control() { return unimplemented(); }
get value() { return isPresent(this.control) ? this.control.value : null; }
get valid() { return isPresent(this.control) ? this.control.valid : null; }
get errors() {
return isPresent(this.control) ? this.control.errors : null;
}
get pristine() { return isPresent(this.control) ? this.control.pristine : null; }
get dirty() { return isPresent(this.control) ? this.control.dirty : null; }
get touched() { return isPresent(this.control) ? this.control.touched : null; }
get untouched() { return isPresent(this.control) ? this.control.untouched : null; }
get path() { return null; }
}

View File

@ -0,0 +1,42 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Directive, Renderer, ElementRef, forwardRef, Provider } from 'angular2/core';
import { NG_VALUE_ACCESSOR } from './control_value_accessor';
import { CONST_EXPR } from 'angular2/src/facade/lang';
const CHECKBOX_VALUE_ACCESSOR = CONST_EXPR(new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => CheckboxControlValueAccessor), multi: true }));
/**
* The accessor for writing a value and listening to changes on a checkbox input element.
*
* ### Example
* ```
* <input type="checkbox" ngControl="rememberLogin">
* ```
*/
export let CheckboxControlValueAccessor = class {
constructor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = (_) => { };
this.onTouched = () => { };
}
writeValue(value) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', value);
}
registerOnChange(fn) { this.onChange = fn; }
registerOnTouched(fn) { this.onTouched = fn; }
};
CheckboxControlValueAccessor = __decorate([
Directive({
selector: 'input[type=checkbox][ngControl],input[type=checkbox][ngFormControl],input[type=checkbox][ngModel]',
host: { '(change)': 'onChange($event.target.checked)', '(blur)': 'onTouched()' },
providers: [CHECKBOX_VALUE_ACCESSOR]
}),
__metadata('design:paramtypes', [Renderer, ElementRef])
], CheckboxControlValueAccessor);

View File

@ -0,0 +1,16 @@
import { AbstractControlDirective } from './abstract_control_directive';
/**
* A directive that contains multiple {@link NgControl}s.
*
* Only used by the forms module.
*/
export class ControlContainer extends AbstractControlDirective {
/**
* Get the form to which this container belongs.
*/
get formDirective() { return null; }
/**
* Get the path to this container.
*/
get path() { return null; }
}

View File

@ -0,0 +1,8 @@
import { OpaqueToken } from 'angular2/core';
import { CONST_EXPR } from 'angular2/src/facade/lang';
/**
* Used to provide a {@link ControlValueAccessor} for form controls.
*
* See {@link DefaultValueAccessor} for how to implement one.
*/
export const NG_VALUE_ACCESSOR = CONST_EXPR(new OpaqueToken("NgValueAccessor"));

View File

@ -0,0 +1,47 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Directive, ElementRef, Renderer, forwardRef, Provider } from 'angular2/core';
import { NG_VALUE_ACCESSOR } from './control_value_accessor';
import { isBlank, CONST_EXPR } from 'angular2/src/facade/lang';
const DEFAULT_VALUE_ACCESSOR = CONST_EXPR(new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => DefaultValueAccessor), multi: true }));
/**
* The default accessor for writing a value and listening to changes that is used by the
* {@link NgModel}, {@link NgFormControl}, and {@link NgControlName} directives.
*
* ### Example
* ```
* <input type="text" ngControl="searchQuery">
* ```
*/
export let DefaultValueAccessor = class {
constructor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = (_) => { };
this.onTouched = () => { };
}
writeValue(value) {
var normalizedValue = isBlank(value) ? '' : value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', normalizedValue);
}
registerOnChange(fn) { this.onChange = fn; }
registerOnTouched(fn) { this.onTouched = fn; }
};
DefaultValueAccessor = __decorate([
Directive({
selector: 'input:not([type=checkbox])[ngControl],textarea[ngControl],input:not([type=checkbox])[ngFormControl],textarea[ngFormControl],input:not([type=checkbox])[ngModel],textarea[ngModel],[ngDefaultControl]',
// TODO: vsavkin replace the above selector with the one below it once
// https://github.com/angular/angular/issues/3011 is implemented
// selector: '[ngControl],[ngModel],[ngFormControl]',
host: { '(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()' },
bindings: [DEFAULT_VALUE_ACCESSOR]
}),
__metadata('design:paramtypes', [Renderer, ElementRef])
], DefaultValueAccessor);

View File

@ -0,0 +1,17 @@
import { AbstractControlDirective } from './abstract_control_directive';
import { unimplemented } from 'angular2/src/facade/exceptions';
/**
* A base class that all control directive extend.
* It binds a {@link Control} object to a DOM element.
*
* Used internally by Angular forms.
*/
export class NgControl extends AbstractControlDirective {
constructor(...args) {
super(...args);
this.name = null;
this.valueAccessor = null;
}
get validator() { return unimplemented(); }
get asyncValidator() { return unimplemented(); }
}

View File

@ -0,0 +1,105 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { Directive, Optional, Inject, Host, SkipSelf, forwardRef, Provider, Self } from 'angular2/core';
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { ControlContainer } from './control_container';
import { controlPath, composeValidators, composeAsyncValidators } from './shared';
import { NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '../validators';
const controlGroupProvider = CONST_EXPR(new Provider(ControlContainer, { useExisting: forwardRef(() => NgControlGroup) }));
/**
* Creates and binds a control group to a DOM element.
*
* This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}.
*
* ### Example ([live demo](http://plnkr.co/edit/7EJ11uGeaggViYM6T5nq?p=preview))
*
* ```typescript
* @Component({
* selector: 'my-app',
* directives: [FORM_DIRECTIVES],
* template: `
* <div>
* <h2>Angular2 Control &amp; ControlGroup Example</h2>
* <form #f="ngForm">
* <div ngControlGroup="name" #cg-name="form">
* <h3>Enter your name:</h3>
* <p>First: <input ngControl="first" required></p>
* <p>Middle: <input ngControl="middle"></p>
* <p>Last: <input ngControl="last" required></p>
* </div>
* <h3>Name value:</h3>
* <pre>{{valueOf(cgName)}}</pre>
* <p>Name is {{cgName?.control?.valid ? "valid" : "invalid"}}</p>
* <h3>What's your favorite food?</h3>
* <p><input ngControl="food"></p>
* <h3>Form value</h3>
* <pre>{{valueOf(f)}}</pre>
* </form>
* </div>
* `,
* directives: [FORM_DIRECTIVES]
* })
* export class App {
* valueOf(cg: NgControlGroup): string {
* if (cg.control == null) {
* return null;
* }
* return JSON.stringify(cg.control.value, null, 2);
* }
* }
* ```
*
* This example declares a control group for a user's name. The value and validation state of
* this group can be accessed separately from the overall form.
*/
export let NgControlGroup = class extends ControlContainer {
constructor(parent, _validators, _asyncValidators) {
super();
this._validators = _validators;
this._asyncValidators = _asyncValidators;
this._parent = parent;
}
ngOnInit() { this.formDirective.addControlGroup(this); }
ngOnDestroy() { this.formDirective.removeControlGroup(this); }
/**
* Get the {@link ControlGroup} backing this binding.
*/
get control() { return this.formDirective.getControlGroup(this); }
/**
* Get the path to this control group.
*/
get path() { return controlPath(this.name, this._parent); }
/**
* Get the {@link Form} to which this group belongs.
*/
get formDirective() { return this._parent.formDirective; }
get validator() { return composeValidators(this._validators); }
get asyncValidator() { return composeAsyncValidators(this._asyncValidators); }
};
NgControlGroup = __decorate([
Directive({
selector: '[ngControlGroup]',
providers: [controlGroupProvider],
inputs: ['name: ngControlGroup'],
exportAs: 'ngForm'
}),
__param(0, Host()),
__param(0, SkipSelf()),
__param(1, Optional()),
__param(1, Self()),
__param(1, Inject(NG_VALIDATORS)),
__param(2, Optional()),
__param(2, Self()),
__param(2, Inject(NG_ASYNC_VALIDATORS)),
__metadata('design:paramtypes', [ControlContainer, Array, Array])
], NgControlGroup);

View File

@ -0,0 +1,129 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { EventEmitter, ObservableWrapper } from 'angular2/src/facade/async';
import { Directive, forwardRef, Host, SkipSelf, Provider, Inject, Optional, Self } from 'angular2/core';
import { ControlContainer } from './control_container';
import { NgControl } from './ng_control';
import { NG_VALUE_ACCESSOR } from './control_value_accessor';
import { controlPath, composeValidators, composeAsyncValidators, isPropertyUpdated, selectValueAccessor } from './shared';
import { NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '../validators';
const controlNameBinding = CONST_EXPR(new Provider(NgControl, { useExisting: forwardRef(() => NgControlName) }));
/**
* Creates and binds a control with a specified name to a DOM element.
*
* This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}.
* ### Example
*
* In this example, we create the login and password controls.
* We can work with each control separately: check its validity, get its value, listen to its
* changes.
*
* ```
* @Component({
* selector: "login-comp",
* directives: [FORM_DIRECTIVES],
* template: `
* <form #f="ngForm" (submit)='onLogIn(f.value)'>
* Login <input type='text' ngControl='login' #l="form">
* <div *ngIf="!l.valid">Login is invalid</div>
*
* Password <input type='password' ngControl='password'>
* <button type='submit'>Log in!</button>
* </form>
* `})
* class LoginComp {
* onLogIn(value): void {
* // value === {login: 'some login', password: 'some password'}
* }
* }
* ```
*
* We can also use ngModel to bind a domain model to the form.
*
* ```
* @Component({
* selector: "login-comp",
* directives: [FORM_DIRECTIVES],
* template: `
* <form (submit)='onLogIn()'>
* Login <input type='text' ngControl='login' [(ngModel)]="credentials.login">
* Password <input type='password' ngControl='password'
* [(ngModel)]="credentials.password">
* <button type='submit'>Log in!</button>
* </form>
* `})
* class LoginComp {
* credentials: {login:string, password:string};
*
* onLogIn(): void {
* // this.credentials.login === "some login"
* // this.credentials.password === "some password"
* }
* }
* ```
*/
export let NgControlName = class extends NgControl {
constructor(_parent, _validators, _asyncValidators, valueAccessors) {
super();
this._parent = _parent;
this._validators = _validators;
this._asyncValidators = _asyncValidators;
/** @internal */
this.update = new EventEmitter();
this._added = false;
this.valueAccessor = selectValueAccessor(this, valueAccessors);
}
ngOnChanges(changes) {
if (!this._added) {
this.formDirective.addControl(this);
this._added = true;
}
if (isPropertyUpdated(changes, this.viewModel)) {
this.viewModel = this.model;
this.formDirective.updateModel(this, this.model);
}
}
ngOnDestroy() { this.formDirective.removeControl(this); }
viewToModelUpdate(newValue) {
this.viewModel = newValue;
ObservableWrapper.callEmit(this.update, newValue);
}
get path() { return controlPath(this.name, this._parent); }
get formDirective() { return this._parent.formDirective; }
get validator() { return composeValidators(this._validators); }
get asyncValidator() { return composeAsyncValidators(this._asyncValidators); }
get control() { return this.formDirective.getControl(this); }
};
NgControlName = __decorate([
Directive({
selector: '[ngControl]',
bindings: [controlNameBinding],
inputs: ['name: ngControl', 'model: ngModel'],
outputs: ['update: ngModelChange'],
exportAs: 'ngForm'
}),
__param(0, Host()),
__param(0, SkipSelf()),
__param(1, Optional()),
__param(1, Self()),
__param(1, Inject(NG_VALIDATORS)),
__param(2, Optional()),
__param(2, Self()),
__param(2, Inject(NG_ASYNC_VALIDATORS)),
__param(3, Optional()),
__param(3, Self()),
__param(3, Inject(NG_VALUE_ACCESSOR)),
__metadata('design:paramtypes', [ControlContainer, Array, Array, Array])
], NgControlName);

View File

@ -0,0 +1,57 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { Directive, Self } from 'angular2/core';
import { NgControl } from './ng_control';
import { isPresent } from 'angular2/src/facade/lang';
/**
* Directive automatically applied to Angular forms that sets CSS classes
* based on control status (valid/invalid/dirty/etc).
*/
export let NgControlStatus = class {
constructor(cd) {
this._cd = cd;
}
get ngClassUntouched() {
return isPresent(this._cd.control) ? this._cd.control.untouched : false;
}
get ngClassTouched() {
return isPresent(this._cd.control) ? this._cd.control.touched : false;
}
get ngClassPristine() {
return isPresent(this._cd.control) ? this._cd.control.pristine : false;
}
get ngClassDirty() {
return isPresent(this._cd.control) ? this._cd.control.dirty : false;
}
get ngClassValid() {
return isPresent(this._cd.control) ? this._cd.control.valid : false;
}
get ngClassInvalid() {
return isPresent(this._cd.control) ? !this._cd.control.valid : false;
}
};
NgControlStatus = __decorate([
Directive({
selector: '[ngControl],[ngModel],[ngFormControl]',
host: {
'[class.ng-untouched]': 'ngClassUntouched',
'[class.ng-touched]': 'ngClassTouched',
'[class.ng-pristine]': 'ngClassPristine',
'[class.ng-dirty]': 'ngClassDirty',
'[class.ng-valid]': 'ngClassValid',
'[class.ng-invalid]': 'ngClassInvalid'
}
}),
__param(0, Self()),
__metadata('design:paramtypes', [NgControl])
], NgControlStatus);

View File

@ -0,0 +1,164 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { PromiseWrapper, ObservableWrapper, EventEmitter } from 'angular2/src/facade/async';
import { ListWrapper } from 'angular2/src/facade/collection';
import { isPresent, CONST_EXPR } from 'angular2/src/facade/lang';
import { Directive, forwardRef, Provider, Optional, Inject, Self } from 'angular2/core';
import { ControlContainer } from './control_container';
import { ControlGroup, Control } from '../model';
import { setUpControl, setUpControlGroup, composeValidators, composeAsyncValidators } from './shared';
import { NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '../validators';
const formDirectiveProvider = CONST_EXPR(new Provider(ControlContainer, { useExisting: forwardRef(() => NgForm) }));
/**
* If `NgForm` is bound in a component, `<form>` elements in that component will be
* upgraded to use the Angular form system.
*
* ### Typical Use
*
* Include `FORM_DIRECTIVES` in the `directives` section of a {@link View} annotation
* to use `NgForm` and its associated controls.
*
* ### Structure
*
* An Angular form is a collection of `Control`s in some hierarchy.
* `Control`s can be at the top level or can be organized in `ControlGroup`s
* or `ControlArray`s. This hierarchy is reflected in the form's `value`, a
* JSON object that mirrors the form structure.
*
* ### Submission
*
* The `ngSubmit` event signals when the user triggers a form submission.
*
* ### Example ([live demo](http://plnkr.co/edit/ltdgYj4P0iY64AR71EpL?p=preview))
*
* ```typescript
* @Component({
* selector: 'my-app',
* template: `
* <div>
* <p>Submit the form to see the data object Angular builds</p>
* <h2>NgForm demo</h2>
* <form #f="ngForm" (ngSubmit)="onSubmit(f.value)">
* <h3>Control group: credentials</h3>
* <div ngControlGroup="credentials">
* <p>Login: <input type="text" ngControl="login"></p>
* <p>Password: <input type="password" ngControl="password"></p>
* </div>
* <h3>Control group: person</h3>
* <div ngControlGroup="person">
* <p>First name: <input type="text" ngControl="firstName"></p>
* <p>Last name: <input type="text" ngControl="lastName"></p>
* </div>
* <button type="submit">Submit Form</button>
* <p>Form data submitted:</p>
* </form>
* <pre>{{data}}</pre>
* </div>
* `,
* directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
* })
* export class App {
* constructor() {}
*
* data: string;
*
* onSubmit(data) {
* this.data = JSON.stringify(data, null, 2);
* }
* }
* ```
*/
export let NgForm = class extends ControlContainer {
constructor(validators, asyncValidators) {
super();
this.ngSubmit = new EventEmitter();
this.form = new ControlGroup({}, null, composeValidators(validators), composeAsyncValidators(asyncValidators));
}
get formDirective() { return this; }
get control() { return this.form; }
get path() { return []; }
get controls() { return this.form.controls; }
addControl(dir) {
PromiseWrapper.scheduleMicrotask(() => {
var container = this._findContainer(dir.path);
var ctrl = new Control();
setUpControl(ctrl, dir);
container.addControl(dir.name, ctrl);
ctrl.updateValueAndValidity({ emitEvent: false });
});
}
getControl(dir) { return this.form.find(dir.path); }
removeControl(dir) {
PromiseWrapper.scheduleMicrotask(() => {
var container = this._findContainer(dir.path);
if (isPresent(container)) {
container.removeControl(dir.name);
container.updateValueAndValidity({ emitEvent: false });
}
});
}
addControlGroup(dir) {
PromiseWrapper.scheduleMicrotask(() => {
var container = this._findContainer(dir.path);
var group = new ControlGroup({});
setUpControlGroup(group, dir);
container.addControl(dir.name, group);
group.updateValueAndValidity({ emitEvent: false });
});
}
removeControlGroup(dir) {
PromiseWrapper.scheduleMicrotask(() => {
var container = this._findContainer(dir.path);
if (isPresent(container)) {
container.removeControl(dir.name);
container.updateValueAndValidity({ emitEvent: false });
}
});
}
getControlGroup(dir) {
return this.form.find(dir.path);
}
updateModel(dir, value) {
PromiseWrapper.scheduleMicrotask(() => {
var ctrl = this.form.find(dir.path);
ctrl.updateValue(value);
});
}
onSubmit() {
ObservableWrapper.callEmit(this.ngSubmit, null);
return false;
}
/** @internal */
_findContainer(path) {
path.pop();
return ListWrapper.isEmpty(path) ? this.form : this.form.find(path);
}
};
NgForm = __decorate([
Directive({
selector: 'form:not([ngNoForm]):not([ngFormModel]),ngForm,[ngForm]',
bindings: [formDirectiveProvider],
host: {
'(submit)': 'onSubmit()',
},
outputs: ['ngSubmit'],
exportAs: 'ngForm'
}),
__param(0, Optional()),
__param(0, Self()),
__param(0, Inject(NG_VALIDATORS)),
__param(1, Optional()),
__param(1, Self()),
__param(1, Inject(NG_ASYNC_VALIDATORS)),
__metadata('design:paramtypes', [Array, Array])
], NgForm);

View File

@ -0,0 +1,117 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import { EventEmitter, ObservableWrapper } from 'angular2/src/facade/async';
import { Directive, forwardRef, Provider, Inject, Optional, Self } from 'angular2/core';
import { NgControl } from './ng_control';
import { NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '../validators';
import { NG_VALUE_ACCESSOR } from './control_value_accessor';
import { setUpControl, composeValidators, composeAsyncValidators, isPropertyUpdated, selectValueAccessor } from './shared';
const formControlBinding = CONST_EXPR(new Provider(NgControl, { useExisting: forwardRef(() => NgFormControl) }));
/**
* Binds an existing {@link Control} to a DOM element.
*
* ### Example ([live demo](http://plnkr.co/edit/jcQlZ2tTh22BZZ2ucNAT?p=preview))
*
* In this example, we bind the control to an input element. When the value of the input element
* changes, the value of the control will reflect that change. Likewise, if the value of the
* control changes, the input element reflects that change.
*
* ```typescript
* @Component({
* selector: 'my-app',
* template: `
* <div>
* <h2>NgFormControl Example</h2>
* <form>
* <p>Element with existing control: <input type="text"
* [ngFormControl]="loginControl"></p>
* <p>Value of existing control: {{loginControl.value}}</p>
* </form>
* </div>
* `,
* directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
* })
* export class App {
* loginControl: Control = new Control('');
* }
* ```
*
* ###ngModel
*
* We can also use `ngModel` to bind a domain model to the form.
*
* ### Example ([live demo](http://plnkr.co/edit/yHMLuHO7DNgT8XvtjTDH?p=preview))
*
* ```typescript
* @Component({
* selector: "login-comp",
* directives: [FORM_DIRECTIVES],
* template: "<input type='text' [ngFormControl]='loginControl' [(ngModel)]='login'>"
* })
* class LoginComp {
* loginControl: Control = new Control('');
* login:string;
* }
* ```
*/
export let NgFormControl = class extends NgControl {
constructor(_validators, _asyncValidators, valueAccessors) {
super();
this._validators = _validators;
this._asyncValidators = _asyncValidators;
this.update = new EventEmitter();
this.valueAccessor = selectValueAccessor(this, valueAccessors);
}
ngOnChanges(changes) {
if (this._isControlChanged(changes)) {
setUpControl(this.form, this);
this.form.updateValueAndValidity({ emitEvent: false });
}
if (isPropertyUpdated(changes, this.viewModel)) {
this.form.updateValue(this.model);
this.viewModel = this.model;
}
}
get path() { return []; }
get validator() { return composeValidators(this._validators); }
get asyncValidator() { return composeAsyncValidators(this._asyncValidators); }
get control() { return this.form; }
viewToModelUpdate(newValue) {
this.viewModel = newValue;
ObservableWrapper.callEmit(this.update, newValue);
}
_isControlChanged(changes) {
return StringMapWrapper.contains(changes, "form");
}
};
NgFormControl = __decorate([
Directive({
selector: '[ngFormControl]',
bindings: [formControlBinding],
inputs: ['form: ngFormControl', 'model: ngModel'],
outputs: ['update: ngModelChange'],
exportAs: 'ngForm'
}),
__param(0, Optional()),
__param(0, Self()),
__param(0, Inject(NG_VALIDATORS)),
__param(1, Optional()),
__param(1, Self()),
__param(1, Inject(NG_ASYNC_VALIDATORS)),
__param(2, Optional()),
__param(2, Self()),
__param(2, Inject(NG_VALUE_ACCESSOR)),
__metadata('design:paramtypes', [Array, Array, Array])
], NgFormControl);

View File

@ -0,0 +1,164 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { ListWrapper, StringMapWrapper } from 'angular2/src/facade/collection';
import { ObservableWrapper, EventEmitter } from 'angular2/src/facade/async';
import { Directive, forwardRef, Provider, Inject, Optional, Self } from 'angular2/core';
import { ControlContainer } from './control_container';
import { setUpControl, setUpControlGroup, composeValidators, composeAsyncValidators } from './shared';
import { Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '../validators';
const formDirectiveProvider = CONST_EXPR(new Provider(ControlContainer, { useExisting: forwardRef(() => NgFormModel) }));
/**
* Binds an existing control group to a DOM element.
*
* ### Example ([live demo](http://plnkr.co/edit/jqrVirudY8anJxTMUjTP?p=preview))
*
* In this example, we bind the control group to the form element, and we bind the login and
* password controls to the login and password elements.
*
* ```typescript
* @Component({
* selector: 'my-app',
* template: `
* <div>
* <h2>NgFormModel Example</h2>
* <form [ngFormModel]="loginForm">
* <p>Login: <input type="text" ngControl="login"></p>
* <p>Password: <input type="password" ngControl="password"></p>
* </form>
* <p>Value:</p>
* <pre>{{value}}</pre>
* </div>
* `,
* directives: [FORM_DIRECTIVES]
* })
* export class App {
* loginForm: ControlGroup;
*
* constructor() {
* this.loginForm = new ControlGroup({
* login: new Control(""),
* password: new Control("")
* });
* }
*
* get value(): string {
* return JSON.stringify(this.loginForm.value, null, 2);
* }
* }
* ```
*
* We can also use ngModel to bind a domain model to the form.
*
* ```typescript
* @Component({
* selector: "login-comp",
* directives: [FORM_DIRECTIVES],
* template: `
* <form [ngFormModel]='loginForm'>
* Login <input type='text' ngControl='login' [(ngModel)]='credentials.login'>
* Password <input type='password' ngControl='password'
* [(ngModel)]='credentials.password'>
* <button (click)="onLogin()">Login</button>
* </form>`
* })
* class LoginComp {
* credentials: {login: string, password: string};
* loginForm: ControlGroup;
*
* constructor() {
* this.loginForm = new ControlGroup({
* login: new Control(""),
* password: new Control("")
* });
* }
*
* onLogin(): void {
* // this.credentials.login === 'some login'
* // this.credentials.password === 'some password'
* }
* }
* ```
*/
export let NgFormModel = class extends ControlContainer {
constructor(_validators, _asyncValidators) {
super();
this._validators = _validators;
this._asyncValidators = _asyncValidators;
this.form = null;
this.directives = [];
this.ngSubmit = new EventEmitter();
}
ngOnChanges(changes) {
if (StringMapWrapper.contains(changes, "form")) {
var sync = composeValidators(this._validators);
this.form.validator = Validators.compose([this.form.validator, sync]);
var async = composeAsyncValidators(this._asyncValidators);
this.form.asyncValidator = Validators.composeAsync([this.form.asyncValidator, async]);
this.form.updateValueAndValidity({ onlySelf: true, emitEvent: false });
}
this._updateDomValue();
}
get formDirective() { return this; }
get control() { return this.form; }
get path() { return []; }
addControl(dir) {
var ctrl = this.form.find(dir.path);
setUpControl(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
this.directives.push(dir);
}
getControl(dir) { return this.form.find(dir.path); }
removeControl(dir) { ListWrapper.remove(this.directives, dir); }
addControlGroup(dir) {
var ctrl = this.form.find(dir.path);
setUpControlGroup(ctrl, dir);
ctrl.updateValueAndValidity({ emitEvent: false });
}
removeControlGroup(dir) { }
getControlGroup(dir) {
return this.form.find(dir.path);
}
updateModel(dir, value) {
var ctrl = this.form.find(dir.path);
ctrl.updateValue(value);
}
onSubmit() {
ObservableWrapper.callEmit(this.ngSubmit, null);
return false;
}
/** @internal */
_updateDomValue() {
this.directives.forEach(dir => {
var ctrl = this.form.find(dir.path);
dir.valueAccessor.writeValue(ctrl.value);
});
}
};
NgFormModel = __decorate([
Directive({
selector: '[ngFormModel]',
bindings: [formDirectiveProvider],
inputs: ['form: ngFormModel'],
host: { '(submit)': 'onSubmit()' },
outputs: ['ngSubmit'],
exportAs: 'ngForm'
}),
__param(0, Optional()),
__param(0, Self()),
__param(0, Inject(NG_VALIDATORS)),
__param(1, Optional()),
__param(1, Self()),
__param(1, Inject(NG_ASYNC_VALIDATORS)),
__metadata('design:paramtypes', [Array, Array])
], NgFormModel);

View File

@ -0,0 +1,93 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { EventEmitter, ObservableWrapper } from 'angular2/src/facade/async';
import { Directive, forwardRef, Provider, Inject, Optional, Self } from 'angular2/core';
import { NG_VALUE_ACCESSOR } from './control_value_accessor';
import { NgControl } from './ng_control';
import { Control } from '../model';
import { NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '../validators';
import { setUpControl, isPropertyUpdated, selectValueAccessor, composeValidators, composeAsyncValidators } from './shared';
const formControlBinding = CONST_EXPR(new Provider(NgControl, { useExisting: forwardRef(() => NgModel) }));
/**
* Binds a domain model to a form control.
*
* ### Usage
*
* `ngModel` binds an existing domain model to a form control. For a
* two-way binding, use `[(ngModel)]` to ensure the model updates in
* both directions.
*
* ### Example ([live demo](http://plnkr.co/edit/R3UX5qDaUqFO2VYR0UzH?p=preview))
* ```typescript
* @Component({
* selector: "search-comp",
* directives: [FORM_DIRECTIVES],
* template: `<input type='text' [(ngModel)]="searchQuery">`
* })
* class SearchComp {
* searchQuery: string;
* }
* ```
*/
export let NgModel = class extends NgControl {
constructor(_validators, _asyncValidators, valueAccessors) {
super();
this._validators = _validators;
this._asyncValidators = _asyncValidators;
/** @internal */
this._control = new Control();
/** @internal */
this._added = false;
this.update = new EventEmitter();
this.valueAccessor = selectValueAccessor(this, valueAccessors);
}
ngOnChanges(changes) {
if (!this._added) {
setUpControl(this._control, this);
this._control.updateValueAndValidity({ emitEvent: false });
this._added = true;
}
if (isPropertyUpdated(changes, this.viewModel)) {
this._control.updateValue(this.model);
this.viewModel = this.model;
}
}
get control() { return this._control; }
get path() { return []; }
get validator() { return composeValidators(this._validators); }
get asyncValidator() { return composeAsyncValidators(this._asyncValidators); }
viewToModelUpdate(newValue) {
this.viewModel = newValue;
ObservableWrapper.callEmit(this.update, newValue);
}
};
NgModel = __decorate([
Directive({
selector: '[ngModel]:not([ngControl]):not([ngFormControl])',
bindings: [formControlBinding],
inputs: ['model: ngModel'],
outputs: ['update: ngModelChange'],
exportAs: 'ngForm'
}),
__param(0, Optional()),
__param(0, Self()),
__param(0, Inject(NG_VALIDATORS)),
__param(1, Optional()),
__param(1, Self()),
__param(1, Inject(NG_ASYNC_VALIDATORS)),
__param(2, Optional()),
__param(2, Self()),
__param(2, Inject(NG_VALUE_ACCESSOR)),
__metadata('design:paramtypes', [Array, Array, Array])
], NgModel);

View File

@ -0,0 +1,16 @@
export function normalizeValidator(validator) {
if (validator.validate !== undefined) {
return (c) => validator.validate(c);
}
else {
return validator;
}
}
export function normalizeAsyncValidator(validator) {
if (validator.validate !== undefined) {
return (c) => Promise.resolve(validator.validate(c));
}
else {
return validator;
}
}

View File

@ -0,0 +1,49 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Directive, ElementRef, Renderer, forwardRef, Provider } from 'angular2/core';
import { NG_VALUE_ACCESSOR } from './control_value_accessor';
import { CONST_EXPR, NumberWrapper } from 'angular2/src/facade/lang';
const NUMBER_VALUE_ACCESSOR = CONST_EXPR(new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => NumberValueAccessor), multi: true }));
/**
* The accessor for writing a number value and listening to changes that is used by the
* {@link NgModel}, {@link NgFormControl}, and {@link NgControlName} directives.
*
* ### Example
* ```
* <input type="number" [(ngModel)]="age">
* ```
*/
export let NumberValueAccessor = class {
constructor(_renderer, _elementRef) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = (_) => { };
this.onTouched = () => { };
}
writeValue(value) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', value);
}
registerOnChange(fn) {
this.onChange = (value) => { fn(NumberWrapper.parseFloat(value)); };
}
registerOnTouched(fn) { this.onTouched = fn; }
};
NumberValueAccessor = __decorate([
Directive({
selector: 'input[type=number][ngControl],input[type=number][ngFormControl],input[type=number][ngModel]',
host: {
'(change)': 'onChange($event.target.value)',
'(input)': 'onChange($event.target.value)',
'(blur)': 'onTouched()'
},
bindings: [NUMBER_VALUE_ACCESSOR]
}),
__metadata('design:paramtypes', [Renderer, ElementRef])
], NumberValueAccessor);

View File

@ -0,0 +1,115 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Directive, ElementRef, Renderer, forwardRef, Provider, Input, Injector, Injectable } from 'angular2/core';
import { NG_VALUE_ACCESSOR } from 'angular2/src/common/forms/directives/control_value_accessor';
import { NgControl } from 'angular2/src/common/forms/directives/ng_control';
import { CONST_EXPR, isPresent } from 'angular2/src/facade/lang';
import { ListWrapper } from 'angular2/src/facade/collection';
const RADIO_VALUE_ACCESSOR = CONST_EXPR(new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => RadioControlValueAccessor), multi: true }));
/**
* Internal class used by Angular to uncheck radio buttons with the matching name.
*/
export let RadioControlRegistry = class {
constructor() {
this._accessors = [];
}
add(control, accessor) {
this._accessors.push([control, accessor]);
}
remove(accessor) {
var indexToRemove = -1;
for (var i = 0; i < this._accessors.length; ++i) {
if (this._accessors[i][1] === accessor) {
indexToRemove = i;
}
}
ListWrapper.removeAt(this._accessors, indexToRemove);
}
select(accessor) {
this._accessors.forEach((c) => {
if (c[0].control.root === accessor._control.control.root && c[1] !== accessor) {
c[1].fireUncheck();
}
});
}
};
RadioControlRegistry = __decorate([
Injectable(),
__metadata('design:paramtypes', [])
], RadioControlRegistry);
/**
* The value provided by the forms API for radio buttons.
*/
export class RadioButtonState {
constructor(checked, value) {
this.checked = checked;
this.value = value;
}
}
/**
* The accessor for writing a radio control value and listening to changes that is used by the
* {@link NgModel}, {@link NgFormControl}, and {@link NgControlName} directives.
*
* ### Example
* ```
* @Component({
* template: `
* <input type="radio" name="food" [(ngModel)]="foodChicken">
* <input type="radio" name="food" [(ngModel)]="foodFish">
* `
* })
* class FoodCmp {
* foodChicken = new RadioButtonState(true, "chicken");
* foodFish = new RadioButtonState(false, "fish");
* }
* ```
*/
export let RadioControlValueAccessor = class {
constructor(_renderer, _elementRef, _registry, _injector) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this._registry = _registry;
this._injector = _injector;
this.onChange = () => { };
this.onTouched = () => { };
}
ngOnInit() {
this._control = this._injector.get(NgControl);
this._registry.add(this._control, this);
}
ngOnDestroy() { this._registry.remove(this); }
writeValue(value) {
this._state = value;
if (isPresent(value) && value.checked) {
this._renderer.setElementProperty(this._elementRef.nativeElement, 'checked', true);
}
}
registerOnChange(fn) {
this._fn = fn;
this.onChange = () => {
fn(new RadioButtonState(true, this._state.value));
this._registry.select(this);
};
}
fireUncheck() { this._fn(new RadioButtonState(false, this._state.value)); }
registerOnTouched(fn) { this.onTouched = fn; }
};
__decorate([
Input(),
__metadata('design:type', String)
], RadioControlValueAccessor.prototype, "name", void 0);
RadioControlValueAccessor = __decorate([
Directive({
selector: 'input[type=radio][ngControl],input[type=radio][ngFormControl],input[type=radio][ngModel]',
host: { '(change)': 'onChange()', '(blur)': 'onTouched()' },
providers: [RADIO_VALUE_ACCESSOR]
}),
__metadata('design:paramtypes', [Renderer, ElementRef, RadioControlRegistry, Injector])
], RadioControlValueAccessor);

View File

@ -0,0 +1,64 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { Query, Directive, Renderer, forwardRef, Provider, ElementRef, QueryList } from 'angular2/core';
import { ObservableWrapper } from 'angular2/src/facade/async';
import { NG_VALUE_ACCESSOR } from './control_value_accessor';
import { CONST_EXPR } from 'angular2/src/facade/lang';
const SELECT_VALUE_ACCESSOR = CONST_EXPR(new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => SelectControlValueAccessor), multi: true }));
/**
* Marks `<option>` as dynamic, so Angular can be notified when options change.
*
* ### Example
*
* ```
* <select ngControl="city">
* <option *ngFor="#c of cities" [value]="c"></option>
* </select>
* ```
*/
export let NgSelectOption = class {
};
NgSelectOption = __decorate([
Directive({ selector: 'option' }),
__metadata('design:paramtypes', [])
], NgSelectOption);
/**
* The accessor for writing a value and listening to changes on a select element.
*/
export let SelectControlValueAccessor = class {
constructor(_renderer, _elementRef, query) {
this._renderer = _renderer;
this._elementRef = _elementRef;
this.onChange = (_) => { };
this.onTouched = () => { };
this._updateValueWhenListOfOptionsChanges(query);
}
writeValue(value) {
this.value = value;
this._renderer.setElementProperty(this._elementRef.nativeElement, 'value', value);
}
registerOnChange(fn) { this.onChange = fn; }
registerOnTouched(fn) { this.onTouched = fn; }
_updateValueWhenListOfOptionsChanges(query) {
ObservableWrapper.subscribe(query.changes, (_) => this.writeValue(this.value));
}
};
SelectControlValueAccessor = __decorate([
Directive({
selector: 'select[ngControl],select[ngFormControl],select[ngModel]',
host: { '(input)': 'onChange($event.target.value)', '(blur)': 'onTouched()' },
bindings: [SELECT_VALUE_ACCESSOR]
}),
__param(2, Query(NgSelectOption, { descendants: true })),
__metadata('design:paramtypes', [Renderer, ElementRef, QueryList])
], SelectControlValueAccessor);

View File

@ -0,0 +1,93 @@
import { ListWrapper, StringMapWrapper } from 'angular2/src/facade/collection';
import { isBlank, isPresent, looseIdentical, hasConstructor } from 'angular2/src/facade/lang';
import { BaseException } from 'angular2/src/facade/exceptions';
import { Validators } from '../validators';
import { DefaultValueAccessor } from './default_value_accessor';
import { NumberValueAccessor } from './number_value_accessor';
import { CheckboxControlValueAccessor } from './checkbox_value_accessor';
import { SelectControlValueAccessor } from './select_control_value_accessor';
import { RadioControlValueAccessor } from './radio_control_value_accessor';
import { normalizeValidator, normalizeAsyncValidator } from './normalize_validator';
export function controlPath(name, parent) {
var p = ListWrapper.clone(parent.path);
p.push(name);
return p;
}
export function setUpControl(control, dir) {
if (isBlank(control))
_throwError(dir, "Cannot find control");
if (isBlank(dir.valueAccessor))
_throwError(dir, "No value accessor for");
control.validator = Validators.compose([control.validator, dir.validator]);
control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);
dir.valueAccessor.writeValue(control.value);
// view -> model
dir.valueAccessor.registerOnChange((newValue) => {
dir.viewToModelUpdate(newValue);
control.updateValue(newValue, { emitModelToViewChange: false });
control.markAsDirty();
});
// model -> view
control.registerOnChange((newValue) => dir.valueAccessor.writeValue(newValue));
// touched
dir.valueAccessor.registerOnTouched(() => control.markAsTouched());
}
export function setUpControlGroup(control, dir) {
if (isBlank(control))
_throwError(dir, "Cannot find control");
control.validator = Validators.compose([control.validator, dir.validator]);
control.asyncValidator = Validators.composeAsync([control.asyncValidator, dir.asyncValidator]);
}
function _throwError(dir, message) {
var path = dir.path.join(" -> ");
throw new BaseException(`${message} '${path}'`);
}
export function composeValidators(validators) {
return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null;
}
export function composeAsyncValidators(validators) {
return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) :
null;
}
export function isPropertyUpdated(changes, viewModel) {
if (!StringMapWrapper.contains(changes, "model"))
return false;
var change = changes["model"];
if (change.isFirstChange())
return true;
return !looseIdentical(viewModel, change.currentValue);
}
// TODO: vsavkin remove it once https://github.com/angular/angular/issues/3011 is implemented
export function selectValueAccessor(dir, valueAccessors) {
if (isBlank(valueAccessors))
return null;
var defaultAccessor;
var builtinAccessor;
var customAccessor;
valueAccessors.forEach((v) => {
if (hasConstructor(v, DefaultValueAccessor)) {
defaultAccessor = v;
}
else if (hasConstructor(v, CheckboxControlValueAccessor) ||
hasConstructor(v, NumberValueAccessor) ||
hasConstructor(v, SelectControlValueAccessor) ||
hasConstructor(v, RadioControlValueAccessor)) {
if (isPresent(builtinAccessor))
_throwError(dir, "More than one built-in value accessor matches");
builtinAccessor = v;
}
else {
if (isPresent(customAccessor))
_throwError(dir, "More than one custom value accessor matches");
customAccessor = v;
}
});
if (isPresent(customAccessor))
return customAccessor;
if (isPresent(builtinAccessor))
return builtinAccessor;
if (isPresent(defaultAccessor))
return defaultAccessor;
_throwError(dir, "No valid value accessor for");
return null;
}

View File

@ -0,0 +1,115 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
import { forwardRef, Provider, Attribute, Directive } from 'angular2/core';
import { CONST_EXPR } from 'angular2/src/facade/lang';
import { Validators, NG_VALIDATORS } from '../validators';
import { NumberWrapper } from "angular2/src/facade/lang";
const REQUIRED_VALIDATOR = CONST_EXPR(new Provider(NG_VALIDATORS, { useValue: Validators.required, multi: true }));
/**
* A Directive that adds the `required` validator to any controls marked with the
* `required` attribute, via the {@link NG_VALIDATORS} binding.
*
* ### Example
*
* ```
* <input ngControl="fullName" required>
* ```
*/
export let RequiredValidator = class {
};
RequiredValidator = __decorate([
Directive({
selector: '[required][ngControl],[required][ngFormControl],[required][ngModel]',
providers: [REQUIRED_VALIDATOR]
}),
__metadata('design:paramtypes', [])
], RequiredValidator);
/**
* Provivder which adds {@link MinLengthValidator} to {@link NG_VALIDATORS}.
*
* ## Example:
*
* {@example common/forms/ts/validators/validators.ts region='min'}
*/
const MIN_LENGTH_VALIDATOR = CONST_EXPR(new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MinLengthValidator), multi: true }));
/**
* A directive which installs the {@link MinLengthValidator} for any `ngControl`,
* `ngFormControl`, or control with `ngModel` that also has a `minlength` attribute.
*/
export let MinLengthValidator = class {
constructor(minLength) {
this._validator = Validators.minLength(NumberWrapper.parseInt(minLength, 10));
}
validate(c) { return this._validator(c); }
};
MinLengthValidator = __decorate([
Directive({
selector: '[minlength][ngControl],[minlength][ngFormControl],[minlength][ngModel]',
providers: [MIN_LENGTH_VALIDATOR]
}),
__param(0, Attribute("minlength")),
__metadata('design:paramtypes', [String])
], MinLengthValidator);
/**
* Provider which adds {@link MaxLengthValidator} to {@link NG_VALIDATORS}.
*
* ## Example:
*
* {@example common/forms/ts/validators/validators.ts region='max'}
*/
const MAX_LENGTH_VALIDATOR = CONST_EXPR(new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => MaxLengthValidator), multi: true }));
/**
* A directive which installs the {@link MaxLengthValidator} for any `ngControl, `ngFormControl`,
* or control with `ngModel` that also has a `maxlength` attribute.
*/
export let MaxLengthValidator = class {
constructor(maxLength) {
this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10));
}
validate(c) { return this._validator(c); }
};
MaxLengthValidator = __decorate([
Directive({
selector: '[maxlength][ngControl],[maxlength][ngFormControl],[maxlength][ngModel]',
providers: [MAX_LENGTH_VALIDATOR]
}),
__param(0, Attribute("maxlength")),
__metadata('design:paramtypes', [String])
], MaxLengthValidator);
/**
* A Directive that adds the `pattern` validator to any controls marked with the
* `pattern` attribute, via the {@link NG_VALIDATORS} binding. Uses attribute value
* as the regex to validate Control value against. Follows pattern attribute
* semantics; i.e. regex must match entire Control value.
*
* ### Example
*
* ```
* <input [ngControl]="fullName" pattern="[a-zA-Z ]*">
* ```
*/
const PATTERN_VALIDATOR = CONST_EXPR(new Provider(NG_VALIDATORS, { useExisting: forwardRef(() => PatternValidator), multi: true }));
export let PatternValidator = class {
constructor(pattern) {
this._validator = Validators.pattern(pattern);
}
validate(c) { return this._validator(c); }
};
PatternValidator = __decorate([
Directive({
selector: '[pattern][ngControl],[pattern][ngFormControl],[pattern][ngModel]',
providers: [PATTERN_VALIDATOR]
}),
__param(0, Attribute("pattern")),
__metadata('design:paramtypes', [String])
], PatternValidator);

View File

@ -0,0 +1,112 @@
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Injectable } from 'angular2/core';
import { StringMapWrapper } from 'angular2/src/facade/collection';
import { isPresent, isArray } from 'angular2/src/facade/lang';
import * as modelModule from './model';
/**
* Creates a form object from a user-specified configuration.
*
* ### Example ([live demo](http://plnkr.co/edit/ENgZo8EuIECZNensZCVr?p=preview))
*
* ```typescript
* @Component({
* selector: 'my-app',
* viewBindings: [FORM_BINDINGS]
* template: `
* <form [ngFormModel]="loginForm">
* <p>Login <input ngControl="login"></p>
* <div ngControlGroup="passwordRetry">
* <p>Password <input type="password" ngControl="password"></p>
* <p>Confirm password <input type="password" ngControl="passwordConfirmation"></p>
* </div>
* </form>
* <h3>Form value:</h3>
* <pre>{{value}}</pre>
* `,
* directives: [FORM_DIRECTIVES]
* })
* export class App {
* loginForm: ControlGroup;
*
* constructor(builder: FormBuilder) {
* this.loginForm = builder.group({
* login: ["", Validators.required],
* passwordRetry: builder.group({
* password: ["", Validators.required],
* passwordConfirmation: ["", Validators.required, asyncValidator]
* })
* });
* }
*
* get value(): string {
* return JSON.stringify(this.loginForm.value, null, 2);
* }
* }
* ```
*/
export let FormBuilder = class {
/**
* Construct a new {@link ControlGroup} with the given map of configuration.
* Valid keys for the `extra` parameter map are `optionals` and `validator`.
*
* See the {@link ControlGroup} constructor for more details.
*/
group(controlsConfig, extra = null) {
var controls = this._reduceControls(controlsConfig);
var optionals = (isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null);
var validator = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null;
var asyncValidator = isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null;
return new modelModule.ControlGroup(controls, optionals, validator, asyncValidator);
}
/**
* Construct a new {@link Control} with the given `value`,`validator`, and `asyncValidator`.
*/
control(value, validator = null, asyncValidator = null) {
return new modelModule.Control(value, validator, asyncValidator);
}
/**
* Construct an array of {@link Control}s from the given `controlsConfig` array of
* configuration, with the given optional `validator` and `asyncValidator`.
*/
array(controlsConfig, validator = null, asyncValidator = null) {
var controls = controlsConfig.map(c => this._createControl(c));
return new modelModule.ControlArray(controls, validator, asyncValidator);
}
/** @internal */
_reduceControls(controlsConfig) {
var controls = {};
StringMapWrapper.forEach(controlsConfig, (controlConfig, controlName) => {
controls[controlName] = this._createControl(controlConfig);
});
return controls;
}
/** @internal */
_createControl(controlConfig) {
if (controlConfig instanceof modelModule.Control ||
controlConfig instanceof modelModule.ControlGroup ||
controlConfig instanceof modelModule.ControlArray) {
return controlConfig;
}
else if (isArray(controlConfig)) {
var value = controlConfig[0];
var validator = controlConfig.length > 1 ? controlConfig[1] : null;
var asyncValidator = controlConfig.length > 2 ? controlConfig[2] : null;
return this.control(value, validator, asyncValidator);
}
else {
return this.control(controlConfig);
}
}
};
FormBuilder = __decorate([
Injectable(),
__metadata('design:paramtypes', [])
], FormBuilder);

Some files were not shown because too many files have changed in this diff Show More