style(lint): re-format modules/@angular

This commit is contained in:
Alex Eagle 2016-06-08 16:38:52 -07:00
parent bbed364e7b
commit f39c9c9e75
589 changed files with 21829 additions and 24259 deletions

View File

@ -9,7 +9,7 @@ require('./tools/check-environment')(
const gulp = require('gulp');
const path = require('path');
const srcsToFmt = ['tools/**/*.ts'];
const srcsToFmt = ['tools/**/*.ts', 'modules/@angular/**/*.ts'];
gulp.task('format:enforce', () => {
const format = require('gulp-clang-format');

View File

@ -1,6 +1,8 @@
import {Type} from '@angular/core';
import {FORM_DIRECTIVES} from './forms-deprecated';
import {CORE_DIRECTIVES} from './directives';
import {FORM_DIRECTIVES} from './forms-deprecated';
/**
* A collection of Angular core directives that are likely to be used in each and every Angular

View File

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

View File

@ -1,11 +1,13 @@
import {Type} from '../facade/lang';
import {NgClass} from './ng_class';
import {NgFor} from './ng_for';
import {NgIf} from './ng_if';
import {NgTemplateOutlet} from './ng_template_outlet';
import {NgStyle} from './ng_style';
import {NgSwitch, NgSwitchWhen, NgSwitchDefault} from './ng_switch';
import {NgPlural, NgPluralCase} from './ng_plural';
import {NgStyle} from './ng_style';
import {NgSwitch, NgSwitchDefault, NgSwitchWhen} from './ng_switch';
import {NgTemplateOutlet} from './ng_template_outlet';
/**
* A collection of Angular core directives that are likely to be used in each and every Angular
@ -59,5 +61,5 @@ export const CORE_DIRECTIVES: Type[] = /*@ts2dart_const*/[
NgSwitchWhen,
NgSwitchDefault,
NgPlural,
NgPluralCase
NgPluralCase,
];

View File

@ -1,18 +1,8 @@
import {
DoCheck,
OnDestroy,
Directive,
ElementRef,
IterableDiffers,
KeyValueDiffers,
Renderer,
IterableDiffer,
KeyValueDiffer,
CollectionChangeRecord,
KeyValueChangeRecord
} from '@angular/core';
import {isPresent, isString, isArray} from '../facade/lang';
import {CollectionChangeRecord, Directive, DoCheck, ElementRef, IterableDiffer, IterableDiffers, KeyValueChangeRecord, KeyValueDiffer, KeyValueDiffers, OnDestroy, Renderer} from '@angular/core';
import {StringMapWrapper, isListLikeIterable} from '../facade/collection';
import {isArray, isPresent, isString} from '../facade/lang';
/**
* The `NgClass` directive conditionally adds and removes CSS classes on an HTML element based on
@ -82,7 +72,8 @@ export class NgClass implements DoCheck, OnDestroy {
private _initialClasses: string[] = [];
private _rawClass: string[]|Set<string>;
constructor(private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers,
constructor(
private _iterableDiffers: IterableDiffers, private _keyValueDiffers: KeyValueDiffers,
private _ngEl: ElementRef, private _renderer: Renderer) {}
set initialClasses(v: string) {
@ -156,16 +147,16 @@ export class NgClass implements DoCheck, OnDestroy {
this._initialClasses.forEach(className => this._toggleClass(className, !isCleanup));
}
private _applyClasses(rawClassVal: string[] | Set<string>| {[key: string]: any},
isCleanup: boolean) {
private _applyClasses(
rawClassVal: string[]|Set<string>|{[key: string]: any}, isCleanup: boolean) {
if (isPresent(rawClassVal)) {
if (isArray(rawClassVal)) {
(<string[]>rawClassVal).forEach(className => this._toggleClass(className, !isCleanup));
} else if (rawClassVal instanceof Set) {
(<Set<string>>rawClassVal).forEach(className => this._toggleClass(className, !isCleanup));
} else {
StringMapWrapper.forEach(<{[k: string]: any}>rawClassVal,
(expVal: any, className: string) => {
StringMapWrapper.forEach(
<{[k: string]: any}>rawClassVal, (expVal: any, className: string) => {
if (isPresent(expVal)) this._toggleClass(className, !isCleanup);
});
}

View File

@ -1,18 +1,7 @@
import {
DoCheck,
Directive,
ChangeDetectorRef,
IterableDiffer,
IterableDiffers,
ViewContainerRef,
TemplateRef,
EmbeddedViewRef,
TrackByFn,
DefaultIterableDiffer,
CollectionChangeRecord
} from '@angular/core';
import {isPresent, isBlank, getTypeNameForDebugging} from '../facade/lang';
import {ChangeDetectorRef, CollectionChangeRecord, DefaultIterableDiffer, Directive, DoCheck, EmbeddedViewRef, IterableDiffer, IterableDiffers, TemplateRef, TrackByFn, ViewContainerRef} from '@angular/core';
import {BaseException} from '../facade/exceptions';
import {getTypeNameForDebugging, isBlank, isPresent} from '../facade/lang';
export class NgForRow {
constructor(public $implicit: any, public index: number, public count: number) {}
@ -87,7 +76,8 @@ export class NgFor implements DoCheck {
_ngForTrackBy: TrackByFn;
private _differ: IterableDiffer;
constructor(private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef<NgForRow>,
constructor(
private _viewContainer: ViewContainerRef, private _templateRef: TemplateRef<NgForRow>,
private _iterableDiffers: IterableDiffers, private _cdr: ChangeDetectorRef) {}
set ngForOf(value: any) {
@ -121,15 +111,18 @@ export class NgFor implements DoCheck {
// TODO(rado): check if change detection can produce a change record that is
// easier to consume than current.
var recordViewTuples: RecordViewTuple[] = [];
changes.forEachRemovedItem((removedRecord: CollectionChangeRecord) =>
changes.forEachRemovedItem(
(removedRecord: CollectionChangeRecord) =>
recordViewTuples.push(new RecordViewTuple(removedRecord, null)));
changes.forEachMovedItem((movedRecord: CollectionChangeRecord) =>
changes.forEachMovedItem(
(movedRecord: CollectionChangeRecord) =>
recordViewTuples.push(new RecordViewTuple(movedRecord, null)));
var insertTuples = this._bulkRemove(recordViewTuples);
changes.forEachAddedItem((addedRecord: CollectionChangeRecord) =>
changes.forEachAddedItem(
(addedRecord: CollectionChangeRecord) =>
insertTuples.push(new RecordViewTuple(addedRecord, null)));
this._bulkInsert(insertTuples);
@ -155,7 +148,8 @@ export class NgFor implements DoCheck {
}
private _bulkRemove(tuples: RecordViewTuple[]): RecordViewTuple[] {
tuples.sort((a: RecordViewTuple, b: RecordViewTuple) =>
tuples.sort(
(a: RecordViewTuple, b: RecordViewTuple) =>
a.record.previousIndex - b.record.previousIndex);
var movedTuples: RecordViewTuple[] = [];
for (var i = tuples.length - 1; i >= 0; i--) {

View File

@ -1,6 +1,8 @@
import {Directive, ViewContainerRef, TemplateRef} from '@angular/core';
import {Directive, TemplateRef, ViewContainerRef} from '@angular/core';
import {isBlank} from '../facade/lang';
/**
* Removes or recreates a portion of the DOM tree based on an {expression}.
*

View File

@ -1,15 +1,7 @@
import {
Directive,
ViewContainerRef,
TemplateRef,
ContentChildren,
QueryList,
Attribute,
AfterContentInit,
Input
} from '@angular/core';
import {isPresent, NumberWrapper} from '../facade/lang';
import {AfterContentInit, Attribute, ContentChildren, Directive, Input, QueryList, TemplateRef, ViewContainerRef} from '@angular/core';
import {Map} from '../facade/collection';
import {NumberWrapper, isPresent} from '../facade/lang';
import {SwitchView} from './ng_switch';
@ -81,7 +73,8 @@ export abstract class NgLocalization { abstract getPluralCategory(value: any): s
export class NgPluralCase {
/** @internal */
_view: SwitchView;
constructor(@Attribute('ngPluralCase') public value: string, template: TemplateRef<Object>,
constructor(
@Attribute('ngPluralCase') public value: string, template: TemplateRef<Object>,
viewContainer: ViewContainerRef) {
this._view = new SwitchView(viewContainer, template);
}
@ -143,7 +136,7 @@ export class NgPlural implements AfterContentInit {
}
/** @internal */
_isValueView(pluralCase: NgPluralCase): boolean { return pluralCase.value[0] === "="; }
_isValueView(pluralCase: NgPluralCase): boolean { return pluralCase.value[0] === '='; }
/** @internal */
_formatValue(pluralCase: NgPluralCase): any {

View File

@ -1,13 +1,7 @@
import {
DoCheck,
KeyValueChangeRecord,
KeyValueDiffer,
KeyValueDiffers,
ElementRef,
Directive,
Renderer
} from '@angular/core';
import {isPresent, isBlank} from '../facade/lang';
import {Directive, DoCheck, ElementRef, KeyValueChangeRecord, KeyValueDiffer, KeyValueDiffers, Renderer} from '@angular/core';
import {isBlank, isPresent} from '../facade/lang';
/**
* The `NgStyle` directive changes styles based on a result of expression evaluation.
@ -69,8 +63,8 @@ export class NgStyle implements DoCheck {
/** @internal */
_differ: KeyValueDiffer;
constructor(private _differs: KeyValueDiffers, private _ngEl: ElementRef,
private _renderer: Renderer) {}
constructor(
private _differs: KeyValueDiffers, private _ngEl: ElementRef, private _renderer: Renderer) {}
set rawStyle(v: {[key: string]: string}) {
this._rawStyle = v;

View File

@ -1,12 +1,13 @@
import {Directive, Host, ViewContainerRef, TemplateRef} from '@angular/core';
import {isPresent, isBlank, normalizeBlank} from '../facade/lang';
import {Directive, Host, TemplateRef, ViewContainerRef} from '@angular/core';
import {ListWrapper, Map} from '../facade/collection';
import {isBlank, isPresent, normalizeBlank} from '../facade/lang';
const _WHEN_DEFAULT = /*@ts2dart_const*/ new Object();
export class SwitchView {
constructor(private _viewContainerRef: ViewContainerRef,
private _templateRef: TemplateRef<Object>) {}
constructor(
private _viewContainerRef: ViewContainerRef, private _templateRef: TemplateRef<Object>) {}
create(): void { this._viewContainerRef.createEmbeddedView(this._templateRef); }
@ -180,7 +181,8 @@ export class NgSwitchWhen {
_view: SwitchView;
private _switch: NgSwitch;
constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef<Object>,
constructor(
viewContainer: ViewContainerRef, templateRef: TemplateRef<Object>,
@Host() ngSwitch: NgSwitch) {
this._switch = ngSwitch;
this._view = new SwitchView(viewContainer, templateRef);
@ -202,7 +204,8 @@ export class NgSwitchWhen {
*/
@Directive({selector: '[ngSwitchDefault]'})
export class NgSwitchDefault {
constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef<Object>,
constructor(
viewContainer: ViewContainerRef, templateRef: TemplateRef<Object>,
@Host() sswitch: NgSwitch) {
sswitch._registerView(_WHEN_DEFAULT, new SwitchView(viewContainer, templateRef));
}

View File

@ -1,6 +1,8 @@
import {Directive, Input, ViewContainerRef, ViewRef, TemplateRef} from '@angular/core';
import {Directive, Input, TemplateRef, ViewContainerRef, ViewRef} from '@angular/core';
import {isPresent} from '../facade/lang';
/**
* Creates and inserts an embedded view based on a prepared `TemplateRef`.
*

View File

@ -10,39 +10,32 @@
* Forms providers are not included in default providers; you must import these providers
* explicitly.
*/
export {AbstractControl, Control, ControlGroup, ControlArray} from './forms-deprecated/model';
import {Type} from '@angular/core';
import {RadioControlRegistry} from './forms-deprecated/directives/radio_control_value_accessor';
import {FormBuilder} from './forms-deprecated/form_builder';
export {FORM_DIRECTIVES, RadioButtonState} from './forms-deprecated/directives';
export {AbstractControlDirective} from './forms-deprecated/directives/abstract_control_directive';
export {Form} from './forms-deprecated/directives/form_interface';
export {CheckboxControlValueAccessor} from './forms-deprecated/directives/checkbox_value_accessor';
export {ControlContainer} from './forms-deprecated/directives/control_container';
export {NgControlName} from './forms-deprecated/directives/ng_control_name';
export {NgFormControl} from './forms-deprecated/directives/ng_form_control';
export {NgModel} from './forms-deprecated/directives/ng_model';
export {NgControl} from './forms-deprecated/directives/ng_control';
export {NgControlGroup} from './forms-deprecated/directives/ng_control_group';
export {NgFormModel} from './forms-deprecated/directives/ng_form_model';
export {NgForm} from './forms-deprecated/directives/ng_form';
export {ControlValueAccessor, NG_VALUE_ACCESSOR} from './forms-deprecated/directives/control_value_accessor';
export {DefaultValueAccessor} from './forms-deprecated/directives/default_value_accessor';
export {Form} from './forms-deprecated/directives/form_interface';
export {NgControl} from './forms-deprecated/directives/ng_control';
export {NgControlGroup} from './forms-deprecated/directives/ng_control_group';
export {NgControlName} from './forms-deprecated/directives/ng_control_name';
export {NgControlStatus} from './forms-deprecated/directives/ng_control_status';
export {CheckboxControlValueAccessor} from './forms-deprecated/directives/checkbox_value_accessor';
export {
NgSelectOption,
SelectControlValueAccessor
} from './forms-deprecated/directives/select_control_value_accessor';
export {FORM_DIRECTIVES, RadioButtonState} from './forms-deprecated/directives';
export {NG_VALIDATORS, NG_ASYNC_VALIDATORS, Validators} from './forms-deprecated/validators';
export {
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator,
Validator
} from './forms-deprecated/directives/validators';
export {NgForm} from './forms-deprecated/directives/ng_form';
export {NgFormControl} from './forms-deprecated/directives/ng_form_control';
export {NgFormModel} from './forms-deprecated/directives/ng_form_model';
export {NgModel} from './forms-deprecated/directives/ng_model';
export {NgSelectOption, SelectControlValueAccessor} from './forms-deprecated/directives/select_control_value_accessor';
export {MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator, Validator} from './forms-deprecated/directives/validators';
export {FormBuilder} from './forms-deprecated/form_builder';
import {FormBuilder} from './forms-deprecated/form_builder';
import {RadioControlRegistry} from './forms-deprecated/directives/radio_control_value_accessor';
import {Type} from '@angular/core';
export {AbstractControl, Control, ControlArray, ControlGroup} from './forms-deprecated/model';
export {NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators} from './forms-deprecated/validators';
/**
* Shorthand set of providers used for building Angular forms.

View File

@ -1,60 +1,37 @@
import {Type} from '@angular/core';
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 {DefaultValueAccessor} from './directives/default_value_accessor';
import {NgControlGroup} from './directives/ng_control_group';
import {NgControlName} from './directives/ng_control_name';
import {NgControlStatus} from './directives/ng_control_status';
import {NgForm} from './directives/ng_form';
import {NgFormControl} from './directives/ng_form_control';
import {NgFormModel} from './directives/ng_form_model';
import {NgModel} from './directives/ng_model';
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 {
SelectMultipleControlValueAccessor,
NgSelectMultipleOption
} from './directives/select_multiple_control_value_accessor';
import {
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator
} from './directives/validators';
import {NgSelectOption, SelectControlValueAccessor} from './directives/select_control_value_accessor';
import {NgSelectMultipleOption, SelectMultipleControlValueAccessor} from './directives/select_multiple_control_value_accessor';
import {MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator} 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 {
SelectMultipleControlValueAccessor,
NgSelectMultipleOption
} from './directives/select_multiple_control_value_accessor';
export {
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator
} from './directives/validators';
export {NgControl} from './directives/ng_control';
export {ControlValueAccessor} from './directives/control_value_accessor';
export {DefaultValueAccessor} from './directives/default_value_accessor';
export {NgControl} from './directives/ng_control';
export {NgControlGroup} from './directives/ng_control_group';
export {NgControlName} from './directives/ng_control_name';
export {NgControlStatus} from './directives/ng_control_status';
export {NgForm} from './directives/ng_form';
export {NgFormControl} from './directives/ng_form_control';
export {NgFormModel} from './directives/ng_form_model';
export {NgModel} from './directives/ng_model';
export {NumberValueAccessor} from './directives/number_value_accessor';
export {RadioButtonState, RadioControlValueAccessor} from './directives/radio_control_value_accessor';
export {NgSelectOption, SelectControlValueAccessor} from './directives/select_control_value_accessor';
export {NgSelectMultipleOption, SelectMultipleControlValueAccessor} from './directives/select_multiple_control_value_accessor';
export {MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator} from './directives/validators';
/**
*
@ -95,5 +72,5 @@ export const FORM_DIRECTIVES: Type[] = /*@ts2dart_const*/[
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator
PatternValidator,
];

View File

@ -1,6 +1,7 @@
import {AbstractControl} from '../model';
import {isPresent} from '../../facade/lang';
import {unimplemented} from '../../facade/exceptions';
import {isPresent} from '../../facade/lang';
import {AbstractControl} from '../model';
/**
* Base class for control directives.

View File

@ -1,5 +1,6 @@
import {Directive, Renderer, ElementRef, forwardRef} from '@angular/core';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {Directive, ElementRef, Renderer, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
export const CHECKBOX_VALUE_ACCESSOR: any = /*@ts2dart_const*/ {
provide: NG_VALUE_ACCESSOR,

View File

@ -1,5 +1,6 @@
import {Form} from './form_interface';
import {AbstractControlDirective} from './abstract_control_directive';
import {Form} from './form_interface';
/**
* A directive that contains multiple {@link NgControl}s.

View File

@ -34,4 +34,4 @@ export interface ControlValueAccessor {
* @experimental
*/
export const NG_VALUE_ACCESSOR: OpaqueToken =
/*@ts2dart_const*/ new OpaqueToken("NgValueAccessor");
/*@ts2dart_const*/ new OpaqueToken('NgValueAccessor');

View File

@ -1,6 +1,8 @@
import {Directive, ElementRef, Renderer, forwardRef} from '@angular/core';
import {isBlank} from '../../facade/lang';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
export const DEFAULT_VALUE_ACCESSOR: any = /*@ts2dart_const*/
/* @ts2dart_Provider */ {

View File

@ -1,6 +1,8 @@
import {Control, ControlGroup} from '../model';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {Control, ControlGroup} from '../model';
/**
* An interface that {@link NgFormModel} and {@link NgForm} implement.

View File

@ -1,9 +1,10 @@
import {unimplemented} from '../../facade/exceptions';
import {ControlValueAccessor} from './control_value_accessor';
import {AbstractControlDirective} from './abstract_control_directive';
import {ControlValueAccessor} from './control_value_accessor';
import {AsyncValidatorFn, ValidatorFn} from './validators';
/**
* A base class that all control directive extend.
* It binds a {@link Control} object to a DOM element.

View File

@ -1,19 +1,11 @@
import {
OnInit,
OnDestroy,
Directive,
Optional,
Inject,
Host,
SkipSelf,
forwardRef,
Self
} from '@angular/core';
import {ControlContainer} from './control_container';
import {controlPath, composeValidators, composeAsyncValidators} from './shared';
import {Directive, Host, Inject, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core';
import {ControlGroup} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlContainer} from './control_container';
import {Form} from './form_interface';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {composeAsyncValidators, composeValidators, controlPath} from './shared';
import {AsyncValidatorFn, ValidatorFn} from './validators';
export const controlGroupProvider: any =
@ -79,7 +71,8 @@ export class NgControlGroup extends ControlContainer implements OnInit,
/** @internal */
_parent: ControlContainer;
constructor(@Host() @SkipSelf() parent: ControlContainer,
constructor(
@Host() @SkipSelf() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) {
super();

View File

@ -1,30 +1,14 @@
import {
OnChanges,
OnDestroy,
SimpleChanges,
Directive,
forwardRef,
Host,
SkipSelf,
Inject,
Optional,
Self
} from '@angular/core';
import {Directive, Host, Inject, OnChanges, OnDestroy, Optional, Self, SimpleChanges, SkipSelf, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {ControlContainer} from './control_container';
import {NgControl} from './ng_control';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {
controlPath,
composeValidators,
composeAsyncValidators,
isPropertyUpdated,
selectValueAccessor
} from './shared';
import {Control} from '../model';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {ValidatorFn, AsyncValidatorFn} from './validators';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlContainer} from './control_container';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {NgControl} from './ng_control';
import {composeAsyncValidators, composeValidators, controlPath, isPropertyUpdated, selectValueAccessor} from './shared';
import {AsyncValidatorFn, ValidatorFn} from './validators';
export const controlNameBinding: any =
@ -140,7 +124,9 @@ export class NgControlName extends NgControl implements OnChanges,
get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
get asyncValidator(): AsyncValidatorFn {
return composeAsyncValidators(this._asyncValidators);
}
get control(): Control { return this.formDirective.getControl(this); }
}

View File

@ -1,7 +1,10 @@
import {Directive, Self} from '@angular/core';
import {NgControl} from './ng_control';
import {isPresent} from '../../facade/lang';
import {NgControl} from './ng_control';
/**
* Directive automatically applied to Angular forms that sets CSS classes
* based on control status (valid/invalid/dirty/etc).

View File

@ -1,18 +1,16 @@
import {Directive, forwardRef, Optional, Inject, Self} from '@angular/core';
import {
PromiseWrapper,
ObservableWrapper,
EventEmitter
} from '../../facade/async';
import {Directive, Inject, Optional, Self, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper, PromiseWrapper} from '../../facade/async';
import {ListWrapper} from '../../facade/collection';
import {isPresent} from '../../facade/lang';
import {NgControl} from './ng_control';
import {Form} from './form_interface';
import {NgControlGroup} from './ng_control_group';
import {AbstractControl, Control, ControlGroup} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlContainer} from './control_container';
import {AbstractControl, ControlGroup, Control} from '../model';
import {setUpControl, setUpControlGroup, composeValidators, composeAsyncValidators} from './shared';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {Form} from './form_interface';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {composeAsyncValidators, composeValidators, setUpControl, setUpControlGroup} from './shared';
export const formDirectiveProvider: any =
/*@ts2dart_const*/ {provide: ControlContainer, useExisting: forwardRef(() => NgForm)};
@ -93,11 +91,12 @@ export class NgForm extends ControlContainer implements Form {
form: ControlGroup;
ngSubmit = new EventEmitter();
constructor(@Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],
constructor(
@Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) {
super();
this.form = new ControlGroup({}, null, composeValidators(validators),
composeAsyncValidators(asyncValidators));
this.form = new ControlGroup(
{}, null, composeValidators(validators), composeAsyncValidators(asyncValidators));
}
get submitted(): boolean { return this._submitted; }

View File

@ -1,28 +1,14 @@
import {
OnChanges,
SimpleChanges,
Directive,
forwardRef,
Inject,
Optional,
Self
} from '@angular/core';
import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core';
import {StringMapWrapper} from '../../facade/collection';
import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {NgControl} from './ng_control';
import {StringMapWrapper} from '../../facade/collection';
import {Control} from '../model';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {
setUpControl,
composeValidators,
composeAsyncValidators,
isPropertyUpdated,
selectValueAccessor
} from './shared';
import {ValidatorFn, AsyncValidatorFn} from './validators';
import {NgControl} from './ng_control';
import {composeAsyncValidators, composeValidators, isPropertyUpdated, selectValueAccessor, setUpControl} from './shared';
import {AsyncValidatorFn, ValidatorFn} from './validators';
export const formControlBinding: any =
/*@ts2dart_const*/ /* @ts2dart_Provider */ {
@ -117,7 +103,9 @@ export class NgFormControl extends NgControl implements OnChanges {
get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
get asyncValidator(): AsyncValidatorFn {
return composeAsyncValidators(this._asyncValidators);
}
get control(): Control { return this.form; }
@ -127,6 +115,6 @@ export class NgFormControl extends NgControl implements OnChanges {
}
private _isControlChanged(changes: {[key: string]: any}): boolean {
return StringMapWrapper.contains(changes, "form");
return StringMapWrapper.contains(changes, 'form');
}
}

View File

@ -1,23 +1,17 @@
import {
SimpleChanges,
OnChanges,
Directive,
forwardRef,
Inject,
Optional,
Self
} from '@angular/core';
import {isBlank} from '../../facade/lang';
import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {ListWrapper, StringMapWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions';
import {ObservableWrapper, EventEmitter} from '../../facade/async';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {isBlank} from '../../facade/lang';
import {Control, ControlGroup} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators} from '../validators';
import {ControlContainer} from './control_container';
import {Form} from './form_interface';
import {Control, ControlGroup} from '../model';
import {setUpControl, setUpControlGroup, composeValidators, composeAsyncValidators} from './shared';
import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {composeAsyncValidators, composeValidators, setUpControl, setUpControlGroup} from './shared';
export const formDirectiveProvider: any =
/*@ts2dart_const*/ /* @ts2dart_Provider */ {
@ -115,14 +109,15 @@ export class NgFormModel extends ControlContainer implements Form,
directives: NgControl[] = [];
ngSubmit = new EventEmitter();
constructor(@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
constructor(
@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) {
super();
}
ngOnChanges(changes: SimpleChanges): void {
this._checkFormPresent();
if (StringMapWrapper.contains(changes, "form")) {
if (StringMapWrapper.contains(changes, 'form')) {
var sync = composeValidators(this._validators);
this.form.validator = Validators.compose([this.form.validator, sync]);

View File

@ -1,25 +1,13 @@
import {
OnChanges,
SimpleChanges,
Directive,
forwardRef,
Inject,
Optional,
Self
} from '@angular/core';
import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {Control} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlValueAccessor, 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';
import {ValidatorFn, AsyncValidatorFn} from './validators';
import {composeAsyncValidators, composeValidators, isPropertyUpdated, selectValueAccessor, setUpControl} from './shared';
import {AsyncValidatorFn, ValidatorFn} from './validators';
export const formControlBinding: any =
/*@ts2dart_const*/ /* @ts2dart_Provider */ {
@ -93,7 +81,9 @@ export class NgModel extends NgControl implements OnChanges {
get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
get asyncValidator(): AsyncValidatorFn {
return composeAsyncValidators(this._asyncValidators);
}
viewToModelUpdate(newValue: any): void {
this.viewModel = newValue;

View File

@ -1,5 +1,6 @@
import {AbstractControl} from '../model';
import {Validator, ValidatorFn, AsyncValidatorFn} from './validators';
import {AsyncValidatorFn, Validator, ValidatorFn} from './validators';
export function normalizeValidator(validator: ValidatorFn | Validator): ValidatorFn {
if ((<Validator>validator).validate !== undefined) {

View File

@ -1,6 +1,8 @@
import {Directive, ElementRef, Renderer, forwardRef} from '@angular/core';
import {NumberWrapper} from '../../facade/lang';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
export const NUMBER_VALUE_ACCESSOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*/ {
provide: NG_VALUE_ACCESSOR,

View File

@ -1,17 +1,9 @@
import {
Directive,
ElementRef,
Renderer,
forwardRef,
Input,
OnInit,
OnDestroy,
Injector,
Injectable
} from '@angular/core';
import {isPresent} from '../../facade/lang';
import {Directive, ElementRef, Injectable, Injector, Input, OnDestroy, OnInit, Renderer, forwardRef} from '@angular/core';
import {ListWrapper} from '../../facade/collection';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {isPresent} from '../../facade/lang';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {NgControl} from './ng_control';
export const RADIO_VALUE_ACCESSOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*/ {
@ -49,8 +41,8 @@ export class RadioControlRegistry {
});
}
private _isSameGroup(controlPair:[NgControl, RadioControlValueAccessor],
accessor: RadioControlValueAccessor) {
private _isSameGroup(
controlPair: [NgControl, RadioControlValueAccessor], accessor: RadioControlValueAccessor) {
return controlPair[0].control.root === accessor._control.control.root &&
controlPair[1].name === accessor.name;
}
@ -102,7 +94,8 @@ export class RadioControlValueAccessor implements ControlValueAccessor,
onChange = () => {};
onTouched = () => {};
constructor(private _renderer: Renderer, private _elementRef: ElementRef,
constructor(
private _renderer: Renderer, private _elementRef: ElementRef,
private _registry: RadioControlRegistry, private _injector: Injector) {}
ngOnInit(): void {

View File

@ -1,23 +1,9 @@
import {
Directive,
Renderer,
forwardRef,
ElementRef,
Input,
Host,
OnDestroy,
Optional
} from '@angular/core';
import {
StringWrapper,
isPrimitive,
isPresent,
isBlank,
looseIdentical
} from '../../facade/lang';
import {MapWrapper} from '../../facade/collection';
import {Directive, ElementRef, Host, Input, OnDestroy, Optional, Renderer, forwardRef} from '@angular/core';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {MapWrapper} from '../../facade/collection';
import {StringWrapper, isBlank, isPresent, isPrimitive, looseIdentical} from '../../facade/lang';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
export const SELECT_VALUE_ACCESSOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*/ {
provide: NG_VALUE_ACCESSOR,
@ -27,12 +13,12 @@ export const SELECT_VALUE_ACCESSOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider
function _buildValueString(id: string, value: any): string {
if (isBlank(id)) return `${value}`;
if (!isPrimitive(value)) value = "Object";
if (!isPrimitive(value)) value = 'Object';
return StringWrapper.slice(`${id}: ${value}`, 0, 50);
}
function _extractId(valueString: string): string {
return valueString.split(":")[0];
return valueString.split(':')[0];
}
/**
@ -112,7 +98,8 @@ export class SelectControlValueAccessor implements ControlValueAccessor {
export class NgSelectOption implements OnDestroy {
id: string;
constructor(private _element: ElementRef, private _renderer: Renderer,
constructor(
private _element: ElementRef, private _renderer: Renderer,
@Optional() @Host() private _select: SelectControlValueAccessor) {
if (isPresent(this._select)) this.id = this._select._registerOption();
}

View File

@ -1,23 +1,9 @@
import {
Input,
Directive,
ElementRef,
Renderer,
Optional,
Host,
OnDestroy,
forwardRef
} from "@angular/core";
import {
isBlank,
isPrimitive,
StringWrapper,
isPresent,
looseIdentical,
isString
} from '../../facade/lang';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {Directive, ElementRef, Host, Input, OnDestroy, Optional, Renderer, forwardRef} from '@angular/core';
import {MapWrapper} from '../../facade/collection';
import {StringWrapper, isBlank, isPresent, isPrimitive, isString, looseIdentical} from '../../facade/lang';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
const SELECT_MULTIPLE_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
@ -28,12 +14,12 @@ const SELECT_MULTIPLE_VALUE_ACCESSOR = {
function _buildValueString(id: string, value: any): string {
if (isBlank(id)) return `${value}`;
if (isString(value)) value = `'${value}'`;
if (!isPrimitive(value)) value = "Object";
if (!isPrimitive(value)) value = 'Object';
return StringWrapper.slice(`${id}: ${value}`, 0, 50);
}
function _extractId(valueString: string): string {
return valueString.split(":")[0];
return valueString.split(':')[0];
}
/** Mock interface for HTML Options */
@ -74,9 +60,7 @@ export class SelectMultipleControlValueAccessor implements ControlValueAccessor
let values: Array<any> = <Array<any>>value;
// convert values to ids
let ids = values.map((v) => this._getOptionId(v));
this._optionMap.forEach((opt, o) => {
opt._setSelected(ids.indexOf(o.toString()) > -1);
});
this._optionMap.forEach((opt, o) => { opt._setSelected(ids.indexOf(o.toString()) > -1); });
}
registerOnChange(fn: (value: any) => any): void {
@ -145,7 +129,8 @@ export class NgSelectMultipleOption implements OnDestroy {
/** @internal */
_value: any;
constructor(private _element: ElementRef, private _renderer: Renderer,
constructor(
private _element: ElementRef, private _renderer: Renderer,
@Optional() @Host() private _select: SelectMultipleControlValueAccessor) {
if (isPresent(this._select)) {
this.id = this._select._registerOption(this);

View File

@ -1,21 +1,21 @@
import {ListWrapper, StringMapWrapper} from '../../facade/collection';
import {isBlank, isPresent, looseIdentical, hasConstructor} from '../../facade/lang';
import {BaseException} from '../../facade/exceptions';
import {ControlContainer} from './control_container';
import {NgControl} from './ng_control';
import {AbstractControlDirective} from './abstract_control_directive';
import {NgControlGroup} from './ng_control_group';
import {hasConstructor, isBlank, isPresent, looseIdentical} from '../../facade/lang';
import {Control, ControlGroup} from '../model';
import {Validators} from '../validators';
import {AbstractControlDirective} from './abstract_control_directive';
import {CheckboxControlValueAccessor} from './checkbox_value_accessor';
import {ControlContainer} from './control_container';
import {ControlValueAccessor} from './control_value_accessor';
import {DefaultValueAccessor} from './default_value_accessor';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {normalizeAsyncValidator, normalizeValidator} from './normalize_validator';
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';
import {ValidatorFn, AsyncValidatorFn} from './validators';
import {SelectControlValueAccessor} from './select_control_value_accessor';
import {AsyncValidatorFn, ValidatorFn} from './validators';
export function controlPath(name: string, parent: ControlContainer): string[] {
@ -25,8 +25,8 @@ export function controlPath(name: string, parent: ControlContainer): string[] {
}
export function setUpControl(control: Control, dir: NgControl): void {
if (isBlank(control)) _throwError(dir, "Cannot find control");
if (isBlank(dir.valueAccessor)) _throwError(dir, "No value accessor for");
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]);
@ -47,13 +47,13 @@ export function setUpControl(control: Control, dir: NgControl): void {
}
export function setUpControlGroup(control: ControlGroup, dir: NgControlGroup) {
if (isBlank(control)) _throwError(dir, "Cannot find control");
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: AbstractControlDirective, message: string): void {
var path = dir.path.join(" -> ");
var path = dir.path.join(' -> ');
throw new BaseException(`${message} '${path}'`);
}
@ -61,23 +61,23 @@ export function composeValidators(validators: /* Array<Validator|Function> */ an
return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null;
}
export function composeAsyncValidators(
validators: /* Array<Validator|Function> */ any[]): AsyncValidatorFn {
export function composeAsyncValidators(validators: /* Array<Validator|Function> */ any[]):
AsyncValidatorFn {
return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) :
null;
}
export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any): boolean {
if (!StringMapWrapper.contains(changes, "model")) return false;
var change = changes["model"];
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: NgControl,
valueAccessors: ControlValueAccessor[]): ControlValueAccessor {
export function selectValueAccessor(
dir: NgControl, valueAccessors: ControlValueAccessor[]): ControlValueAccessor {
if (isBlank(valueAccessors)) return null;
var defaultAccessor: ControlValueAccessor;
@ -87,17 +87,17 @@ export function selectValueAccessor(dir: NgControl,
if (hasConstructor(v, DefaultValueAccessor)) {
defaultAccessor = v;
} else if (hasConstructor(v, CheckboxControlValueAccessor) ||
hasConstructor(v, NumberValueAccessor) ||
} 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");
_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");
_throwError(dir, 'More than one custom value accessor matches');
customAccessor = v;
}
});
@ -106,6 +106,6 @@ export function selectValueAccessor(dir: NgControl,
if (isPresent(builtinAccessor)) return builtinAccessor;
if (isPresent(defaultAccessor)) return defaultAccessor;
_throwError(dir, "No valid value accessor for");
_throwError(dir, 'No valid value accessor for');
return null;
}

View File

@ -1,7 +1,8 @@
import {forwardRef, Attribute, Directive} from '@angular/core';
import {Attribute, Directive, forwardRef} from '@angular/core';
import {NumberWrapper} from '../../facade/lang';
import {Validators, NG_VALIDATORS} from '../validators';
import {AbstractControl} from '../model';
import {NG_VALIDATORS, Validators} from '../validators';
@ -82,7 +83,7 @@ export const MIN_LENGTH_VALIDATOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*
export class MinLengthValidator implements Validator {
private _validator: ValidatorFn;
constructor(@Attribute("minlength") minLength: string) {
constructor(@Attribute('minlength') minLength: string) {
this._validator = Validators.minLength(NumberWrapper.parseInt(minLength, 10));
}
@ -115,7 +116,7 @@ export const MAX_LENGTH_VALIDATOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*
export class MaxLengthValidator implements Validator {
private _validator: ValidatorFn;
constructor(@Attribute("maxlength") maxLength: string) {
constructor(@Attribute('maxlength') maxLength: string) {
this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10));
}
@ -150,7 +151,7 @@ export const PATTERN_VALIDATOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*/ {
export class PatternValidator implements Validator {
private _validator: ValidatorFn;
constructor(@Attribute("pattern") pattern: string) {
constructor(@Attribute('pattern') pattern: string) {
this._validator = Validators.pattern(pattern);
}

View File

@ -1,8 +1,11 @@
import {Injectable} from '@angular/core';
import {StringMapWrapper} from '../facade/collection';
import {isPresent, isArray} from '../facade/lang';
import {isArray, isPresent} from '../facade/lang';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import * as modelModule from './model';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
/**
@ -56,21 +59,21 @@ export class FormBuilder {
*
* See the {@link ControlGroup} constructor for more details.
*/
group(controlsConfig: {[key: string]: any},
extra: {[key: string]: any} = null): modelModule.ControlGroup {
group(controlsConfig: {[key: string]: any}, extra: {[key: string]: any} = null):
modelModule.ControlGroup {
var controls = this._reduceControls(controlsConfig);
var optionals = <{[key: string]: boolean}>(
isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null);
var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null;
isPresent(extra) ? StringMapWrapper.get(extra, 'optionals') : null);
var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, 'validator') : null;
var asyncValidator: AsyncValidatorFn =
isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null;
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: Object, validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null): modelModule.Control {
control(value: Object, validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null):
modelModule.Control {
return new modelModule.Control(value, validator, asyncValidator);
}
@ -78,15 +81,16 @@ export class FormBuilder {
* Construct an array of {@link Control}s from the given `controlsConfig` array of
* configuration, with the given optional `validator` and `asyncValidator`.
*/
array(controlsConfig: any[], validator: ValidatorFn = null,
array(
controlsConfig: any[], validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null): modelModule.ControlArray {
var controls = controlsConfig.map(c => this._createControl(c));
return new modelModule.ControlArray(controls, validator, asyncValidator);
}
/** @internal */
_reduceControls(controlsConfig: {[k: string]:
any}): {[key: string]: modelModule.AbstractControl} {
_reduceControls(controlsConfig: {[k: string]: any}):
{[key: string]: modelModule.AbstractControl} {
var controls: {[key: string]: modelModule.AbstractControl} = {};
StringMapWrapper.forEach(controlsConfig, (controlConfig: any, controlName: string) => {
controls[controlName] = this._createControl(controlConfig);

View File

@ -1,24 +1,26 @@
import {isPresent, isBlank, normalizeBool} from '../facade/lang';
import {Observable, EventEmitter, ObservableWrapper} from '../facade/async';
import {EventEmitter, Observable, ObservableWrapper} from '../facade/async';
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {isBlank, isPresent, normalizeBool} from '../facade/lang';
import {PromiseWrapper} from '../facade/promise';
import {StringMapWrapper, ListWrapper} from '../facade/collection';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
/**
* Indicates that a Control is valid, i.e. that no errors exist in the input value.
*/
export const VALID = "VALID";
export const VALID = 'VALID';
/**
* Indicates that a Control is invalid, i.e. that an error exists in the input value.
*/
export const INVALID = "INVALID";
export const INVALID = 'INVALID';
/**
* Indicates that a Control is pending, i.e. that async validation is occurring and
* errors are not yet available for the input value.
*/
export const PENDING = "PENDING";
export const PENDING = 'PENDING';
export function isControl(control: Object): boolean {
return control instanceof AbstractControl;
@ -28,12 +30,11 @@ function _find(control: AbstractControl, path: Array<string | number>| string) {
if (isBlank(path)) return null;
if (!(path instanceof Array)) {
path = (<string>path).split("/");
path = (<string>path).split('/');
}
if (path instanceof Array && ListWrapper.isEmpty(path)) return null;
return (<Array<string | number>>path)
.reduce((v, name) => {
return (<Array<string|number>>path).reduce((v, name) => {
if (v instanceof ControlGroup) {
return isPresent(v.controls[name]) ? v.controls[name] : null;
} else if (v instanceof ControlArray) {
@ -114,8 +115,8 @@ export abstract class AbstractControl {
setParent(parent: ControlGroup|ControlArray): void { this._parent = parent; }
updateValueAndValidity(
{onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}):
void {
onlySelf = normalizeBool(onlySelf);
emitEvent = isPresent(emitEvent) ? emitEvent : true;
@ -273,8 +274,8 @@ export class Control extends AbstractControl {
/** @internal */
_onChange: Function;
constructor(value: any = null, validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
constructor(
value: any = null, validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator);
this._value = value;
this.updateValueAndValidity({onlySelf: true, emitEvent: false});
@ -339,9 +340,9 @@ export class Control extends AbstractControl {
export class ControlGroup extends AbstractControl {
private _optionals: {[key: string]: boolean};
constructor(public controls: {[key: string]: AbstractControl},
optionals: {[key: string]: boolean} = null, validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
constructor(
public controls: {[key: string]: AbstractControl}, optionals: {[key: string]: boolean} = null,
validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator);
this._optionals = isPresent(optionals) ? optionals : {};
this._initObservables();
@ -467,7 +468,8 @@ export class ControlGroup extends AbstractControl {
* @experimental
*/
export class ControlArray extends AbstractControl {
constructor(public controls: AbstractControl[], validator: ValidatorFn = null,
constructor(
public controls: AbstractControl[], validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator);
this._initObservables();

View File

@ -1,10 +1,13 @@
import {OpaqueToken} from '@angular/core';
import {isBlank, isPresent, isString} from '../facade/lang';
import {PromiseWrapper} from '../facade/promise';
import {ObservableWrapper} from '../facade/async';
import {StringMapWrapper} from '../facade/collection';
import {isBlank, isPresent, isString} from '../facade/lang';
import {PromiseWrapper} from '../facade/promise';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import * as modelModule from './model';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
/**
* Providers for validators to be used for {@link Control}s in a form.
@ -16,7 +19,7 @@ import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
* {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'}
* @experimental
*/
export const NG_VALIDATORS: OpaqueToken = /*@ts2dart_const*/ new OpaqueToken("NgValidators");
export const NG_VALIDATORS: OpaqueToken = /*@ts2dart_const*/ new OpaqueToken('NgValidators');
/**
* Providers for asynchronous validators to be used for {@link Control}s
@ -29,7 +32,7 @@ export const NG_VALIDATORS: OpaqueToken = /*@ts2dart_const*/ new OpaqueToken("Ng
* @experimental
*/
export const NG_ASYNC_VALIDATORS: OpaqueToken =
/*@ts2dart_const*/ new OpaqueToken("NgAsyncValidators");
/*@ts2dart_const*/ new OpaqueToken('NgAsyncValidators');
/**
* Provides a set of validators used by form controls.
@ -50,8 +53,8 @@ export class Validators {
* Validator that requires controls to have a non-empty value.
*/
static required(control: modelModule.AbstractControl): {[key: string]: boolean} {
return isBlank(control.value) || (isString(control.value) && control.value == "") ?
{"required": true} :
return isBlank(control.value) || (isString(control.value) && control.value == '') ?
{'required': true} :
null;
}
@ -63,7 +66,7 @@ export class Validators {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
return v.length < minLength ?
{"minlength": {"requiredLength": minLength, "actualLength": v.length}} :
{'minlength': {'requiredLength': minLength, 'actualLength': v.length}} :
null;
};
}
@ -76,7 +79,7 @@ export class Validators {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
return v.length > maxLength ?
{"maxlength": {"requiredLength": maxLength, "actualLength": v.length}} :
{'maxlength': {'requiredLength': maxLength, 'actualLength': v.length}} :
null;
};
}
@ -90,7 +93,7 @@ export class Validators {
let regex = new RegExp(`^${pattern}$`);
let v: string = control.value;
return regex.test(v) ? null :
{"pattern": {"requiredPattern": `^${pattern}$`, "actualValue": v}};
{'pattern': {'requiredPattern': `^${pattern}$`, 'actualValue': v}};
};
}
@ -129,13 +132,13 @@ function _convertToPromise(obj: any): any {
return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj);
}
function _executeValidators(control: modelModule.AbstractControl,
validators: ValidatorFn[]): any[] {
function _executeValidators(
control: modelModule.AbstractControl, validators: ValidatorFn[]): any[] {
return validators.map(v => v(control));
}
function _executeAsyncValidators(control: modelModule.AbstractControl,
validators: AsyncValidatorFn[]): any[] {
function _executeAsyncValidators(
control: modelModule.AbstractControl, validators: AsyncValidatorFn[]): any[] {
return validators.map(v => v(control));
}

View File

@ -10,39 +10,32 @@
* Forms providers are not included in default providers; you must import these providers
* explicitly.
*/
export {AbstractControl, Control, ControlGroup, ControlArray} from './forms/model';
import {Type} from '@angular/core';
import {RadioControlRegistry} from './forms/directives/radio_control_value_accessor';
import {FormBuilder} from './forms/form_builder';
export {FORM_DIRECTIVES, RadioButtonState} from './forms/directives';
export {AbstractControlDirective} from './forms/directives/abstract_control_directive';
export {Form} from './forms/directives/form_interface';
export {CheckboxControlValueAccessor} from './forms/directives/checkbox_value_accessor';
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 {ControlValueAccessor, NG_VALUE_ACCESSOR} from './forms/directives/control_value_accessor';
export {DefaultValueAccessor} from './forms/directives/default_value_accessor';
export {Form} from './forms/directives/form_interface';
export {NgControl} from './forms/directives/ng_control';
export {NgControlGroup} from './forms/directives/ng_control_group';
export {NgControlName} from './forms/directives/ng_control_name';
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,
Validator
} from './forms/directives/validators';
export {NgForm} from './forms/directives/ng_form';
export {NgFormControl} from './forms/directives/ng_form_control';
export {NgFormModel} from './forms/directives/ng_form_model';
export {NgModel} from './forms/directives/ng_model';
export {NgSelectOption, SelectControlValueAccessor} from './forms/directives/select_control_value_accessor';
export {MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator, Validator} 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 {Type} from '@angular/core';
export {AbstractControl, Control, ControlArray, ControlGroup} from './forms/model';
export {NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators} from './forms/validators';
/**
* Shorthand set of providers used for building Angular forms.

View File

@ -1,60 +1,37 @@
import {Type} from '@angular/core';
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 {DefaultValueAccessor} from './directives/default_value_accessor';
import {NgControlGroup} from './directives/ng_control_group';
import {NgControlName} from './directives/ng_control_name';
import {NgControlStatus} from './directives/ng_control_status';
import {NgForm} from './directives/ng_form';
import {NgFormControl} from './directives/ng_form_control';
import {NgFormModel} from './directives/ng_form_model';
import {NgModel} from './directives/ng_model';
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 {
SelectMultipleControlValueAccessor,
NgSelectMultipleOption
} from './directives/select_multiple_control_value_accessor';
import {
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator
} from './directives/validators';
import {NgSelectOption, SelectControlValueAccessor} from './directives/select_control_value_accessor';
import {NgSelectMultipleOption, SelectMultipleControlValueAccessor} from './directives/select_multiple_control_value_accessor';
import {MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator} 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 {
SelectMultipleControlValueAccessor,
NgSelectMultipleOption
} from './directives/select_multiple_control_value_accessor';
export {
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator
} from './directives/validators';
export {NgControl} from './directives/ng_control';
export {ControlValueAccessor} from './directives/control_value_accessor';
export {DefaultValueAccessor} from './directives/default_value_accessor';
export {NgControl} from './directives/ng_control';
export {NgControlGroup} from './directives/ng_control_group';
export {NgControlName} from './directives/ng_control_name';
export {NgControlStatus} from './directives/ng_control_status';
export {NgForm} from './directives/ng_form';
export {NgFormControl} from './directives/ng_form_control';
export {NgFormModel} from './directives/ng_form_model';
export {NgModel} from './directives/ng_model';
export {NumberValueAccessor} from './directives/number_value_accessor';
export {RadioButtonState, RadioControlValueAccessor} from './directives/radio_control_value_accessor';
export {NgSelectOption, SelectControlValueAccessor} from './directives/select_control_value_accessor';
export {NgSelectMultipleOption, SelectMultipleControlValueAccessor} from './directives/select_multiple_control_value_accessor';
export {MaxLengthValidator, MinLengthValidator, PatternValidator, RequiredValidator} from './directives/validators';
/**
*
@ -74,26 +51,13 @@ export {ControlValueAccessor} from './directives/control_value_accessor';
* @experimental
*/
export const FORM_DIRECTIVES: Type[] = /*@ts2dart_const*/[
NgControlName,
NgControlGroup,
NgControlName, NgControlGroup,
NgFormControl,
NgModel,
NgFormModel,
NgForm,
NgFormControl, NgModel, NgFormModel, NgForm,
NgSelectOption,
NgSelectMultipleOption,
DefaultValueAccessor,
NumberValueAccessor,
CheckboxControlValueAccessor,
SelectControlValueAccessor,
SelectMultipleControlValueAccessor,
RadioControlValueAccessor,
NgControlStatus,
NgSelectOption, NgSelectMultipleOption, DefaultValueAccessor, NumberValueAccessor,
CheckboxControlValueAccessor, SelectControlValueAccessor, SelectMultipleControlValueAccessor,
RadioControlValueAccessor, NgControlStatus,
RequiredValidator,
MinLengthValidator,
MaxLengthValidator,
PatternValidator
RequiredValidator, MinLengthValidator, MaxLengthValidator, PatternValidator
];

View File

@ -1,6 +1,7 @@
import {AbstractControl} from '../model';
import {isPresent} from '../../facade/lang';
import {unimplemented} from '../../facade/exceptions';
import {isPresent} from '../../facade/lang';
import {AbstractControl} from '../model';
/**
* Base class for control directives.

View File

@ -1,5 +1,6 @@
import {Directive, Renderer, ElementRef, forwardRef} from '@angular/core';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {Directive, ElementRef, Renderer, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
export const CHECKBOX_VALUE_ACCESSOR: any = /*@ts2dart_const*/ {
provide: NG_VALUE_ACCESSOR,

View File

@ -1,5 +1,6 @@
import {Form} from './form_interface';
import {AbstractControlDirective} from './abstract_control_directive';
import {Form} from './form_interface';
/**
* A directive that contains multiple {@link NgControl}s.

View File

@ -34,4 +34,4 @@ export interface ControlValueAccessor {
* @experimental
*/
export const NG_VALUE_ACCESSOR: OpaqueToken =
/*@ts2dart_const*/ new OpaqueToken("NgValueAccessor");
/*@ts2dart_const*/ new OpaqueToken('NgValueAccessor');

View File

@ -1,6 +1,8 @@
import {Directive, ElementRef, Renderer, forwardRef} from '@angular/core';
import {isBlank} from '../../facade/lang';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
export const DEFAULT_VALUE_ACCESSOR: any = /*@ts2dart_const*/
/* @ts2dart_Provider */ {

View File

@ -1,6 +1,8 @@
import {Control, ControlGroup} from '../model';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {Control, ControlGroup} from '../model';
/**
* An interface that {@link NgFormModel} and {@link NgForm} implement.

View File

@ -1,9 +1,10 @@
import {unimplemented} from '../../facade/exceptions';
import {ControlValueAccessor} from './control_value_accessor';
import {AbstractControlDirective} from './abstract_control_directive';
import {ControlValueAccessor} from './control_value_accessor';
import {AsyncValidatorFn, ValidatorFn} from './validators';
/**
* A base class that all control directive extend.
* It binds a {@link Control} object to a DOM element.

View File

@ -1,19 +1,11 @@
import {
OnInit,
OnDestroy,
Directive,
Optional,
Inject,
Host,
SkipSelf,
forwardRef,
Self
} from '@angular/core';
import {ControlContainer} from './control_container';
import {controlPath, composeValidators, composeAsyncValidators} from './shared';
import {Directive, Host, Inject, OnDestroy, OnInit, Optional, Self, SkipSelf, forwardRef} from '@angular/core';
import {ControlGroup} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlContainer} from './control_container';
import {Form} from './form_interface';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {composeAsyncValidators, composeValidators, controlPath} from './shared';
import {AsyncValidatorFn, ValidatorFn} from './validators';
export const controlGroupProvider: any =
@ -79,7 +71,8 @@ export class NgControlGroup extends ControlContainer implements OnInit,
/** @internal */
_parent: ControlContainer;
constructor(@Host() @SkipSelf() parent: ControlContainer,
constructor(
@Host() @SkipSelf() parent: ControlContainer,
@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) {
super();

View File

@ -1,30 +1,14 @@
import {
OnChanges,
OnDestroy,
SimpleChanges,
Directive,
forwardRef,
Host,
SkipSelf,
Inject,
Optional,
Self
} from '@angular/core';
import {Directive, Host, Inject, OnChanges, OnDestroy, Optional, Self, SimpleChanges, SkipSelf, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {ControlContainer} from './control_container';
import {NgControl} from './ng_control';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {
controlPath,
composeValidators,
composeAsyncValidators,
isPropertyUpdated,
selectValueAccessor
} from './shared';
import {Control} from '../model';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {ValidatorFn, AsyncValidatorFn} from './validators';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlContainer} from './control_container';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {NgControl} from './ng_control';
import {composeAsyncValidators, composeValidators, controlPath, isPropertyUpdated, selectValueAccessor} from './shared';
import {AsyncValidatorFn, ValidatorFn} from './validators';
export const controlNameBinding: any =
@ -140,7 +124,9 @@ export class NgControlName extends NgControl implements OnChanges,
get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
get asyncValidator(): AsyncValidatorFn {
return composeAsyncValidators(this._asyncValidators);
}
get control(): Control { return this.formDirective.getControl(this); }
}

View File

@ -1,7 +1,10 @@
import {Directive, Self} from '@angular/core';
import {NgControl} from './ng_control';
import {isPresent} from '../../facade/lang';
import {NgControl} from './ng_control';
/**
* Directive automatically applied to Angular forms that sets CSS classes
* based on control status (valid/invalid/dirty/etc).

View File

@ -1,18 +1,16 @@
import {Directive, forwardRef, Optional, Inject, Self} from '@angular/core';
import {
PromiseWrapper,
ObservableWrapper,
EventEmitter
} from '../../facade/async';
import {Directive, Inject, Optional, Self, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper, PromiseWrapper} from '../../facade/async';
import {ListWrapper} from '../../facade/collection';
import {isPresent} from '../../facade/lang';
import {NgControl} from './ng_control';
import {Form} from './form_interface';
import {NgControlGroup} from './ng_control_group';
import {AbstractControl, Control, ControlGroup} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlContainer} from './control_container';
import {AbstractControl, ControlGroup, Control} from '../model';
import {setUpControl, setUpControlGroup, composeValidators, composeAsyncValidators} from './shared';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {Form} from './form_interface';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {composeAsyncValidators, composeValidators, setUpControl, setUpControlGroup} from './shared';
export const formDirectiveProvider: any =
/*@ts2dart_const*/ {provide: ControlContainer, useExisting: forwardRef(() => NgForm)};
@ -93,11 +91,12 @@ export class NgForm extends ControlContainer implements Form {
form: ControlGroup;
ngSubmit = new EventEmitter();
constructor(@Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],
constructor(
@Optional() @Self() @Inject(NG_VALIDATORS) validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: any[]) {
super();
this.form = new ControlGroup({}, null, composeValidators(validators),
composeAsyncValidators(asyncValidators));
this.form = new ControlGroup(
{}, null, composeValidators(validators), composeAsyncValidators(asyncValidators));
}
get submitted(): boolean { return this._submitted; }

View File

@ -1,28 +1,14 @@
import {
OnChanges,
SimpleChanges,
Directive,
forwardRef,
Inject,
Optional,
Self
} from '@angular/core';
import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core';
import {StringMapWrapper} from '../../facade/collection';
import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {NgControl} from './ng_control';
import {StringMapWrapper} from '../../facade/collection';
import {Control} from '../model';
import {NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {
setUpControl,
composeValidators,
composeAsyncValidators,
isPropertyUpdated,
selectValueAccessor
} from './shared';
import {ValidatorFn, AsyncValidatorFn} from './validators';
import {NgControl} from './ng_control';
import {composeAsyncValidators, composeValidators, isPropertyUpdated, selectValueAccessor, setUpControl} from './shared';
import {AsyncValidatorFn, ValidatorFn} from './validators';
export const formControlBinding: any =
/*@ts2dart_const*/ /* @ts2dart_Provider */ {
@ -117,7 +103,9 @@ export class NgFormControl extends NgControl implements OnChanges {
get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
get asyncValidator(): AsyncValidatorFn {
return composeAsyncValidators(this._asyncValidators);
}
get control(): Control { return this.form; }
@ -127,6 +115,6 @@ export class NgFormControl extends NgControl implements OnChanges {
}
private _isControlChanged(changes: {[key: string]: any}): boolean {
return StringMapWrapper.contains(changes, "form");
return StringMapWrapper.contains(changes, 'form');
}
}

View File

@ -1,23 +1,17 @@
import {
SimpleChanges,
OnChanges,
Directive,
forwardRef,
Inject,
Optional,
Self
} from '@angular/core';
import {isBlank} from '../../facade/lang';
import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {ListWrapper, StringMapWrapper} from '../../facade/collection';
import {BaseException} from '../../facade/exceptions';
import {ObservableWrapper, EventEmitter} from '../../facade/async';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {isBlank} from '../../facade/lang';
import {Control, ControlGroup} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS, Validators} from '../validators';
import {ControlContainer} from './control_container';
import {Form} from './form_interface';
import {Control, ControlGroup} from '../model';
import {setUpControl, setUpControlGroup, composeValidators, composeAsyncValidators} from './shared';
import {Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS} from '../validators';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {composeAsyncValidators, composeValidators, setUpControl, setUpControlGroup} from './shared';
export const formDirectiveProvider: any =
/*@ts2dart_const*/ /* @ts2dart_Provider */ {
@ -115,14 +109,15 @@ export class NgFormModel extends ControlContainer implements Form,
directives: NgControl[] = [];
ngSubmit = new EventEmitter();
constructor(@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
constructor(
@Optional() @Self() @Inject(NG_VALIDATORS) private _validators: any[],
@Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) private _asyncValidators: any[]) {
super();
}
ngOnChanges(changes: SimpleChanges): void {
this._checkFormPresent();
if (StringMapWrapper.contains(changes, "form")) {
if (StringMapWrapper.contains(changes, 'form')) {
var sync = composeValidators(this._validators);
this.form.validator = Validators.compose([this.form.validator, sync]);

View File

@ -1,25 +1,13 @@
import {
OnChanges,
SimpleChanges,
Directive,
forwardRef,
Inject,
Optional,
Self
} from '@angular/core';
import {Directive, Inject, OnChanges, Optional, Self, SimpleChanges, forwardRef} from '@angular/core';
import {EventEmitter, ObservableWrapper} from '../../facade/async';
import {Control} from '../model';
import {NG_ASYNC_VALIDATORS, NG_VALIDATORS} from '../validators';
import {ControlValueAccessor, 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';
import {ValidatorFn, AsyncValidatorFn} from './validators';
import {composeAsyncValidators, composeValidators, isPropertyUpdated, selectValueAccessor, setUpControl} from './shared';
import {AsyncValidatorFn, ValidatorFn} from './validators';
export const formControlBinding: any =
/*@ts2dart_const*/ /* @ts2dart_Provider */ {
@ -93,7 +81,9 @@ export class NgModel extends NgControl implements OnChanges {
get validator(): ValidatorFn { return composeValidators(this._validators); }
get asyncValidator(): AsyncValidatorFn { return composeAsyncValidators(this._asyncValidators); }
get asyncValidator(): AsyncValidatorFn {
return composeAsyncValidators(this._asyncValidators);
}
viewToModelUpdate(newValue: any): void {
this.viewModel = newValue;

View File

@ -1,5 +1,6 @@
import {AbstractControl} from '../model';
import {Validator, ValidatorFn, AsyncValidatorFn} from './validators';
import {AsyncValidatorFn, Validator, ValidatorFn} from './validators';
export function normalizeValidator(validator: ValidatorFn | Validator): ValidatorFn {
if ((<Validator>validator).validate !== undefined) {

View File

@ -1,6 +1,8 @@
import {Directive, ElementRef, Renderer, forwardRef} from '@angular/core';
import {NumberWrapper} from '../../facade/lang';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
export const NUMBER_VALUE_ACCESSOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*/ {
provide: NG_VALUE_ACCESSOR,

View File

@ -1,17 +1,9 @@
import {
Directive,
ElementRef,
Renderer,
forwardRef,
Input,
OnInit,
OnDestroy,
Injector,
Injectable
} from '@angular/core';
import {isPresent} from '../../facade/lang';
import {Directive, ElementRef, Injectable, Injector, Input, OnDestroy, OnInit, Renderer, forwardRef} from '@angular/core';
import {ListWrapper} from '../../facade/collection';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {isPresent} from '../../facade/lang';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {NgControl} from './ng_control';
export const RADIO_VALUE_ACCESSOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*/ {
@ -49,8 +41,8 @@ export class RadioControlRegistry {
});
}
private _isSameGroup(controlPair:[NgControl, RadioControlValueAccessor],
accessor: RadioControlValueAccessor) {
private _isSameGroup(
controlPair: [NgControl, RadioControlValueAccessor], accessor: RadioControlValueAccessor) {
return controlPair[0].control.root === accessor._control.control.root &&
controlPair[1].name === accessor.name;
}
@ -102,7 +94,8 @@ export class RadioControlValueAccessor implements ControlValueAccessor,
onChange = () => {};
onTouched = () => {};
constructor(private _renderer: Renderer, private _elementRef: ElementRef,
constructor(
private _renderer: Renderer, private _elementRef: ElementRef,
private _registry: RadioControlRegistry, private _injector: Injector) {}
ngOnInit(): void {

View File

@ -1,23 +1,9 @@
import {
Directive,
Renderer,
forwardRef,
ElementRef,
Input,
Host,
OnDestroy,
Optional
} from '@angular/core';
import {
StringWrapper,
isPrimitive,
isPresent,
isBlank,
looseIdentical
} from '../../facade/lang';
import {MapWrapper} from '../../facade/collection';
import {Directive, ElementRef, Host, Input, OnDestroy, Optional, Renderer, forwardRef} from '@angular/core';
import {NG_VALUE_ACCESSOR, ControlValueAccessor} from './control_value_accessor';
import {MapWrapper} from '../../facade/collection';
import {StringWrapper, isBlank, isPresent, isPrimitive, looseIdentical} from '../../facade/lang';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
export const SELECT_VALUE_ACCESSOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*/ {
provide: NG_VALUE_ACCESSOR,
@ -27,12 +13,12 @@ export const SELECT_VALUE_ACCESSOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider
function _buildValueString(id: string, value: any): string {
if (isBlank(id)) return `${value}`;
if (!isPrimitive(value)) value = "Object";
if (!isPrimitive(value)) value = 'Object';
return StringWrapper.slice(`${id}: ${value}`, 0, 50);
}
function _extractId(valueString: string): string {
return valueString.split(":")[0];
return valueString.split(':')[0];
}
/**
@ -112,7 +98,8 @@ export class SelectControlValueAccessor implements ControlValueAccessor {
export class NgSelectOption implements OnDestroy {
id: string;
constructor(private _element: ElementRef, private _renderer: Renderer,
constructor(
private _element: ElementRef, private _renderer: Renderer,
@Optional() @Host() private _select: SelectControlValueAccessor) {
if (isPresent(this._select)) this.id = this._select._registerOption();
}

View File

@ -1,23 +1,9 @@
import {
Input,
Directive,
ElementRef,
Renderer,
Optional,
Host,
OnDestroy,
forwardRef
} from "@angular/core";
import {
isBlank,
isPrimitive,
StringWrapper,
isPresent,
looseIdentical,
isString
} from '../../facade/lang';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
import {Directive, ElementRef, Host, Input, OnDestroy, Optional, Renderer, forwardRef} from '@angular/core';
import {MapWrapper} from '../../facade/collection';
import {StringWrapper, isBlank, isPresent, isPrimitive, isString, looseIdentical} from '../../facade/lang';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from './control_value_accessor';
const SELECT_MULTIPLE_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
@ -28,12 +14,12 @@ const SELECT_MULTIPLE_VALUE_ACCESSOR = {
function _buildValueString(id: string, value: any): string {
if (isBlank(id)) return `${value}`;
if (isString(value)) value = `'${value}'`;
if (!isPrimitive(value)) value = "Object";
if (!isPrimitive(value)) value = 'Object';
return StringWrapper.slice(`${id}: ${value}`, 0, 50);
}
function _extractId(valueString: string): string {
return valueString.split(":")[0];
return valueString.split(':')[0];
}
/** Mock interface for HTML Options */
@ -74,9 +60,7 @@ export class SelectMultipleControlValueAccessor implements ControlValueAccessor
let values: Array<any> = <Array<any>>value;
// convert values to ids
let ids = values.map((v) => this._getOptionId(v));
this._optionMap.forEach((opt, o) => {
opt._setSelected(ids.indexOf(o.toString()) > -1);
});
this._optionMap.forEach((opt, o) => { opt._setSelected(ids.indexOf(o.toString()) > -1); });
}
registerOnChange(fn: (value: any) => any): void {
@ -145,7 +129,8 @@ export class NgSelectMultipleOption implements OnDestroy {
/** @internal */
_value: any;
constructor(private _element: ElementRef, private _renderer: Renderer,
constructor(
private _element: ElementRef, private _renderer: Renderer,
@Optional() @Host() private _select: SelectMultipleControlValueAccessor) {
if (isPresent(this._select)) {
this.id = this._select._registerOption(this);

View File

@ -1,21 +1,21 @@
import {ListWrapper, StringMapWrapper} from '../../facade/collection';
import {isBlank, isPresent, looseIdentical, hasConstructor} from '../../facade/lang';
import {BaseException} from '../../facade/exceptions';
import {ControlContainer} from './control_container';
import {NgControl} from './ng_control';
import {AbstractControlDirective} from './abstract_control_directive';
import {NgControlGroup} from './ng_control_group';
import {hasConstructor, isBlank, isPresent, looseIdentical} from '../../facade/lang';
import {Control, ControlGroup} from '../model';
import {Validators} from '../validators';
import {AbstractControlDirective} from './abstract_control_directive';
import {CheckboxControlValueAccessor} from './checkbox_value_accessor';
import {ControlContainer} from './control_container';
import {ControlValueAccessor} from './control_value_accessor';
import {DefaultValueAccessor} from './default_value_accessor';
import {NgControl} from './ng_control';
import {NgControlGroup} from './ng_control_group';
import {normalizeAsyncValidator, normalizeValidator} from './normalize_validator';
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';
import {ValidatorFn, AsyncValidatorFn} from './validators';
import {SelectControlValueAccessor} from './select_control_value_accessor';
import {AsyncValidatorFn, ValidatorFn} from './validators';
export function controlPath(name: string, parent: ControlContainer): string[] {
@ -25,8 +25,8 @@ export function controlPath(name: string, parent: ControlContainer): string[] {
}
export function setUpControl(control: Control, dir: NgControl): void {
if (isBlank(control)) _throwError(dir, "Cannot find control");
if (isBlank(dir.valueAccessor)) _throwError(dir, "No value accessor for");
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]);
@ -47,13 +47,13 @@ export function setUpControl(control: Control, dir: NgControl): void {
}
export function setUpControlGroup(control: ControlGroup, dir: NgControlGroup) {
if (isBlank(control)) _throwError(dir, "Cannot find control");
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: AbstractControlDirective, message: string): void {
var path = dir.path.join(" -> ");
var path = dir.path.join(' -> ');
throw new BaseException(`${message} '${path}'`);
}
@ -61,23 +61,23 @@ export function composeValidators(validators: /* Array<Validator|Function> */ an
return isPresent(validators) ? Validators.compose(validators.map(normalizeValidator)) : null;
}
export function composeAsyncValidators(
validators: /* Array<Validator|Function> */ any[]): AsyncValidatorFn {
export function composeAsyncValidators(validators: /* Array<Validator|Function> */ any[]):
AsyncValidatorFn {
return isPresent(validators) ? Validators.composeAsync(validators.map(normalizeAsyncValidator)) :
null;
}
export function isPropertyUpdated(changes: {[key: string]: any}, viewModel: any): boolean {
if (!StringMapWrapper.contains(changes, "model")) return false;
var change = changes["model"];
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: NgControl,
valueAccessors: ControlValueAccessor[]): ControlValueAccessor {
export function selectValueAccessor(
dir: NgControl, valueAccessors: ControlValueAccessor[]): ControlValueAccessor {
if (isBlank(valueAccessors)) return null;
var defaultAccessor: ControlValueAccessor;
@ -87,17 +87,17 @@ export function selectValueAccessor(dir: NgControl,
if (hasConstructor(v, DefaultValueAccessor)) {
defaultAccessor = v;
} else if (hasConstructor(v, CheckboxControlValueAccessor) ||
hasConstructor(v, NumberValueAccessor) ||
} 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");
_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");
_throwError(dir, 'More than one custom value accessor matches');
customAccessor = v;
}
});
@ -106,6 +106,6 @@ export function selectValueAccessor(dir: NgControl,
if (isPresent(builtinAccessor)) return builtinAccessor;
if (isPresent(defaultAccessor)) return defaultAccessor;
_throwError(dir, "No valid value accessor for");
_throwError(dir, 'No valid value accessor for');
return null;
}

View File

@ -1,7 +1,8 @@
import {forwardRef, Attribute, Directive} from '@angular/core';
import {Attribute, Directive, forwardRef} from '@angular/core';
import {NumberWrapper} from '../../facade/lang';
import {Validators, NG_VALIDATORS} from '../validators';
import {AbstractControl} from '../model';
import {NG_VALIDATORS, Validators} from '../validators';
@ -82,7 +83,7 @@ export const MIN_LENGTH_VALIDATOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*
export class MinLengthValidator implements Validator {
private _validator: ValidatorFn;
constructor(@Attribute("minlength") minLength: string) {
constructor(@Attribute('minlength') minLength: string) {
this._validator = Validators.minLength(NumberWrapper.parseInt(minLength, 10));
}
@ -115,7 +116,7 @@ export const MAX_LENGTH_VALIDATOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*
export class MaxLengthValidator implements Validator {
private _validator: ValidatorFn;
constructor(@Attribute("maxlength") maxLength: string) {
constructor(@Attribute('maxlength') maxLength: string) {
this._validator = Validators.maxLength(NumberWrapper.parseInt(maxLength, 10));
}
@ -150,7 +151,7 @@ export const PATTERN_VALIDATOR: any = /*@ts2dart_const*/ /*@ts2dart_Provider*/ {
export class PatternValidator implements Validator {
private _validator: ValidatorFn;
constructor(@Attribute("pattern") pattern: string) {
constructor(@Attribute('pattern') pattern: string) {
this._validator = Validators.pattern(pattern);
}

View File

@ -1,8 +1,11 @@
import {Injectable} from '@angular/core';
import {StringMapWrapper} from '../facade/collection';
import {isPresent, isArray} from '../facade/lang';
import {isArray, isPresent} from '../facade/lang';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import * as modelModule from './model';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
/**
@ -56,21 +59,21 @@ export class FormBuilder {
*
* See the {@link ControlGroup} constructor for more details.
*/
group(controlsConfig: {[key: string]: any},
extra: {[key: string]: any} = null): modelModule.ControlGroup {
group(controlsConfig: {[key: string]: any}, extra: {[key: string]: any} = null):
modelModule.ControlGroup {
var controls = this._reduceControls(controlsConfig);
var optionals = <{[key: string]: boolean}>(
isPresent(extra) ? StringMapWrapper.get(extra, "optionals") : null);
var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, "validator") : null;
isPresent(extra) ? StringMapWrapper.get(extra, 'optionals') : null);
var validator: ValidatorFn = isPresent(extra) ? StringMapWrapper.get(extra, 'validator') : null;
var asyncValidator: AsyncValidatorFn =
isPresent(extra) ? StringMapWrapper.get(extra, "asyncValidator") : null;
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: Object, validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null): modelModule.Control {
control(value: Object, validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null):
modelModule.Control {
return new modelModule.Control(value, validator, asyncValidator);
}
@ -78,15 +81,16 @@ export class FormBuilder {
* Construct an array of {@link Control}s from the given `controlsConfig` array of
* configuration, with the given optional `validator` and `asyncValidator`.
*/
array(controlsConfig: any[], validator: ValidatorFn = null,
array(
controlsConfig: any[], validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null): modelModule.ControlArray {
var controls = controlsConfig.map(c => this._createControl(c));
return new modelModule.ControlArray(controls, validator, asyncValidator);
}
/** @internal */
_reduceControls(controlsConfig: {[k: string]:
any}): {[key: string]: modelModule.AbstractControl} {
_reduceControls(controlsConfig: {[k: string]: any}):
{[key: string]: modelModule.AbstractControl} {
var controls: {[key: string]: modelModule.AbstractControl} = {};
StringMapWrapper.forEach(controlsConfig, (controlConfig: any, controlName: string) => {
controls[controlName] = this._createControl(controlConfig);

View File

@ -1,24 +1,26 @@
import {isPresent, isBlank, normalizeBool} from '../facade/lang';
import {Observable, EventEmitter, ObservableWrapper} from '../facade/async';
import {EventEmitter, Observable, ObservableWrapper} from '../facade/async';
import {ListWrapper, StringMapWrapper} from '../facade/collection';
import {isBlank, isPresent, normalizeBool} from '../facade/lang';
import {PromiseWrapper} from '../facade/promise';
import {StringMapWrapper, ListWrapper} from '../facade/collection';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
/**
* Indicates that a Control is valid, i.e. that no errors exist in the input value.
*/
export const VALID = "VALID";
export const VALID = 'VALID';
/**
* Indicates that a Control is invalid, i.e. that an error exists in the input value.
*/
export const INVALID = "INVALID";
export const INVALID = 'INVALID';
/**
* Indicates that a Control is pending, i.e. that async validation is occurring and
* errors are not yet available for the input value.
*/
export const PENDING = "PENDING";
export const PENDING = 'PENDING';
export function isControl(control: Object): boolean {
return control instanceof AbstractControl;
@ -28,12 +30,11 @@ function _find(control: AbstractControl, path: Array<string | number>| string) {
if (isBlank(path)) return null;
if (!(path instanceof Array)) {
path = (<string>path).split("/");
path = (<string>path).split('/');
}
if (path instanceof Array && ListWrapper.isEmpty(path)) return null;
return (<Array<string | number>>path)
.reduce((v, name) => {
return (<Array<string|number>>path).reduce((v, name) => {
if (v instanceof ControlGroup) {
return isPresent(v.controls[name]) ? v.controls[name] : null;
} else if (v instanceof ControlArray) {
@ -114,8 +115,8 @@ export abstract class AbstractControl {
setParent(parent: ControlGroup|ControlArray): void { this._parent = parent; }
updateValueAndValidity(
{onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
updateValueAndValidity({onlySelf, emitEvent}: {onlySelf?: boolean, emitEvent?: boolean} = {}):
void {
onlySelf = normalizeBool(onlySelf);
emitEvent = isPresent(emitEvent) ? emitEvent : true;
@ -273,8 +274,8 @@ export class Control extends AbstractControl {
/** @internal */
_onChange: Function;
constructor(value: any = null, validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
constructor(
value: any = null, validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator);
this._value = value;
this.updateValueAndValidity({onlySelf: true, emitEvent: false});
@ -339,9 +340,9 @@ export class Control extends AbstractControl {
export class ControlGroup extends AbstractControl {
private _optionals: {[key: string]: boolean};
constructor(public controls: {[key: string]: AbstractControl},
optionals: {[key: string]: boolean} = null, validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
constructor(
public controls: {[key: string]: AbstractControl}, optionals: {[key: string]: boolean} = null,
validator: ValidatorFn = null, asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator);
this._optionals = isPresent(optionals) ? optionals : {};
this._initObservables();
@ -467,7 +468,8 @@ export class ControlGroup extends AbstractControl {
* @experimental
*/
export class ControlArray extends AbstractControl {
constructor(public controls: AbstractControl[], validator: ValidatorFn = null,
constructor(
public controls: AbstractControl[], validator: ValidatorFn = null,
asyncValidator: AsyncValidatorFn = null) {
super(validator, asyncValidator);
this._initObservables();

View File

@ -1,10 +1,13 @@
import {OpaqueToken} from '@angular/core';
import {isBlank, isPresent, isString} from '../facade/lang';
import {PromiseWrapper} from '../facade/promise';
import {ObservableWrapper} from '../facade/async';
import {StringMapWrapper} from '../facade/collection';
import {isBlank, isPresent, isString} from '../facade/lang';
import {PromiseWrapper} from '../facade/promise';
import {AsyncValidatorFn, ValidatorFn} from './directives/validators';
import * as modelModule from './model';
import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
/**
* Providers for validators to be used for {@link Control}s in a form.
@ -16,7 +19,7 @@ import {ValidatorFn, AsyncValidatorFn} from './directives/validators';
* {@example core/forms/ts/ng_validators/ng_validators.ts region='ng_validators'}
* @experimental
*/
export const NG_VALIDATORS: OpaqueToken = /*@ts2dart_const*/ new OpaqueToken("NgValidators");
export const NG_VALIDATORS: OpaqueToken = /*@ts2dart_const*/ new OpaqueToken('NgValidators');
/**
* Providers for asynchronous validators to be used for {@link Control}s
@ -29,7 +32,7 @@ export const NG_VALIDATORS: OpaqueToken = /*@ts2dart_const*/ new OpaqueToken("Ng
* @experimental
*/
export const NG_ASYNC_VALIDATORS: OpaqueToken =
/*@ts2dart_const*/ new OpaqueToken("NgAsyncValidators");
/*@ts2dart_const*/ new OpaqueToken('NgAsyncValidators');
/**
* Provides a set of validators used by form controls.
@ -50,8 +53,8 @@ export class Validators {
* Validator that requires controls to have a non-empty value.
*/
static required(control: modelModule.AbstractControl): {[key: string]: boolean} {
return isBlank(control.value) || (isString(control.value) && control.value == "") ?
{"required": true} :
return isBlank(control.value) || (isString(control.value) && control.value == '') ?
{'required': true} :
null;
}
@ -63,7 +66,7 @@ export class Validators {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
return v.length < minLength ?
{"minlength": {"requiredLength": minLength, "actualLength": v.length}} :
{'minlength': {'requiredLength': minLength, 'actualLength': v.length}} :
null;
};
}
@ -76,7 +79,7 @@ export class Validators {
if (isPresent(Validators.required(control))) return null;
var v: string = control.value;
return v.length > maxLength ?
{"maxlength": {"requiredLength": maxLength, "actualLength": v.length}} :
{'maxlength': {'requiredLength': maxLength, 'actualLength': v.length}} :
null;
};
}
@ -90,7 +93,7 @@ export class Validators {
let regex = new RegExp(`^${pattern}$`);
let v: string = control.value;
return regex.test(v) ? null :
{"pattern": {"requiredPattern": `^${pattern}$`, "actualValue": v}};
{'pattern': {'requiredPattern': `^${pattern}$`, 'actualValue': v}};
};
}
@ -129,13 +132,13 @@ function _convertToPromise(obj: any): any {
return PromiseWrapper.isPromise(obj) ? obj : ObservableWrapper.toPromise(obj);
}
function _executeValidators(control: modelModule.AbstractControl,
validators: ValidatorFn[]): any[] {
function _executeValidators(
control: modelModule.AbstractControl, validators: ValidatorFn[]): any[] {
return validators.map(v => v(control));
}
function _executeAsyncValidators(control: modelModule.AbstractControl,
validators: AsyncValidatorFn[]): any[] {
function _executeAsyncValidators(
control: modelModule.AbstractControl, validators: AsyncValidatorFn[]): any[] {
return validators.map(v => v(control));
}

View File

@ -1,9 +1,11 @@
import {Injectable, Inject, Optional} from '@angular/core';
import {Inject, Injectable, Optional} from '@angular/core';
import {isPresent} from '../facade/lang';
import {LocationStrategy, APP_BASE_HREF} from './location_strategy';
import {Location} from './location';
import {UrlChangeListener, PlatformLocation} from './platform_location';
import {APP_BASE_HREF, LocationStrategy} from './location_strategy';
import {PlatformLocation, UrlChangeListener} from './platform_location';
/**
@ -51,7 +53,8 @@ import {UrlChangeListener, PlatformLocation} from './platform_location';
@Injectable()
export class HashLocationStrategy extends LocationStrategy {
private _baseHref: string = '';
constructor(private _platformLocation: PlatformLocation,
constructor(
private _platformLocation: PlatformLocation,
@Optional() @Inject(APP_BASE_HREF) _baseHref?: string) {
super();
if (isPresent(_baseHref)) {

View File

@ -1,8 +1,10 @@
import {Injectable, EventEmitter} from '@angular/core';
import {EventEmitter, Injectable} from '@angular/core';
import {ObservableWrapper} from '../facade/async';
import {LocationStrategy} from './location_strategy';
/**
* `Location` is a service that applications can use to interact with a browser's URL.
* Depending on which {@link LocationStrategy} is used, `Location` will either persist
@ -127,7 +129,8 @@ export class Location {
/**
* Subscribe to the platform's `popState` events.
*/
subscribe(onNext: (value: any) => void, onThrow: (exception: any) => void = null,
subscribe(
onNext: (value: any) => void, onThrow: (exception: any) => void = null,
onReturn: () => void = null): Object {
return ObservableWrapper.subscribe(this._subject, onNext, onThrow, onReturn);
}

View File

@ -1,10 +1,12 @@
import {Injectable, Inject, Optional} from '@angular/core';
import {isBlank} from '../facade/lang';
import {BaseException} from '../facade/exceptions';
import {Inject, Injectable, Optional} from '@angular/core';
import {BaseException} from '../facade/exceptions';
import {isBlank} from '../facade/lang';
import {PlatformLocation, UrlChangeListener} from './platform_location';
import {LocationStrategy, APP_BASE_HREF} from './location_strategy';
import {Location} from './location';
import {APP_BASE_HREF, LocationStrategy} from './location_strategy';
import {PlatformLocation, UrlChangeListener} from './platform_location';
/**
* `PathLocationStrategy` is a {@link LocationStrategy} used to configure the
@ -60,7 +62,8 @@ import {Location} from './location';
export class PathLocationStrategy extends LocationStrategy {
private _baseHref: string;
constructor(private _platformLocation: PlatformLocation,
constructor(
private _platformLocation: PlatformLocation,
@Optional() @Inject(APP_BASE_HREF) href?: string) {
super();

View File

@ -5,13 +5,13 @@
*/
export {AsyncPipe} from './pipes/async_pipe';
export {COMMON_PIPES} from './pipes/common_pipes';
export {DatePipe} from './pipes/date_pipe';
export {JsonPipe} from './pipes/json_pipe';
export {SlicePipe} from './pipes/slice_pipe';
export {LowerCasePipe} from './pipes/lowercase_pipe';
export {DecimalPipe, PercentPipe, CurrencyPipe} from './pipes/number_pipe';
export {UpperCasePipe} from './pipes/uppercase_pipe';
export {ReplacePipe} from './pipes/replace_pipe';
export {I18nPluralPipe} from './pipes/i18n_plural_pipe';
export {I18nSelectPipe} from './pipes/i18n_select_pipe';
export {COMMON_PIPES} from './pipes/common_pipes';
export {JsonPipe} from './pipes/json_pipe';
export {LowerCasePipe} from './pipes/lowercase_pipe';
export {CurrencyPipe, DecimalPipe, PercentPipe} from './pipes/number_pipe';
export {ReplacePipe} from './pipes/replace_pipe';
export {SlicePipe} from './pipes/slice_pipe';
export {UpperCasePipe} from './pipes/uppercase_pipe';

View File

@ -1,7 +1,7 @@
import {Pipe, Injectable, ChangeDetectorRef, OnDestroy, WrappedValue} from '@angular/core';
import {ChangeDetectorRef, Injectable, OnDestroy, Pipe, WrappedValue} from '@angular/core';
import {EventEmitter, Observable, ObservableWrapper} from '../facade/async';
import {isBlank, isPresent, isPromise} from '../facade/lang';
import {ObservableWrapper, Observable, EventEmitter} from '../facade/async';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';

View File

@ -4,15 +4,16 @@
* This module provides a set of common Pipes.
*/
import {AsyncPipe} from './async_pipe';
import {UpperCasePipe} from './uppercase_pipe';
import {LowerCasePipe} from './lowercase_pipe';
import {JsonPipe} from './json_pipe';
import {SlicePipe} from './slice_pipe';
import {DatePipe} from './date_pipe';
import {DecimalPipe, PercentPipe, CurrencyPipe} from './number_pipe';
import {ReplacePipe} from './replace_pipe';
import {I18nPluralPipe} from './i18n_plural_pipe';
import {I18nSelectPipe} from './i18n_select_pipe';
import {JsonPipe} from './json_pipe';
import {LowerCasePipe} from './lowercase_pipe';
import {CurrencyPipe, DecimalPipe, PercentPipe} from './number_pipe';
import {ReplacePipe} from './replace_pipe';
import {SlicePipe} from './slice_pipe';
import {UpperCasePipe} from './uppercase_pipe';
/**
* A collection of Angular core pipes that are likely to be used in each and every
@ -35,5 +36,5 @@ export const COMMON_PIPES = /*@ts2dart_const*/[
DatePipe,
ReplacePipe,
I18nPluralPipe,
I18nSelectPipe
I18nSelectPipe,
];

View File

@ -1,11 +1,6 @@
import {PipeTransform, Pipe, Injectable} from '@angular/core';
import {
isDate,
isNumber,
isString,
DateWrapper,
isBlank,
} from '../facade/lang';
import {Injectable, Pipe, PipeTransform} from '@angular/core';
import {isDate, isNumber, isString, DateWrapper, isBlank,} from '../facade/lang';
import {DateFormatter} from '../facade/intl';
import {StringMapWrapper} from '../facade/collection';

View File

@ -1,5 +1,7 @@
import {PipeTransform, Pipe} from '@angular/core';
import {isStringMap, StringWrapper, isPresent, RegExpWrapper} from '../facade/lang';
import {Pipe, PipeTransform} from '@angular/core';
import {RegExpWrapper, StringWrapper, isPresent, isStringMap} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
var interpolationExp: RegExp = RegExpWrapper.create('#');

View File

@ -1,8 +1,11 @@
import {PipeTransform, Pipe} from '@angular/core';
import {isStringMap} from '../facade/lang';
import {Pipe, PipeTransform} from '@angular/core';
import {StringMapWrapper} from '../facade/collection';
import {isStringMap} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
/**
*
* Generic selector that displays the string that matches the current value.

View File

@ -1,5 +1,5 @@
import {Type, stringify} from '../facade/lang';
import {BaseException} from '../facade/exceptions';
import {Type, stringify} from '../facade/lang';
export class InvalidPipeArgumentException extends BaseException {
constructor(type: Type, value: Object) {

View File

@ -1,7 +1,9 @@
import {PipeTransform, Pipe} from '@angular/core';
import {Pipe, PipeTransform} from '@angular/core';
import {Json} from '../facade/lang';
/**
* Transforms any input value using `JSON.stringify`. Useful for debugging.
*

View File

@ -1,7 +1,10 @@
import {PipeTransform, Pipe} from '@angular/core';
import {isString, isBlank} from '../facade/lang';
import {Pipe, PipeTransform} from '@angular/core';
import {isBlank, isString} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
/**
* Transforms text to lowercase.
*

View File

@ -1,15 +1,8 @@
import {PipeTransform, Pipe} from '@angular/core';
import {Pipe, PipeTransform} from '@angular/core';
import {
isNumber,
isPresent,
isBlank,
NumberWrapper,
RegExpWrapper,
Type
} from '../facade/lang';
import {BaseException} from '../facade/exceptions';
import {NumberFormatter, NumberFormatStyle} from '../facade/intl';
import {NumberFormatStyle, NumberFormatter} from '../facade/intl';
import {NumberWrapper, RegExpWrapper, Type, isBlank, isNumber, isPresent} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
@ -19,7 +12,8 @@ var _re = RegExpWrapper.create('^(\\d+)?\\.((\\d+)(\\-(\\d+))?)?$');
/**
* Internal function to format numbers used by Decimal, Percent and Date pipes.
*/
function formatNumber(pipe: Type, value: number, style: NumberFormatStyle, digits: string, currency: string = null,
function formatNumber(
pipe: Type, value: number, style: NumberFormatStyle, digits: string, currency: string = null,
currencyAsSymbol: boolean = false): string {
if (isBlank(value)) return null;
if (!isNumber(value)) {
@ -138,9 +132,10 @@ export class PercentPipe implements PipeTransform {
*/
@Pipe({name: 'currency'})
export class CurrencyPipe implements PipeTransform {
transform(value: any, currencyCode: string = 'USD', symbolDisplay: boolean = false,
transform(
value: any, currencyCode: string = 'USD', symbolDisplay: boolean = false,
digits: string = null): string {
return formatNumber(CurrencyPipe, value, NumberFormatStyle.Currency, digits, currencyCode,
symbolDisplay);
return formatNumber(
CurrencyPipe, value, NumberFormatStyle.Currency, digits, currencyCode, symbolDisplay);
}
}

View File

@ -1,13 +1,6 @@
import {Injectable, PipeTransform, Pipe} from '@angular/core';
import {Injectable, Pipe, PipeTransform} from '@angular/core';
import {
isBlank,
isString,
isNumber,
isFunction,
RegExpWrapper,
StringWrapper
} from '../facade/lang';
import {RegExpWrapper, StringWrapper, isBlank, isFunction, isNumber, isString} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';

View File

@ -1,6 +1,7 @@
import {PipeTransform, Pipe} from '@angular/core';
import {isBlank, isString, isArray, StringWrapper} from '../facade/lang';
import {Pipe, PipeTransform} from '@angular/core';
import {ListWrapper} from '../facade/collection';
import {StringWrapper, isArray, isBlank, isString} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';

View File

@ -1,7 +1,10 @@
import {PipeTransform, Pipe} from '@angular/core';
import {isString, isBlank} from '../facade/lang';
import {Pipe, PipeTransform} from '@angular/core';
import {isBlank, isString} from '../facade/lang';
import {InvalidPipeArgumentException} from './invalid_pipe_argument_exception';
/**
* Implements uppercase transforms to text.
*

View File

@ -1,15 +1,4 @@
import {
beforeEach,
beforeEachProviders,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, beforeEachProviders, ddescribe, xdescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {ComponentFixture, TestComponentBuilder} from '@angular/compiler/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {ListWrapper, StringMapWrapper, SetWrapper} from '../../src/facade/collection';
@ -25,7 +14,9 @@ export function main() {
describe('binding to CSS class list', () => {
it('should clean up when the directive is destroyed',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div *ngFor="let item of items" [ngClass]="item"></div>';
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
@ -44,7 +35,9 @@ export function main() {
describe('expressions evaluating to objects', () => {
it('should add classes specified in an object literal',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="{foo: true, bar: false}"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -57,7 +50,9 @@ export function main() {
it('should add classes specified in an object literal without change in class names',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div [ngClass]="{'foo-bar': true, 'fooBar': true}"></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -69,7 +64,9 @@ export function main() {
}));
it('should add and remove classes based on changes in object literal values',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="{foo: condition, bar: !condition}"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -85,7 +82,9 @@ export function main() {
}));
it('should add and remove classes based on changes to the expression object',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="objExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -93,10 +92,12 @@ export function main() {
.then((fixture) => {
detectChangesAndCheck(fixture, 'foo');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'bar', true);
detectChangesAndCheck(fixture, 'foo bar');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'baz', true);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'baz', true);
detectChangesAndCheck(fixture, 'foo bar baz');
StringMapWrapper.delete(fixture.debugElement.componentInstance.objExpr, 'bar');
@ -107,7 +108,9 @@ export function main() {
}));
it('should add and remove classes based on reference changes to the expression object',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="objExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -126,7 +129,9 @@ export function main() {
}));
it('should remove active classes when expression evaluates to null',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="objExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -146,7 +151,9 @@ export function main() {
it('should allow multiple classes per expression',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="objExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -171,7 +178,9 @@ export function main() {
}));
it('should split by one or more spaces between classes',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="objExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -190,7 +199,9 @@ export function main() {
describe('expressions evaluating to lists', () => {
it('should add classes specified in a list literal',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div [ngClass]="['foo', 'bar', 'foo-bar', 'fooBar']"></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -202,7 +213,9 @@ export function main() {
}));
it('should add and remove classes based on changes to the expression',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="arrExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -225,7 +238,9 @@ export function main() {
}));
it('should add and remove classes when a reference changes',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="arrExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -241,7 +256,9 @@ export function main() {
}));
it('should take initial classes into account when a reference changes',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div class="foo" [ngClass]="arrExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -257,7 +274,9 @@ export function main() {
}));
it('should ignore empty or blank class names',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div class="foo" [ngClass]="arrExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -272,7 +291,9 @@ export function main() {
}));
it('should trim blanks from class names',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div class="foo" [ngClass]="arrExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -288,7 +309,9 @@ export function main() {
it('should allow multiple classes per item in arrays',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="arrExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -310,7 +333,9 @@ export function main() {
describe('expressions evaluating to sets', () => {
it('should add and remove classes if the set instance changed',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="setExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -333,7 +358,9 @@ export function main() {
describe('expressions evaluating to string', () => {
it('should add classes specified in a string literal',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div [ngClass]="'foo bar foo-bar fooBar'"></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -345,7 +372,9 @@ export function main() {
}));
it('should add and remove classes based on changes to the expression',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="strExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -365,7 +394,9 @@ export function main() {
}));
it('should remove active classes when switching from string to null',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div [ngClass]="strExpr"></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -381,7 +412,9 @@ export function main() {
}));
it('should take initial classes into account when switching from string to null',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div class="foo" [ngClass]="strExpr"></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -397,7 +430,9 @@ export function main() {
}));
it('should ignore empty and blank strings',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div class="foo" [ngClass]="strExpr"></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -415,16 +450,20 @@ export function main() {
describe('cooperation with other class-changing constructs', () => {
it('should co-operate with the class attribute',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div [ngClass]="objExpr" class="init foo"></div>';
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
.then((fixture) => {
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'bar', true);
detectChangesAndCheck(fixture, 'init foo bar');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'foo', false);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'foo', false);
detectChangesAndCheck(fixture, 'init bar');
fixture.debugElement.componentInstance.objExpr = null;
@ -435,16 +474,20 @@ export function main() {
}));
it('should co-operate with the interpolated class attribute',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div [ngClass]="objExpr" class="{{'init foo'}}"></div>`;
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
.then((fixture) => {
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'bar', true);
detectChangesAndCheck(fixture, `init foo bar`);
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'foo', false);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'foo', false);
detectChangesAndCheck(fixture, `init bar`);
fixture.debugElement.componentInstance.objExpr = null;
@ -455,16 +498,20 @@ export function main() {
}));
it('should co-operate with the class attribute and binding to it',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div [ngClass]="objExpr" class="init" [class]="'foo'"></div>`;
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
.then((fixture) => {
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'bar', true);
detectChangesAndCheck(fixture, `init foo bar`);
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'foo', false);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'foo', false);
detectChangesAndCheck(fixture, `init bar`);
fixture.debugElement.componentInstance.objExpr = null;
@ -475,7 +522,9 @@ export function main() {
}));
it('should co-operate with the class attribute and class.name binding',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
'<div class="init foo" [ngClass]="objExpr" [class.baz]="condition"></div>';
@ -484,10 +533,12 @@ export function main() {
.then((fixture) => {
detectChangesAndCheck(fixture, 'init foo baz');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'bar', true);
detectChangesAndCheck(fixture, 'init foo baz bar');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'foo', false);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'foo', false);
detectChangesAndCheck(fixture, 'init baz bar');
fixture.debugElement.componentInstance.condition = false;
@ -498,7 +549,9 @@ export function main() {
}));
it('should co-operate with initial class and class attribute binding when binding changes',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div class="init" [ngClass]="objExpr" [class]="strExpr"></div>';
tcb.overrideTemplate(TestComponent, template)
@ -506,7 +559,8 @@ export function main() {
.then((fixture) => {
detectChangesAndCheck(fixture, 'init foo');
StringMapWrapper.set(fixture.debugElement.componentInstance.objExpr, 'bar', true);
StringMapWrapper.set(
fixture.debugElement.componentInstance.objExpr, 'bar', true);
detectChangesAndCheck(fixture, 'init foo bar');
fixture.debugElement.componentInstance.strExpr = 'baz';

View File

@ -1,13 +1,4 @@
import {
beforeEach,
beforeEachProviders,
ddescribe,
describe,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, beforeEachProviders, ddescribe, describe, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder, ComponentFixture} from '@angular/compiler/testing';
@ -25,7 +16,9 @@ export function main() {
'<div><copy-me template="ngFor let item of items">{{item.toString()}};</copy-me></div>';
it('should reflect initial elements',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, TEMPLATE)
.createAsync(TestComponent)
.then((fixture) => {
@ -36,7 +29,9 @@ export function main() {
}));
it('should reflect added elements',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, TEMPLATE)
.createAsync(TestComponent)
.then((fixture) => {
@ -51,7 +46,9 @@ export function main() {
}));
it('should reflect removed elements',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, TEMPLATE)
.createAsync(TestComponent)
.then((fixture) => {
@ -66,7 +63,9 @@ export function main() {
}));
it('should reflect moved elements',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, TEMPLATE)
.createAsync(TestComponent)
.then((fixture) => {
@ -82,7 +81,9 @@ export function main() {
}));
it('should reflect a mix of all changes (additions/removals/moves)',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, TEMPLATE)
.createAsync(TestComponent)
.then((fixture) => {
@ -98,8 +99,11 @@ export function main() {
}));
it('should iterate over an array of objects',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<ul><li template="ngFor let item of items">{{item["name"]}};</li></ul>';
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
'<ul><li template="ngFor let item of items">{{item["name"]}};</li></ul>';
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
@ -128,7 +132,9 @@ export function main() {
}));
it('should gracefully handle nulls',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<ul><li template="ngFor let item of null">{{item}};</li></ul>';
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
@ -140,7 +146,9 @@ export function main() {
}));
it('should gracefully handle ref changing to null and back',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, TEMPLATE)
.createAsync(TestComponent)
.then((fixture) => {
@ -160,7 +168,9 @@ export function main() {
if (!IS_DART) {
it('should throw on non-iterable ref and suggest using an array',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, TEMPLATE)
.createAsync(TestComponent)
.then((fixture) => {
@ -177,7 +187,9 @@ export function main() {
}
it('should throw on ref changing to string',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, TEMPLATE)
.createAsync(TestComponent)
.then((fixture) => {
@ -191,7 +203,9 @@ export function main() {
}));
it('should works with duplicates',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, TEMPLATE)
.createAsync(TestComponent)
.then((fixture) => {
@ -204,7 +218,9 @@ export function main() {
}));
it('should repeat over nested arrays',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div>' +
'<div template="ngFor let item of items">' +
'<div template="ngFor let subitem of item">' +
@ -231,7 +247,9 @@ export function main() {
}));
it('should repeat over nested arrays with no intermediate element',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div><template ngFor let-item [ngForOf]="items">' +
'<div template="ngFor let subitem of item">' +
'{{subitem}}-{{item.length}};' +
@ -252,7 +270,9 @@ export function main() {
}));
it('should repeat over nested ngIf that are the last node in the ngFor temlate',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
`<div><template ngFor let-item [ngForOf]="items" let-i="index"><div>{{i}}|</div>` +
`<div *ngIf="i % 2 == 0">even|</div></template></div>`;
@ -279,7 +299,9 @@ export function main() {
}));
it('should display indices correctly',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
'<div><copy-me template="ngFor: let item of items; let i=index">{{i.toString()}}</copy-me></div>';
@ -298,7 +320,9 @@ export function main() {
}));
it('should display first item correctly',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
'<div><copy-me template="ngFor: let item of items; let isFirst=first">{{isFirst.toString()}}</copy-me></div>';
@ -317,7 +341,9 @@ export function main() {
}));
it('should display last item correctly',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
'<div><copy-me template="ngFor: let item of items; let isLast=last">{{isLast.toString()}}</copy-me></div>';
@ -336,7 +362,9 @@ export function main() {
}));
it('should display even items correctly',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
'<div><copy-me template="ngFor: let item of items; let isEven=even">{{isEven.toString()}}</copy-me></div>';
@ -355,7 +383,9 @@ export function main() {
}));
it('should display odd items correctly',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
'<div><copy-me template="ngFor: let item of items; let isOdd=odd">{{isOdd.toString()}}</copy-me></div>';
@ -374,7 +404,9 @@ export function main() {
}));
it('should allow to use a custom template',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(
TestComponent,
'<ul><template ngFor [ngForOf]="items" [ngForTemplate]="contentTpl"></template></ul>')
@ -393,7 +425,9 @@ export function main() {
}));
it('should use a default template if a custom one is null',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, `<ul><template ngFor let-item [ngForOf]="items"
[ngForTemplate]="contentTpl" let-i="index">{{i}}: {{item}};</template></ul>`)
.overrideTemplate(ComponentUsingTestComponent, '<test-cmp></test-cmp>')
@ -409,7 +443,9 @@ export function main() {
}));
it('should use a custom template when both default and a custom one are present',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb.overrideTemplate(TestComponent, `<ul><template ngFor let-item [ngForOf]="items"
[ngForTemplate]="contentTpl" let-i="index">{{i}}=> {{item}};</template></ul>`)
.overrideTemplate(
@ -428,7 +464,9 @@ export function main() {
describe('track by', function() {
it('should not replace tracked items',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
`<template ngFor let-item [ngForOf]="items" [ngForTrackBy]="trackById" let-i="index">
<p>{{items[i]}}</p>
@ -450,7 +488,9 @@ export function main() {
});
}));
it('should update implicit local variable on view',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
`<div><template ngFor let-item [ngForOf]="items" [ngForTrackBy]="trackById">{{item['color']}}</template></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -466,7 +506,9 @@ export function main() {
});
}));
it('should move items around and keep them updated ',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
`<div><template ngFor let-item [ngForOf]="items" [ngForTrackBy]="trackById">{{item['color']}}</template></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -485,7 +527,9 @@ export function main() {
}));
it('should handle added and removed items properly when tracking by index',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
`<div><template ngFor let-item [ngForOf]="items" [ngForTrackBy]="trackByIndex">{{item}}</template></div>`;
tcb.overrideTemplate(TestComponent, template)

View File

@ -1,12 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {expect} from '@angular/platform-browser/testing';
import {TestComponentBuilder} from '@angular/compiler/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
@ -21,15 +13,18 @@ import {IS_DART} from '../../src/facade/lang';
export function main() {
describe('ngIf directive', () => {
it('should work in a template attribute',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var html = '<div><copy-me template="ngIf booleanCondition">hello</copy-me></div>';
tcb.overrideTemplate(TestComponent, html)
.createAsync(TestComponent)
.then((fixture) => {
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(1);
expect(fixture.debugElement.nativeElement).toHaveText('hello');
async.done();
@ -37,7 +32,9 @@ export function main() {
}));
it('should work in a template element',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var html =
'<div><template [ngIf]="booleanCondition"><copy-me>hello2</copy-me></template></div>';
@ -45,8 +42,9 @@ export function main() {
.createAsync(TestComponent)
.then((fixture) => {
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(1);
expect(fixture.debugElement.nativeElement).toHaveText('hello2');
async.done();
@ -54,7 +52,9 @@ export function main() {
}));
it('should toggle node when condition changes',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var html = '<div><copy-me template="ngIf booleanCondition">hello</copy-me></div>';
tcb.overrideTemplate(TestComponent, html)
@ -62,22 +62,25 @@ export function main() {
.then((fixture) => {
fixture.debugElement.componentInstance.booleanCondition = false;
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(0);
expect(fixture.debugElement.nativeElement).toHaveText('');
fixture.debugElement.componentInstance.booleanCondition = true;
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(1);
expect(fixture.debugElement.nativeElement).toHaveText('hello');
fixture.debugElement.componentInstance.booleanCondition = false;
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(0);
expect(fixture.debugElement.nativeElement).toHaveText('');
@ -86,7 +89,9 @@ export function main() {
}));
it('should handle nested if correctly',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var html =
'<div><template [ngIf]="booleanCondition"><copy-me *ngIf="nestedBooleanCondition">hello</copy-me></template></div>';
@ -95,36 +100,41 @@ export function main() {
.then((fixture) => {
fixture.debugElement.componentInstance.booleanCondition = false;
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(0);
expect(fixture.debugElement.nativeElement).toHaveText('');
fixture.debugElement.componentInstance.booleanCondition = true;
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(1);
expect(fixture.debugElement.nativeElement).toHaveText('hello');
fixture.debugElement.componentInstance.nestedBooleanCondition = false;
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(0);
expect(fixture.debugElement.nativeElement).toHaveText('');
fixture.debugElement.componentInstance.nestedBooleanCondition = true;
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(1);
expect(fixture.debugElement.nativeElement).toHaveText('hello');
fixture.debugElement.componentInstance.booleanCondition = false;
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(0);
expect(fixture.debugElement.nativeElement).toHaveText('');
@ -133,9 +143,10 @@ export function main() {
}));
it('should update several nodes with if',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var html =
'<div>' +
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var html = '<div>' +
'<copy-me template="ngIf numberCondition + 1 >= 2">helloNumber</copy-me>' +
'<copy-me template="ngIf stringCondition == \'foo\'">helloString</copy-me>' +
'<copy-me template="ngIf functionCondition(stringCondition, numberCondition)">helloFunction</copy-me>' +
@ -145,24 +156,27 @@ export function main() {
.createAsync(TestComponent)
.then((fixture) => {
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(3);
expect(getDOM().getText(fixture.debugElement.nativeElement))
.toEqual('helloNumberhelloStringhelloFunction');
fixture.debugElement.componentInstance.numberCondition = 0;
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(1);
expect(fixture.debugElement.nativeElement).toHaveText('helloString');
fixture.debugElement.componentInstance.numberCondition = 1;
fixture.debugElement.componentInstance.stringCondition = "bar";
fixture.debugElement.componentInstance.stringCondition = 'bar';
fixture.detectChanges();
expect(
getDOM().querySelectorAll(fixture.debugElement.nativeElement, 'copy-me').length)
expect(getDOM()
.querySelectorAll(fixture.debugElement.nativeElement, 'copy-me')
.length)
.toEqual(1);
expect(fixture.debugElement.nativeElement).toHaveText('helloNumber');
async.done();
@ -172,7 +186,9 @@ export function main() {
if (!IS_DART) {
it('should not add the element twice if the condition goes from true to true (JS)',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var html = '<div><copy-me template="ngIf numberCondition">hello</copy-me></div>';
tcb.overrideTemplate(TestComponent, html)
@ -198,7 +214,9 @@ export function main() {
}));
it('should not recreate the element if the condition goes from true to true (JS)',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var html = '<div><copy-me template="ngIf numberCondition">hello</copy-me></div>';
tcb.overrideTemplate(TestComponent, html)
@ -206,13 +224,15 @@ export function main() {
.then((fixture) => {
fixture.detectChanges();
getDOM().addClass(
getDOM().querySelector(fixture.debugElement.nativeElement, 'copy-me'), "foo");
getDOM().querySelector(fixture.debugElement.nativeElement, 'copy-me'),
'foo');
fixture.debugElement.componentInstance.numberCondition = 2;
fixture.detectChanges();
expect(getDOM().hasClass(
expect(
getDOM().hasClass(
getDOM().querySelector(fixture.debugElement.nativeElement, 'copy-me'),
"foo"))
'foo'))
.toBe(true);
async.done();
@ -222,7 +242,9 @@ export function main() {
if (IS_DART) {
it('should not create the element if the condition is not a boolean (DART)',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var html = '<div><copy-me template="ngIf numberCondition">hello</copy-me></div>';
tcb.overrideTemplate(TestComponent, html)
@ -253,7 +275,9 @@ class TestComponent {
this.booleanCondition = true;
this.nestedBooleanCondition = true;
this.numberCondition = 1;
this.stringCondition = "foo";
this.functionCondition = function(s: any /** TODO #9100 */, n: any /** TODO #9100 */) { return s == "foo" && n == 1; };
this.stringCondition = 'foo';
this.functionCondition = function(s: any /** TODO #9100 */, n: any /** TODO #9100 */) {
return s == 'foo' && n == 1;
};
}
}

View File

@ -1,14 +1,4 @@
import {
beforeEachProviders,
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEachProviders, beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder} from '@angular/compiler/testing';
@ -20,7 +10,9 @@ export function main() {
beforeEachProviders(() => [{provide: NgLocalization, useClass: TestLocalizationMap}]);
it('should display the template according to the exact value',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div>' +
'<ul [ngPlural]="switchValue">' +
'<template ngPluralCase="=0"><li>you have no messages.</li></template>' +
@ -43,9 +35,10 @@ export function main() {
}));
it('should display the template according to the category',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
'<div>' +
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div>' +
'<ul [ngPlural]="switchValue">' +
'<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
'<template ngPluralCase="many"><li>you have many messages.</li></template>' +
@ -56,7 +49,8 @@ export function main() {
.then((fixture) => {
fixture.debugElement.componentInstance.switchValue = 2;
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('you have a few messages.');
expect(fixture.debugElement.nativeElement)
.toHaveText('you have a few messages.');
fixture.debugElement.componentInstance.switchValue = 8;
fixture.detectChanges();
@ -67,9 +61,10 @@ export function main() {
}));
it('should default to other when no matches are found',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
'<div>' +
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div>' +
'<ul [ngPlural]="switchValue">' +
'<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
'<template ngPluralCase="other"><li>default message.</li></template>' +
@ -87,9 +82,10 @@ export function main() {
}));
it('should prioritize value matches over category matches',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
'<div>' +
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div>' +
'<ul [ngPlural]="switchValue">' +
'<template ngPluralCase="few"><li>you have a few messages.</li></template>' +
'<template ngPluralCase="=2">you have two messages.</template>' +
@ -104,7 +100,8 @@ export function main() {
fixture.debugElement.componentInstance.switchValue = 3;
fixture.detectChanges();
expect(fixture.debugElement.nativeElement).toHaveText('you have a few messages.');
expect(fixture.debugElement.nativeElement)
.toHaveText('you have a few messages.');
async.done();
});

View File

@ -1,15 +1,4 @@
import {
beforeEach,
beforeEachProviders,
ddescribe,
xdescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, beforeEachProviders, ddescribe, xdescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder, ComponentFixture} from '@angular/compiler/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
@ -24,15 +13,17 @@ export function main() {
describe('binding to CSS styles', () => {
it('should add styles specified in an object literal',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div [ngStyle]="{'max-width': '40px'}"></div>`;
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
.then((fixture) => {
fixture.detectChanges();
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'max-width'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'max-width'))
.toEqual('40px');
async.done();
@ -40,7 +31,9 @@ export function main() {
}));
it('should add and change styles specified in an object expression',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div [ngStyle]="expr"></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -50,15 +43,15 @@ export function main() {
fixture.debugElement.componentInstance.expr = {'max-width': '40px'};
fixture.detectChanges();
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'max-width'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'max-width'))
.toEqual('40px');
expr = fixture.debugElement.componentInstance.expr;
(expr as any /** TODO #9100 */)['max-width'] = '30%';
fixture.detectChanges();
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'max-width'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'max-width'))
.toEqual('30%');
async.done();
@ -66,7 +59,9 @@ export function main() {
}));
it('should remove styles when deleting a key in an object expression',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div [ngStyle]="expr"></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -74,14 +69,15 @@ export function main() {
.then((fixture) => {
fixture.debugElement.componentInstance.expr = {'max-width': '40px'};
fixture.detectChanges();
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'max-width'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'max-width'))
.toEqual('40px');
StringMapWrapper.delete(fixture.debugElement.componentInstance.expr, 'max-width');
StringMapWrapper.delete(
fixture.debugElement.componentInstance.expr, 'max-width');
fixture.detectChanges();
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'max-width'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'max-width'))
.toEqual('');
async.done();
@ -89,7 +85,9 @@ export function main() {
}));
it('should co-operate with the style attribute',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div style="font-size: 12px" [ngStyle]="expr"></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -97,20 +95,21 @@ export function main() {
.then((fixture) => {
fixture.debugElement.componentInstance.expr = {'max-width': '40px'};
fixture.detectChanges();
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'max-width'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'max-width'))
.toEqual('40px');
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'font-size'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'font-size'))
.toEqual('12px');
StringMapWrapper.delete(fixture.debugElement.componentInstance.expr, 'max-width');
StringMapWrapper.delete(
fixture.debugElement.componentInstance.expr, 'max-width');
fixture.detectChanges();
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'max-width'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'max-width'))
.toEqual('');
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'font-size'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'font-size'))
.toEqual('12px');
async.done();
@ -118,7 +117,9 @@ export function main() {
}));
it('should co-operate with the style.[styleName]="expr" special-case in the compiler',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<div [style.font-size.px]="12" [ngStyle]="expr"></div>`;
tcb.overrideTemplate(TestComponent, template)
@ -126,21 +127,22 @@ export function main() {
.then((fixture) => {
fixture.debugElement.componentInstance.expr = {'max-width': '40px'};
fixture.detectChanges();
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'max-width'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'max-width'))
.toEqual('40px');
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'font-size'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'font-size'))
.toEqual('12px');
StringMapWrapper.delete(fixture.debugElement.componentInstance.expr, 'max-width');
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'font-size'))
StringMapWrapper.delete(
fixture.debugElement.componentInstance.expr, 'max-width');
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'font-size'))
.toEqual('12px');
fixture.detectChanges();
expect(
getDOM().getStyle(fixture.debugElement.children[0].nativeElement, 'max-width'))
expect(getDOM().getStyle(
fixture.debugElement.children[0].nativeElement, 'max-width'))
.toEqual('');
async.done();

View File

@ -1,13 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {Component} from '@angular/core';
import {TestComponentBuilder, ComponentFixture} from '@angular/compiler/testing';
@ -18,7 +9,9 @@ export function main() {
describe('switch', () => {
describe('switch value changes', () => {
it('should switch amongst when values',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div>' +
'<ul [ngSwitch]="switchValue">' +
'<template ngSwitchWhen="a"><li>when a</li></template>' +
@ -44,7 +37,9 @@ export function main() {
}));
it('should switch amongst when values with fallback to default',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div>' +
'<ul [ngSwitch]="switchValue">' +
'<li template="ngSwitchWhen \'a\'">when a</li>' +
@ -70,7 +65,9 @@ export function main() {
}));
it('should support multiple whens with the same value',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div>' +
'<ul [ngSwitch]="switchValue">' +
'<template ngSwitchWhen="a"><li>when a1;</li></template>' +
@ -103,7 +100,9 @@ export function main() {
describe('when values changes', () => {
it('should switch amongst when values',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div>' +
'<ul [ngSwitch]="switchValue">' +
'<template [ngSwitchWhen]="when1"><li>when 1;</li></template>' +

View File

@ -1,13 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder, ComponentFixture} from '@angular/compiler/testing';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {Component, Directive, TemplateRef, ContentChildren, QueryList} from '@angular/core';
@ -16,7 +7,9 @@ import {NgTemplateOutlet} from '@angular/common';
export function main() {
describe('insert', () => {
it('should do nothing if templateRef is null',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<template [ngTemplateOutlet]="null"></template>`;
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
@ -30,7 +23,9 @@ export function main() {
}));
it('should insert content specified by TemplateRef',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
`<tpl-refs #refs="tplRefs"><template>foo</template></tpl-refs><template [ngTemplateOutlet]="currentTplRef"></template>`;
tcb.overrideTemplate(TestComponent, template)
@ -51,7 +46,9 @@ export function main() {
}));
it('should clear content if TemplateRef becomes null',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
`<tpl-refs #refs="tplRefs"><template>foo</template></tpl-refs><template [ngTemplateOutlet]="currentTplRef"></template>`;
tcb.overrideTemplate(TestComponent, template)
@ -74,8 +71,11 @@ export function main() {
}));
it('should swap content if TemplateRef changes',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = `<tpl-refs #refs="tplRefs"><template>foo</template><template>bar</template></tpl-refs><template [ngTemplateOutlet]="currentTplRef"></template>`;
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template =
`<tpl-refs #refs="tplRefs"><template>foo</template><template>bar</template></tpl-refs><template [ngTemplateOutlet]="currentTplRef"></template>`;
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
.then((fixture) => {

View File

@ -1,13 +1,4 @@
import {
beforeEach,
ddescribe,
describe,
expect,
iit,
inject,
it,
xit,
} from '@angular/core/testing/testing_internal';
import {beforeEach, ddescribe, describe, expect, iit, inject, it, xit,} from '@angular/core/testing/testing_internal';
import {TestComponentBuilder, ComponentFixture} from '@angular/compiler/testing';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {Component, Directive} from '@angular/core';
@ -17,7 +8,9 @@ import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
export function main() {
describe('non-bindable', () => {
it('should not interpolate children',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div>{{text}}<span ngNonBindable>{{text}}</span></div>';
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
@ -29,7 +22,9 @@ export function main() {
}));
it('should ignore directives on child nodes',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div ngNonBindable><span id=child test-dec>{{text}}</span></div>';
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)
@ -45,7 +40,9 @@ export function main() {
}));
it('should trigger directives on the same node',
inject([TestComponentBuilder, AsyncTestCompleter], (tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var template = '<div><span id=child ngNonBindable test-dec>{{text}}</span></div>';
tcb.overrideTemplate(TestComponent, template)
.createAsync(TestComponent)

View File

@ -1,41 +1,10 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach,
inject
} from '@angular/core/testing/testing_internal';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {
fakeAsync,
flushMicrotasks,
Log,
tick,
} from '@angular/core/testing';
import {fakeAsync, flushMicrotasks, Log, tick,} from '@angular/core/testing';
import {SpyNgControl, SpyValueAccessor} from '../spies';
import {
ControlGroup,
Control,
NgControlName,
NgControlGroup,
NgFormModel,
ControlValueAccessor,
Validators,
NgForm,
NgModel,
NgFormControl,
NgControl,
DefaultValueAccessor,
CheckboxControlValueAccessor,
SelectControlValueAccessor,
Validator
} from '@angular/common';
import {ControlGroup, Control, NgControlName, NgControlGroup, NgFormModel, ControlValueAccessor, Validators, NgForm, NgModel, NgFormControl, NgControl, DefaultValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor, Validator} from '@angular/common';
import {selectValueAccessor, composeValidators} from '@angular/common/src/forms-deprecated/directives/shared';
@ -53,13 +22,13 @@ class DummyControlValueAccessor implements ControlValueAccessor {
}
class CustomValidatorDirective implements Validator {
validate(c: Control): {[key: string]: any} { return {"custom": true}; }
validate(c: Control): {[key: string]: any} { return {'custom': true}; }
}
function asyncValidator(expected: any /** TODO #9100 */, timeout = 0) {
return (c: any /** TODO #9100 */) => {
var completer = PromiseWrapper.completer();
var res = c.value != expected ? {"async": true} : null;
var res = c.value != expected ? {'async': true} : null;
if (timeout == 0) {
completer.resolve(res);
} else {
@ -70,71 +39,73 @@ function asyncValidator(expected: any /** TODO #9100 */, timeout = 0) {
}
export function main() {
describe("Form Directives", () => {
describe('Form Directives', () => {
var defaultAccessor: DefaultValueAccessor;
beforeEach(() => { defaultAccessor = new DefaultValueAccessor(null, null); });
describe("shared", () => {
describe("selectValueAccessor", () => {
describe('shared', () => {
describe('selectValueAccessor', () => {
var dir: NgControl;
beforeEach(() => { dir = <any>new SpyNgControl(); });
it("should throw when given an empty array",
it('should throw when given an empty array',
() => { expect(() => selectValueAccessor(dir, [])).toThrowError(); });
it("should return the default value accessor when no other provided",
it('should return the default value accessor when no other provided',
() => { expect(selectValueAccessor(dir, [defaultAccessor])).toEqual(defaultAccessor); });
it("should return checkbox accessor when provided", () => {
it('should return checkbox accessor when provided', () => {
var checkboxAccessor = new CheckboxControlValueAccessor(null, null);
expect(selectValueAccessor(dir, [defaultAccessor, checkboxAccessor]))
.toEqual(checkboxAccessor);
expect(selectValueAccessor(dir, [
defaultAccessor, checkboxAccessor
])).toEqual(checkboxAccessor);
});
it("should return select accessor when provided", () => {
it('should return select accessor when provided', () => {
var selectAccessor = new SelectControlValueAccessor(null, null);
expect(selectValueAccessor(dir, [defaultAccessor, selectAccessor]))
.toEqual(selectAccessor);
expect(selectValueAccessor(dir, [
defaultAccessor, selectAccessor
])).toEqual(selectAccessor);
});
it("should throw when more than one build-in accessor is provided", () => {
it('should throw when more than one build-in accessor is provided', () => {
var checkboxAccessor = new CheckboxControlValueAccessor(null, null);
var selectAccessor = new SelectControlValueAccessor(null, null);
expect(() => selectValueAccessor(dir, [checkboxAccessor, selectAccessor])).toThrowError();
});
it("should return custom accessor when provided", () => {
it('should return custom accessor when provided', () => {
var customAccessor = new SpyValueAccessor();
var checkboxAccessor = new CheckboxControlValueAccessor(null, null);
expect(selectValueAccessor(dir, <any>[defaultAccessor, customAccessor, checkboxAccessor]))
.toEqual(customAccessor);
});
it("should throw when more than one custom accessor is provided", () => {
it('should throw when more than one custom accessor is provided', () => {
var customAccessor: ControlValueAccessor = <any>new SpyValueAccessor();
expect(() => selectValueAccessor(dir, [customAccessor, customAccessor])).toThrowError();
});
});
describe("composeValidators", () => {
it("should compose functions", () => {
var dummy1 = (_: any /** TODO #9100 */) => ({"dummy1": true});
var dummy2 = (_: any /** TODO #9100 */) => ({"dummy2": true});
describe('composeValidators', () => {
it('should compose functions', () => {
var dummy1 = (_: any /** TODO #9100 */) => ({'dummy1': true});
var dummy2 = (_: any /** TODO #9100 */) => ({'dummy2': true});
var v = composeValidators([dummy1, dummy2]);
expect(v(new Control(""))).toEqual({"dummy1": true, "dummy2": true});
expect(v(new Control(''))).toEqual({'dummy1': true, 'dummy2': true});
});
it("should compose validator directives", () => {
var dummy1 = (_: any /** TODO #9100 */) => ({"dummy1": true});
it('should compose validator directives', () => {
var dummy1 = (_: any /** TODO #9100 */) => ({'dummy1': true});
var v = composeValidators([dummy1, new CustomValidatorDirective()]);
expect(v(new Control(""))).toEqual({"dummy1": true, "custom": true});
expect(v(new Control(''))).toEqual({'dummy1': true, 'custom': true});
});
});
});
describe("NgFormModel", () => {
describe('NgFormModel', () => {
var form: any /** TODO #9100 */;
var formModel: ControlGroup;
var loginControlDir: any /** TODO #9100 */;
@ -142,19 +113,19 @@ export function main() {
beforeEach(() => {
form = new NgFormModel([], []);
formModel = new ControlGroup({
"login": new Control(),
"passwords":
new ControlGroup({"password": new Control(), "passwordConfirm": new Control()})
'login': new Control(),
'passwords':
new ControlGroup({'password': new Control(), 'passwordConfirm': new Control()})
});
form.form = formModel;
loginControlDir = new NgControlName(form, [Validators.required],
[asyncValidator("expected")], [defaultAccessor]);
loginControlDir.name = "login";
loginControlDir = new NgControlName(
form, [Validators.required], [asyncValidator('expected')], [defaultAccessor]);
loginControlDir.name = 'login';
loginControlDir.valueAccessor = new DummyControlValueAccessor();
});
it("should reexport control properties", () => {
it('should reexport control properties', () => {
expect(form.control).toBe(formModel);
expect(form.value).toBe(formModel.value);
expect(form.valid).toBe(formModel.valid);
@ -165,130 +136,132 @@ export function main() {
expect(form.untouched).toBe(formModel.untouched);
});
describe("addControl", () => {
it("should throw when no control found", () => {
describe('addControl', () => {
it('should throw when no control found', () => {
var dir = new NgControlName(form, null, null, [defaultAccessor]);
dir.name = "invalidName";
dir.name = 'invalidName';
expect(() => form.addControl(dir))
.toThrowError(new RegExp("Cannot find control 'invalidName'"));
.toThrowError(new RegExp('Cannot find control \'invalidName\''));
});
it("should throw when no value accessor", () => {
it('should throw when no value accessor', () => {
var dir = new NgControlName(form, null, null, null);
dir.name = "login";
dir.name = 'login';
expect(() => form.addControl(dir))
.toThrowError(new RegExp("No value accessor for 'login'"));
.toThrowError(new RegExp('No value accessor for \'login\''));
});
it("should set up validators", fakeAsync(() => {
it('should set up validators', fakeAsync(() => {
form.addControl(loginControlDir);
// sync validators are set
expect(formModel.hasError("required", ["login"])).toBe(true);
expect(formModel.hasError("async", ["login"])).toBe(false);
expect(formModel.hasError('required', ['login'])).toBe(true);
expect(formModel.hasError('async', ['login'])).toBe(false);
(<Control>formModel.find(["login"])).updateValue("invalid value");
(<Control>formModel.find(['login'])).updateValue('invalid value');
// sync validator passes, running async validators
expect(formModel.pending).toBe(true);
tick();
expect(formModel.hasError("required", ["login"])).toBe(false);
expect(formModel.hasError("async", ["login"])).toBe(true);
expect(formModel.hasError('required', ['login'])).toBe(false);
expect(formModel.hasError('async', ['login'])).toBe(true);
}));
it("should write value to the DOM", () => {
(<Control>formModel.find(["login"])).updateValue("initValue");
it('should write value to the DOM', () => {
(<Control>formModel.find(['login'])).updateValue('initValue');
form.addControl(loginControlDir);
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual("initValue");
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual('initValue');
});
it("should add the directive to the list of directives included in the form", () => {
it('should add the directive to the list of directives included in the form', () => {
form.addControl(loginControlDir);
expect(form.directives).toEqual([loginControlDir]);
});
});
describe("addControlGroup", () => {
describe('addControlGroup', () => {
var matchingPasswordsValidator = (g: any /** TODO #9100 */) => {
if (g.controls["password"].value != g.controls["passwordConfirm"].value) {
return {"differentPasswords": true};
if (g.controls['password'].value != g.controls['passwordConfirm'].value) {
return {'differentPasswords': true};
} else {
return null;
}
};
it("should set up validator", fakeAsync(() => {
var group = new NgControlGroup(form, [matchingPasswordsValidator],
[asyncValidator('expected')]);
group.name = "passwords";
it('should set up validator', fakeAsync(() => {
var group = new NgControlGroup(
form, [matchingPasswordsValidator], [asyncValidator('expected')]);
group.name = 'passwords';
form.addControlGroup(group);
(<Control>formModel.find(["passwords", "password"])).updateValue("somePassword");
(<Control>formModel.find(["passwords", "passwordConfirm"]))
.updateValue("someOtherPassword");
(<Control>formModel.find(['passwords', 'password'])).updateValue('somePassword');
(<Control>formModel.find([
'passwords', 'passwordConfirm'
])).updateValue('someOtherPassword');
// sync validators are set
expect(formModel.hasError("differentPasswords", ["passwords"])).toEqual(true);
expect(formModel.hasError('differentPasswords', ['passwords'])).toEqual(true);
(<Control>formModel.find(["passwords", "passwordConfirm"]))
.updateValue("somePassword");
(<Control>formModel.find([
'passwords', 'passwordConfirm'
])).updateValue('somePassword');
// sync validators pass, running async validators
expect(formModel.pending).toBe(true);
tick();
expect(formModel.hasError("async", ["passwords"])).toBe(true);
expect(formModel.hasError('async', ['passwords'])).toBe(true);
}));
});
describe("removeControl", () => {
it("should remove the directive to the list of directives included in the form", () => {
describe('removeControl', () => {
it('should remove the directive to the list of directives included in the form', () => {
form.addControl(loginControlDir);
form.removeControl(loginControlDir);
expect(form.directives).toEqual([]);
});
});
describe("ngOnChanges", () => {
it("should update dom values of all the directives", () => {
describe('ngOnChanges', () => {
it('should update dom values of all the directives', () => {
form.addControl(loginControlDir);
(<Control>formModel.find(["login"])).updateValue("new value");
(<Control>formModel.find(['login'])).updateValue('new value');
form.ngOnChanges({});
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual("new value");
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual('new value');
});
it("should set up a sync validator", () => {
var formValidator = (c: any /** TODO #9100 */) => ({"custom": true});
it('should set up a sync validator', () => {
var formValidator = (c: any /** TODO #9100 */) => ({'custom': true});
var f = new NgFormModel([formValidator], []);
f.form = formModel;
f.ngOnChanges({"form": new SimpleChange(null, null)});
f.ngOnChanges({'form': new SimpleChange(null, null)});
expect(formModel.errors).toEqual({"custom": true});
expect(formModel.errors).toEqual({'custom': true});
});
it("should set up an async validator", fakeAsync(() => {
var f = new NgFormModel([], [asyncValidator("expected")]);
it('should set up an async validator', fakeAsync(() => {
var f = new NgFormModel([], [asyncValidator('expected')]);
f.form = formModel;
f.ngOnChanges({"form": new SimpleChange(null, null)});
f.ngOnChanges({'form': new SimpleChange(null, null)});
tick();
expect(formModel.errors).toEqual({"async": true});
expect(formModel.errors).toEqual({'async': true});
}));
});
});
describe("NgForm", () => {
describe('NgForm', () => {
var form: any /** TODO #9100 */;
var formModel: ControlGroup;
var loginControlDir: any /** TODO #9100 */;
@ -299,14 +272,14 @@ export function main() {
formModel = form.form;
personControlGroupDir = new NgControlGroup(form, [], []);
personControlGroupDir.name = "person";
personControlGroupDir.name = 'person';
loginControlDir = new NgControlName(personControlGroupDir, null, null, [defaultAccessor]);
loginControlDir.name = "login";
loginControlDir.name = 'login';
loginControlDir.valueAccessor = new DummyControlValueAccessor();
});
it("should reexport control properties", () => {
it('should reexport control properties', () => {
expect(form.control).toBe(formModel);
expect(form.value).toBe(formModel.value);
expect(form.valid).toBe(formModel.valid);
@ -317,21 +290,21 @@ export function main() {
expect(form.untouched).toBe(formModel.untouched);
});
describe("addControl & addControlGroup", () => {
it("should create a control with the given name", fakeAsync(() => {
describe('addControl & addControlGroup', () => {
it('should create a control with the given name', fakeAsync(() => {
form.addControlGroup(personControlGroupDir);
form.addControl(loginControlDir);
flushMicrotasks();
expect(formModel.find(["person", "login"])).not.toBeNull;
expect(formModel.find(['person', 'login'])).not.toBeNull;
}));
// should update the form's value and validity
});
describe("removeControl & removeControlGroup", () => {
it("should remove control", fakeAsync(() => {
describe('removeControl & removeControlGroup', () => {
it('should remove control', fakeAsync(() => {
form.addControlGroup(personControlGroupDir);
form.addControl(loginControlDir);
@ -340,45 +313,45 @@ export function main() {
flushMicrotasks();
expect(formModel.find(["person"])).toBeNull();
expect(formModel.find(["person", "login"])).toBeNull();
expect(formModel.find(['person'])).toBeNull();
expect(formModel.find(['person', 'login'])).toBeNull();
}));
// should update the form's value and validity
});
it("should set up sync validator", fakeAsync(() => {
var formValidator = (c: any /** TODO #9100 */) => ({"custom": true});
it('should set up sync validator', fakeAsync(() => {
var formValidator = (c: any /** TODO #9100 */) => ({'custom': true});
var f = new NgForm([formValidator], []);
tick();
expect(f.form.errors).toEqual({"custom": true});
expect(f.form.errors).toEqual({'custom': true});
}));
it("should set up async validator", fakeAsync(() => {
var f = new NgForm([], [asyncValidator("expected")]);
it('should set up async validator', fakeAsync(() => {
var f = new NgForm([], [asyncValidator('expected')]);
tick();
expect(f.form.errors).toEqual({"async": true});
expect(f.form.errors).toEqual({'async': true});
}));
});
describe("NgControlGroup", () => {
describe('NgControlGroup', () => {
var formModel: any /** TODO #9100 */;
var controlGroupDir: any /** TODO #9100 */;
beforeEach(() => {
formModel = new ControlGroup({"login": new Control(null)});
formModel = new ControlGroup({'login': new Control(null)});
var parent = new NgFormModel([], []);
parent.form = new ControlGroup({"group": formModel});
parent.form = new ControlGroup({'group': formModel});
controlGroupDir = new NgControlGroup(parent, [], []);
controlGroupDir.name = "group";
controlGroupDir.name = 'group';
});
it("should reexport control properties", () => {
it('should reexport control properties', () => {
expect(controlGroupDir.control).toBe(formModel);
expect(controlGroupDir.value).toBe(formModel.value);
expect(controlGroupDir.valid).toBe(formModel.valid);
@ -390,7 +363,7 @@ export function main() {
});
});
describe("NgFormControl", () => {
describe('NgFormControl', () => {
var controlDir: any /** TODO #9100 */;
var control: any /** TODO #9100 */;
var checkProperties = function(control: any /** TODO #9100 */) {
@ -412,36 +385,36 @@ export function main() {
controlDir.form = control;
});
it("should reexport control properties", () => { checkProperties(control); });
it('should reexport control properties', () => { checkProperties(control); });
it("should reexport new control properties", () => {
it('should reexport new control properties', () => {
var newControl = new Control(null);
controlDir.form = newControl;
controlDir.ngOnChanges({"form": new SimpleChange(control, newControl)});
controlDir.ngOnChanges({'form': new SimpleChange(control, newControl)});
checkProperties(newControl);
});
it("should set up validator", () => {
it('should set up validator', () => {
expect(control.valid).toBe(true);
// this will add the required validator and recalculate the validity
controlDir.ngOnChanges({"form": new SimpleChange(null, control)});
controlDir.ngOnChanges({'form': new SimpleChange(null, control)});
expect(control.valid).toBe(false);
});
});
describe("NgModel", () => {
describe('NgModel', () => {
var ngModel: any /** TODO #9100 */;
beforeEach(() => {
ngModel =
new NgModel([Validators.required], [asyncValidator("expected")], [defaultAccessor]);
new NgModel([Validators.required], [asyncValidator('expected')], [defaultAccessor]);
ngModel.valueAccessor = new DummyControlValueAccessor();
});
it("should reexport control properties", () => {
it('should reexport control properties', () => {
var control = ngModel.control;
expect(ngModel.control).toBe(control);
expect(ngModel.value).toBe(control.value);
@ -453,34 +426,34 @@ export function main() {
expect(ngModel.untouched).toBe(control.untouched);
});
it("should set up validator", fakeAsync(() => {
it('should set up validator', fakeAsync(() => {
// this will add the required validator and recalculate the validity
ngModel.ngOnChanges({});
tick();
expect(ngModel.control.errors).toEqual({"required": true});
expect(ngModel.control.errors).toEqual({'required': true});
ngModel.control.updateValue("someValue");
ngModel.control.updateValue('someValue');
tick();
expect(ngModel.control.errors).toEqual({"async": true});
expect(ngModel.control.errors).toEqual({'async': true});
}));
});
describe("NgControlName", () => {
describe('NgControlName', () => {
var formModel: any /** TODO #9100 */;
var controlNameDir: any /** TODO #9100 */;
beforeEach(() => {
formModel = new Control("name");
formModel = new Control('name');
var parent = new NgFormModel([], []);
parent.form = new ControlGroup({"name": formModel});
parent.form = new ControlGroup({'name': formModel});
controlNameDir = new NgControlName(parent, [], [], [defaultAccessor]);
controlNameDir.name = "name";
controlNameDir.name = 'name';
});
it("should reexport control properties", () => {
it('should reexport control properties', () => {
expect(controlNameDir.control).toBe(formModel);
expect(controlNameDir.value).toBe(formModel.value);
expect(controlNameDir.valid).toBe(formModel.valid);

View File

@ -1,67 +1,59 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach
} from '@angular/core/testing/testing_internal';
import {Control, FormBuilder} from '@angular/common';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {PromiseWrapper} from '../../src/facade/promise';
export function main() {
function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ { return null; }
function asyncValidator(_: any /** TODO #9100 */) { return PromiseWrapper.resolve(null); }
describe("Form Builder", () => {
describe('Form Builder', () => {
var b: any /** TODO #9100 */;
beforeEach(() => { b = new FormBuilder(); });
it("should create controls from a value", () => {
var g = b.group({"login": "some value"});
it('should create controls from a value', () => {
var g = b.group({'login': 'some value'});
expect(g.controls["login"].value).toEqual("some value");
expect(g.controls['login'].value).toEqual('some value');
});
it("should create controls from an array", () => {
it('should create controls from an array', () => {
var g = b.group(
{"login": ["some value"], "password": ["some value", syncValidator, asyncValidator]});
{'login': ['some value'], 'password': ['some value', syncValidator, asyncValidator]});
expect(g.controls["login"].value).toEqual("some value");
expect(g.controls["password"].value).toEqual("some value");
expect(g.controls["password"].validator).toEqual(syncValidator);
expect(g.controls["password"].asyncValidator).toEqual(asyncValidator);
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['password'].value).toEqual('some value');
expect(g.controls['password'].validator).toEqual(syncValidator);
expect(g.controls['password'].asyncValidator).toEqual(asyncValidator);
});
it("should use controls", () => {
var g = b.group({"login": b.control("some value", syncValidator, asyncValidator)});
it('should use controls', () => {
var g = b.group({'login': b.control('some value', syncValidator, asyncValidator)});
expect(g.controls["login"].value).toEqual("some value");
expect(g.controls["login"].validator).toBe(syncValidator);
expect(g.controls["login"].asyncValidator).toBe(asyncValidator);
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it("should create groups with optional controls", () => {
var g = b.group({"login": "some value"}, {"optionals": {"login": false}});
it('should create groups with optional controls', () => {
var g = b.group({'login': 'some value'}, {'optionals': {'login': false}});
expect(g.contains("login")).toEqual(false);
expect(g.contains('login')).toEqual(false);
});
it("should create groups with a custom validator", () => {
var g = b.group({"login": "some value"},
{"validator": syncValidator, "asyncValidator": asyncValidator});
it('should create groups with a custom validator', () => {
var g = b.group(
{'login': 'some value'}, {'validator': syncValidator, 'asyncValidator': asyncValidator});
expect(g.validator).toBe(syncValidator);
expect(g.asyncValidator).toBe(asyncValidator);
});
it("should create control arrays", () => {
var c = b.control("three");
var a = b.array(["one", ["two", syncValidator], c, b.array(['four'])], syncValidator,
asyncValidator);
it('should create control arrays', () => {
var c = b.control('three');
var a = b.array(
['one', ['two', syncValidator], c, b.array(['four'])], syncValidator, asyncValidator);
expect(a.value).toEqual(['one', 'two', 'three', ['four']]);
expect(a.validator).toBe(syncValidator);

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +1,9 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach
} from '@angular/core/testing/testing_internal';
import {fakeAsync, flushMicrotasks, Log, tick} from '@angular/core/testing';
import {ControlGroup, Control, Validators, AbstractControl, ControlArray} from '@angular/common';
import {PromiseWrapper} from '../../src/facade/promise';
import {AbstractControl, Control, ControlArray, ControlGroup, Validators} from '@angular/common';
import {Log, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {EventEmitter, ObservableWrapper, TimerWrapper} from '../../src/facade/async';
import {PromiseWrapper} from '../../src/facade/promise';
export function main() {
function validator(key: string, error: any) {
@ -22,95 +14,98 @@ export function main() {
}
}
describe("Validators", () => {
describe("required", () => {
it("should error on an empty string",
() => { expect(Validators.required(new Control(""))).toEqual({"required": true}); });
describe('Validators', () => {
describe('required', () => {
it('should error on an empty string',
() => { expect(Validators.required(new Control(''))).toEqual({'required': true}); });
it("should error on null",
() => { expect(Validators.required(new Control(null))).toEqual({"required": true}); });
it('should error on null',
() => { expect(Validators.required(new Control(null))).toEqual({'required': true}); });
it("should not error on a non-empty string",
() => { expect(Validators.required(new Control("not empty"))).toEqual(null); });
it('should not error on a non-empty string',
() => { expect(Validators.required(new Control('not empty'))).toEqual(null); });
it("should accept zero as valid",
it('should accept zero as valid',
() => { expect(Validators.required(new Control(0))).toEqual(null); });
});
describe("minLength", () => {
it("should not error on an empty string",
() => { expect(Validators.minLength(2)(new Control(""))).toEqual(null); });
describe('minLength', () => {
it('should not error on an empty string',
() => { expect(Validators.minLength(2)(new Control(''))).toEqual(null); });
it("should not error on null",
it('should not error on null',
() => { expect(Validators.minLength(2)(new Control(null))).toEqual(null); });
it("should not error on valid strings",
() => { expect(Validators.minLength(2)(new Control("aa"))).toEqual(null); });
it('should not error on valid strings',
() => { expect(Validators.minLength(2)(new Control('aa'))).toEqual(null); });
it("should error on short strings", () => {
expect(Validators.minLength(2)(new Control("a")))
.toEqual({"minlength": {"requiredLength": 2, "actualLength": 1}});
it('should error on short strings', () => {
expect(Validators.minLength(2)(new Control('a'))).toEqual({
'minlength': {'requiredLength': 2, 'actualLength': 1}
});
});
});
describe("maxLength", () => {
it("should not error on an empty string",
() => { expect(Validators.maxLength(2)(new Control(""))).toEqual(null); });
describe('maxLength', () => {
it('should not error on an empty string',
() => { expect(Validators.maxLength(2)(new Control(''))).toEqual(null); });
it("should not error on null",
it('should not error on null',
() => { expect(Validators.maxLength(2)(new Control(null))).toEqual(null); });
it("should not error on valid strings",
() => { expect(Validators.maxLength(2)(new Control("aa"))).toEqual(null); });
it('should not error on valid strings',
() => { expect(Validators.maxLength(2)(new Control('aa'))).toEqual(null); });
it("should error on long strings", () => {
expect(Validators.maxLength(2)(new Control("aaa")))
.toEqual({"maxlength": {"requiredLength": 2, "actualLength": 3}});
it('should error on long strings', () => {
expect(Validators.maxLength(2)(new Control('aaa'))).toEqual({
'maxlength': {'requiredLength': 2, 'actualLength': 3}
});
});
});
describe("pattern", () => {
it("should not error on an empty string",
() => { expect(Validators.pattern("[a-zA-Z ]*")(new Control(""))).toEqual(null); });
describe('pattern', () => {
it('should not error on an empty string',
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control(''))).toEqual(null); });
it("should not error on null",
() => { expect(Validators.pattern("[a-zA-Z ]*")(new Control(null))).toEqual(null); });
it('should not error on null',
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control(null))).toEqual(null); });
it("should not error on valid strings",
() => { expect(Validators.pattern("[a-zA-Z ]*")(new Control("aaAA"))).toEqual(null); });
it('should not error on valid strings',
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control('aaAA'))).toEqual(null); });
it("should error on failure to match string", () => {
expect(Validators.pattern("[a-zA-Z ]*")(new Control("aaa0")))
.toEqual({"pattern": {"requiredPattern": "^[a-zA-Z ]*$", "actualValue": "aaa0"}});
it('should error on failure to match string', () => {
expect(Validators.pattern('[a-zA-Z ]*')(new Control('aaa0'))).toEqual({
'pattern': {'requiredPattern': '^[a-zA-Z ]*$', 'actualValue': 'aaa0'}
});
});
});
describe("compose", () => {
it("should return null when given null",
describe('compose', () => {
it('should return null when given null',
() => { expect(Validators.compose(null)).toBe(null); });
it("should collect errors from all the validators", () => {
var c = Validators.compose([validator("a", true), validator("b", true)]);
expect(c(new Control(""))).toEqual({"a": true, "b": true});
it('should collect errors from all the validators', () => {
var c = Validators.compose([validator('a', true), validator('b', true)]);
expect(c(new Control(''))).toEqual({'a': true, 'b': true});
});
it("should run validators left to right", () => {
var c = Validators.compose([validator("a", 1), validator("a", 2)]);
expect(c(new Control(""))).toEqual({"a": 2});
it('should run validators left to right', () => {
var c = Validators.compose([validator('a', 1), validator('a', 2)]);
expect(c(new Control(''))).toEqual({'a': 2});
});
it("should return null when no errors", () => {
it('should return null when no errors', () => {
var c = Validators.compose([Validators.nullValidator, Validators.nullValidator]);
expect(c(new Control(""))).toEqual(null);
expect(c(new Control(''))).toEqual(null);
});
it("should ignore nulls", () => {
it('should ignore nulls', () => {
var c = Validators.compose([null, Validators.required]);
expect(c(new Control(""))).toEqual({"required": true});
expect(c(new Control(''))).toEqual({'required': true});
});
});
describe("composeAsync", () => {
describe('composeAsync', () => {
function asyncValidator(expected: any /** TODO #9100 */, response: any /** TODO #9100 */) {
return (c: any /** TODO #9100 */) => {
var emitter = new EventEmitter();
@ -127,43 +122,42 @@ export function main() {
};
}
it("should return null when given null",
it('should return null when given null',
() => { expect(Validators.composeAsync(null)).toEqual(null); });
it("should collect errors from all the validators", fakeAsync(() => {
it('should collect errors from all the validators', fakeAsync(() => {
var c = Validators.composeAsync([
asyncValidator("expected", {"one": true}),
asyncValidator("expected", {"two": true})
asyncValidator('expected', {'one': true}), asyncValidator('expected', {'two': true})
]);
var value: any /** TODO #9100 */ = null;
(<Promise<any>>c(new Control("invalid"))).then(v => value = v);
(<Promise<any>>c(new Control('invalid'))).then(v => value = v);
tick(1);
expect(value).toEqual({"one": true, "two": true});
expect(value).toEqual({'one': true, 'two': true});
}));
it("should return null when no errors", fakeAsync(() => {
var c = Validators.composeAsync([asyncValidator("expected", {"one": true})]);
it('should return null when no errors', fakeAsync(() => {
var c = Validators.composeAsync([asyncValidator('expected', {'one': true})]);
var value: any /** TODO #9100 */ = null;
(<Promise<any>>c(new Control("expected"))).then(v => value = v);
(<Promise<any>>c(new Control('expected'))).then(v => value = v);
tick(1);
expect(value).toEqual(null);
}));
it("should ignore nulls", fakeAsync(() => {
var c = Validators.composeAsync([asyncValidator("expected", {"one": true}), null]);
it('should ignore nulls', fakeAsync(() => {
var c = Validators.composeAsync([asyncValidator('expected', {'one': true}), null]);
var value: any /** TODO #9100 */ = null;
(<Promise<any>>c(new Control("invalid"))).then(v => value = v);
(<Promise<any>>c(new Control('invalid'))).then(v => value = v);
tick(1);
expect(value).toEqual({"one": true});
expect(value).toEqual({'one': true});
}));
});
});

View File

@ -1,41 +1,10 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach,
inject
} from '@angular/core/testing/testing_internal';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, inject, it, xit} from '@angular/core/testing/testing_internal';
import {
fakeAsync,
flushMicrotasks,
Log,
tick,
} from '@angular/core/testing';
import {fakeAsync, flushMicrotasks, Log, tick,} from '@angular/core/testing';
import {SpyNgControl, SpyValueAccessor} from '../spies';
import {
ControlGroup,
Control,
NgControlName,
NgControlGroup,
NgFormModel,
ControlValueAccessor,
Validators,
NgForm,
NgModel,
NgFormControl,
NgControl,
DefaultValueAccessor,
CheckboxControlValueAccessor,
SelectControlValueAccessor,
Validator
} from '@angular/common/src/forms';
import {ControlGroup, Control, NgControlName, NgControlGroup, NgFormModel, ControlValueAccessor, Validators, NgForm, NgModel, NgFormControl, NgControl, DefaultValueAccessor, CheckboxControlValueAccessor, SelectControlValueAccessor, Validator} from '@angular/common/src/forms';
import {selectValueAccessor, composeValidators} from '@angular/common/src/forms/directives/shared';
@ -53,13 +22,13 @@ class DummyControlValueAccessor implements ControlValueAccessor {
}
class CustomValidatorDirective implements Validator {
validate(c: Control): {[key: string]: any} { return {"custom": true}; }
validate(c: Control): {[key: string]: any} { return {'custom': true}; }
}
function asyncValidator(expected: any /** TODO #9100 */, timeout = 0) {
return (c: any /** TODO #9100 */) => {
var completer = PromiseWrapper.completer();
var res = c.value != expected ? {"async": true} : null;
var res = c.value != expected ? {'async': true} : null;
if (timeout == 0) {
completer.resolve(res);
} else {
@ -70,71 +39,73 @@ function asyncValidator(expected: any /** TODO #9100 */, timeout = 0) {
}
export function main() {
describe("Form Directives", () => {
describe('Form Directives', () => {
var defaultAccessor: DefaultValueAccessor;
beforeEach(() => { defaultAccessor = new DefaultValueAccessor(null, null); });
describe("shared", () => {
describe("selectValueAccessor", () => {
describe('shared', () => {
describe('selectValueAccessor', () => {
var dir: NgControl;
beforeEach(() => { dir = <any>new SpyNgControl(); });
it("should throw when given an empty array",
it('should throw when given an empty array',
() => { expect(() => selectValueAccessor(dir, [])).toThrowError(); });
it("should return the default value accessor when no other provided",
it('should return the default value accessor when no other provided',
() => { expect(selectValueAccessor(dir, [defaultAccessor])).toEqual(defaultAccessor); });
it("should return checkbox accessor when provided", () => {
it('should return checkbox accessor when provided', () => {
var checkboxAccessor = new CheckboxControlValueAccessor(null, null);
expect(selectValueAccessor(dir, [defaultAccessor, checkboxAccessor]))
.toEqual(checkboxAccessor);
expect(selectValueAccessor(dir, [
defaultAccessor, checkboxAccessor
])).toEqual(checkboxAccessor);
});
it("should return select accessor when provided", () => {
it('should return select accessor when provided', () => {
var selectAccessor = new SelectControlValueAccessor(null, null);
expect(selectValueAccessor(dir, [defaultAccessor, selectAccessor]))
.toEqual(selectAccessor);
expect(selectValueAccessor(dir, [
defaultAccessor, selectAccessor
])).toEqual(selectAccessor);
});
it("should throw when more than one build-in accessor is provided", () => {
it('should throw when more than one build-in accessor is provided', () => {
var checkboxAccessor = new CheckboxControlValueAccessor(null, null);
var selectAccessor = new SelectControlValueAccessor(null, null);
expect(() => selectValueAccessor(dir, [checkboxAccessor, selectAccessor])).toThrowError();
});
it("should return custom accessor when provided", () => {
it('should return custom accessor when provided', () => {
var customAccessor = new SpyValueAccessor();
var checkboxAccessor = new CheckboxControlValueAccessor(null, null);
expect(selectValueAccessor(dir, <any>[defaultAccessor, customAccessor, checkboxAccessor]))
.toEqual(customAccessor);
});
it("should throw when more than one custom accessor is provided", () => {
it('should throw when more than one custom accessor is provided', () => {
var customAccessor: ControlValueAccessor = <any>new SpyValueAccessor();
expect(() => selectValueAccessor(dir, [customAccessor, customAccessor])).toThrowError();
});
});
describe("composeValidators", () => {
it("should compose functions", () => {
var dummy1 = (_: any /** TODO #9100 */) => ({"dummy1": true});
var dummy2 = (_: any /** TODO #9100 */) => ({"dummy2": true});
describe('composeValidators', () => {
it('should compose functions', () => {
var dummy1 = (_: any /** TODO #9100 */) => ({'dummy1': true});
var dummy2 = (_: any /** TODO #9100 */) => ({'dummy2': true});
var v = composeValidators([dummy1, dummy2]);
expect(v(new Control(""))).toEqual({"dummy1": true, "dummy2": true});
expect(v(new Control(''))).toEqual({'dummy1': true, 'dummy2': true});
});
it("should compose validator directives", () => {
var dummy1 = (_: any /** TODO #9100 */) => ({"dummy1": true});
it('should compose validator directives', () => {
var dummy1 = (_: any /** TODO #9100 */) => ({'dummy1': true});
var v = composeValidators([dummy1, new CustomValidatorDirective()]);
expect(v(new Control(""))).toEqual({"dummy1": true, "custom": true});
expect(v(new Control(''))).toEqual({'dummy1': true, 'custom': true});
});
});
});
describe("NgFormModel", () => {
describe('NgFormModel', () => {
var form: any /** TODO #9100 */;
var formModel: ControlGroup;
var loginControlDir: any /** TODO #9100 */;
@ -142,19 +113,19 @@ export function main() {
beforeEach(() => {
form = new NgFormModel([], []);
formModel = new ControlGroup({
"login": new Control(),
"passwords":
new ControlGroup({"password": new Control(), "passwordConfirm": new Control()})
'login': new Control(),
'passwords':
new ControlGroup({'password': new Control(), 'passwordConfirm': new Control()})
});
form.form = formModel;
loginControlDir = new NgControlName(form, [Validators.required],
[asyncValidator("expected")], [defaultAccessor]);
loginControlDir.name = "login";
loginControlDir = new NgControlName(
form, [Validators.required], [asyncValidator('expected')], [defaultAccessor]);
loginControlDir.name = 'login';
loginControlDir.valueAccessor = new DummyControlValueAccessor();
});
it("should reexport control properties", () => {
it('should reexport control properties', () => {
expect(form.control).toBe(formModel);
expect(form.value).toBe(formModel.value);
expect(form.valid).toBe(formModel.valid);
@ -165,130 +136,132 @@ export function main() {
expect(form.untouched).toBe(formModel.untouched);
});
describe("addControl", () => {
it("should throw when no control found", () => {
describe('addControl', () => {
it('should throw when no control found', () => {
var dir = new NgControlName(form, null, null, [defaultAccessor]);
dir.name = "invalidName";
dir.name = 'invalidName';
expect(() => form.addControl(dir))
.toThrowError(new RegExp("Cannot find control 'invalidName'"));
.toThrowError(new RegExp('Cannot find control \'invalidName\''));
});
it("should throw when no value accessor", () => {
it('should throw when no value accessor', () => {
var dir = new NgControlName(form, null, null, null);
dir.name = "login";
dir.name = 'login';
expect(() => form.addControl(dir))
.toThrowError(new RegExp("No value accessor for 'login'"));
.toThrowError(new RegExp('No value accessor for \'login\''));
});
it("should set up validators", fakeAsync(() => {
it('should set up validators', fakeAsync(() => {
form.addControl(loginControlDir);
// sync validators are set
expect(formModel.hasError("required", ["login"])).toBe(true);
expect(formModel.hasError("async", ["login"])).toBe(false);
expect(formModel.hasError('required', ['login'])).toBe(true);
expect(formModel.hasError('async', ['login'])).toBe(false);
(<Control>formModel.find(["login"])).updateValue("invalid value");
(<Control>formModel.find(['login'])).updateValue('invalid value');
// sync validator passes, running async validators
expect(formModel.pending).toBe(true);
tick();
expect(formModel.hasError("required", ["login"])).toBe(false);
expect(formModel.hasError("async", ["login"])).toBe(true);
expect(formModel.hasError('required', ['login'])).toBe(false);
expect(formModel.hasError('async', ['login'])).toBe(true);
}));
it("should write value to the DOM", () => {
(<Control>formModel.find(["login"])).updateValue("initValue");
it('should write value to the DOM', () => {
(<Control>formModel.find(['login'])).updateValue('initValue');
form.addControl(loginControlDir);
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual("initValue");
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual('initValue');
});
it("should add the directive to the list of directives included in the form", () => {
it('should add the directive to the list of directives included in the form', () => {
form.addControl(loginControlDir);
expect(form.directives).toEqual([loginControlDir]);
});
});
describe("addControlGroup", () => {
describe('addControlGroup', () => {
var matchingPasswordsValidator = (g: any /** TODO #9100 */) => {
if (g.controls["password"].value != g.controls["passwordConfirm"].value) {
return {"differentPasswords": true};
if (g.controls['password'].value != g.controls['passwordConfirm'].value) {
return {'differentPasswords': true};
} else {
return null;
}
};
it("should set up validator", fakeAsync(() => {
var group = new NgControlGroup(form, [matchingPasswordsValidator],
[asyncValidator('expected')]);
group.name = "passwords";
it('should set up validator', fakeAsync(() => {
var group = new NgControlGroup(
form, [matchingPasswordsValidator], [asyncValidator('expected')]);
group.name = 'passwords';
form.addControlGroup(group);
(<Control>formModel.find(["passwords", "password"])).updateValue("somePassword");
(<Control>formModel.find(["passwords", "passwordConfirm"]))
.updateValue("someOtherPassword");
(<Control>formModel.find(['passwords', 'password'])).updateValue('somePassword');
(<Control>formModel.find([
'passwords', 'passwordConfirm'
])).updateValue('someOtherPassword');
// sync validators are set
expect(formModel.hasError("differentPasswords", ["passwords"])).toEqual(true);
expect(formModel.hasError('differentPasswords', ['passwords'])).toEqual(true);
(<Control>formModel.find(["passwords", "passwordConfirm"]))
.updateValue("somePassword");
(<Control>formModel.find([
'passwords', 'passwordConfirm'
])).updateValue('somePassword');
// sync validators pass, running async validators
expect(formModel.pending).toBe(true);
tick();
expect(formModel.hasError("async", ["passwords"])).toBe(true);
expect(formModel.hasError('async', ['passwords'])).toBe(true);
}));
});
describe("removeControl", () => {
it("should remove the directive to the list of directives included in the form", () => {
describe('removeControl', () => {
it('should remove the directive to the list of directives included in the form', () => {
form.addControl(loginControlDir);
form.removeControl(loginControlDir);
expect(form.directives).toEqual([]);
});
});
describe("ngOnChanges", () => {
it("should update dom values of all the directives", () => {
describe('ngOnChanges', () => {
it('should update dom values of all the directives', () => {
form.addControl(loginControlDir);
(<Control>formModel.find(["login"])).updateValue("new value");
(<Control>formModel.find(['login'])).updateValue('new value');
form.ngOnChanges({});
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual("new value");
expect((<any>loginControlDir.valueAccessor).writtenValue).toEqual('new value');
});
it("should set up a sync validator", () => {
var formValidator = (c: any /** TODO #9100 */) => ({"custom": true});
it('should set up a sync validator', () => {
var formValidator = (c: any /** TODO #9100 */) => ({'custom': true});
var f = new NgFormModel([formValidator], []);
f.form = formModel;
f.ngOnChanges({"form": new SimpleChange(null, null)});
f.ngOnChanges({'form': new SimpleChange(null, null)});
expect(formModel.errors).toEqual({"custom": true});
expect(formModel.errors).toEqual({'custom': true});
});
it("should set up an async validator", fakeAsync(() => {
var f = new NgFormModel([], [asyncValidator("expected")]);
it('should set up an async validator', fakeAsync(() => {
var f = new NgFormModel([], [asyncValidator('expected')]);
f.form = formModel;
f.ngOnChanges({"form": new SimpleChange(null, null)});
f.ngOnChanges({'form': new SimpleChange(null, null)});
tick();
expect(formModel.errors).toEqual({"async": true});
expect(formModel.errors).toEqual({'async': true});
}));
});
});
describe("NgForm", () => {
describe('NgForm', () => {
var form: any /** TODO #9100 */;
var formModel: ControlGroup;
var loginControlDir: any /** TODO #9100 */;
@ -299,14 +272,14 @@ export function main() {
formModel = form.form;
personControlGroupDir = new NgControlGroup(form, [], []);
personControlGroupDir.name = "person";
personControlGroupDir.name = 'person';
loginControlDir = new NgControlName(personControlGroupDir, null, null, [defaultAccessor]);
loginControlDir.name = "login";
loginControlDir.name = 'login';
loginControlDir.valueAccessor = new DummyControlValueAccessor();
});
it("should reexport control properties", () => {
it('should reexport control properties', () => {
expect(form.control).toBe(formModel);
expect(form.value).toBe(formModel.value);
expect(form.valid).toBe(formModel.valid);
@ -317,21 +290,21 @@ export function main() {
expect(form.untouched).toBe(formModel.untouched);
});
describe("addControl & addControlGroup", () => {
it("should create a control with the given name", fakeAsync(() => {
describe('addControl & addControlGroup', () => {
it('should create a control with the given name', fakeAsync(() => {
form.addControlGroup(personControlGroupDir);
form.addControl(loginControlDir);
flushMicrotasks();
expect(formModel.find(["person", "login"])).not.toBeNull;
expect(formModel.find(['person', 'login'])).not.toBeNull;
}));
// should update the form's value and validity
});
describe("removeControl & removeControlGroup", () => {
it("should remove control", fakeAsync(() => {
describe('removeControl & removeControlGroup', () => {
it('should remove control', fakeAsync(() => {
form.addControlGroup(personControlGroupDir);
form.addControl(loginControlDir);
@ -340,45 +313,45 @@ export function main() {
flushMicrotasks();
expect(formModel.find(["person"])).toBeNull();
expect(formModel.find(["person", "login"])).toBeNull();
expect(formModel.find(['person'])).toBeNull();
expect(formModel.find(['person', 'login'])).toBeNull();
}));
// should update the form's value and validity
});
it("should set up sync validator", fakeAsync(() => {
var formValidator = (c: any /** TODO #9100 */) => ({"custom": true});
it('should set up sync validator', fakeAsync(() => {
var formValidator = (c: any /** TODO #9100 */) => ({'custom': true});
var f = new NgForm([formValidator], []);
tick();
expect(f.form.errors).toEqual({"custom": true});
expect(f.form.errors).toEqual({'custom': true});
}));
it("should set up async validator", fakeAsync(() => {
var f = new NgForm([], [asyncValidator("expected")]);
it('should set up async validator', fakeAsync(() => {
var f = new NgForm([], [asyncValidator('expected')]);
tick();
expect(f.form.errors).toEqual({"async": true});
expect(f.form.errors).toEqual({'async': true});
}));
});
describe("NgControlGroup", () => {
describe('NgControlGroup', () => {
var formModel: any /** TODO #9100 */;
var controlGroupDir: any /** TODO #9100 */;
beforeEach(() => {
formModel = new ControlGroup({"login": new Control(null)});
formModel = new ControlGroup({'login': new Control(null)});
var parent = new NgFormModel([], []);
parent.form = new ControlGroup({"group": formModel});
parent.form = new ControlGroup({'group': formModel});
controlGroupDir = new NgControlGroup(parent, [], []);
controlGroupDir.name = "group";
controlGroupDir.name = 'group';
});
it("should reexport control properties", () => {
it('should reexport control properties', () => {
expect(controlGroupDir.control).toBe(formModel);
expect(controlGroupDir.value).toBe(formModel.value);
expect(controlGroupDir.valid).toBe(formModel.valid);
@ -390,7 +363,7 @@ export function main() {
});
});
describe("NgFormControl", () => {
describe('NgFormControl', () => {
var controlDir: any /** TODO #9100 */;
var control: any /** TODO #9100 */;
var checkProperties = function(control: any /** TODO #9100 */) {
@ -412,36 +385,36 @@ export function main() {
controlDir.form = control;
});
it("should reexport control properties", () => { checkProperties(control); });
it('should reexport control properties', () => { checkProperties(control); });
it("should reexport new control properties", () => {
it('should reexport new control properties', () => {
var newControl = new Control(null);
controlDir.form = newControl;
controlDir.ngOnChanges({"form": new SimpleChange(control, newControl)});
controlDir.ngOnChanges({'form': new SimpleChange(control, newControl)});
checkProperties(newControl);
});
it("should set up validator", () => {
it('should set up validator', () => {
expect(control.valid).toBe(true);
// this will add the required validator and recalculate the validity
controlDir.ngOnChanges({"form": new SimpleChange(null, control)});
controlDir.ngOnChanges({'form': new SimpleChange(null, control)});
expect(control.valid).toBe(false);
});
});
describe("NgModel", () => {
describe('NgModel', () => {
var ngModel: any /** TODO #9100 */;
beforeEach(() => {
ngModel =
new NgModel([Validators.required], [asyncValidator("expected")], [defaultAccessor]);
new NgModel([Validators.required], [asyncValidator('expected')], [defaultAccessor]);
ngModel.valueAccessor = new DummyControlValueAccessor();
});
it("should reexport control properties", () => {
it('should reexport control properties', () => {
var control = ngModel.control;
expect(ngModel.control).toBe(control);
expect(ngModel.value).toBe(control.value);
@ -453,34 +426,34 @@ export function main() {
expect(ngModel.untouched).toBe(control.untouched);
});
it("should set up validator", fakeAsync(() => {
it('should set up validator', fakeAsync(() => {
// this will add the required validator and recalculate the validity
ngModel.ngOnChanges({});
tick();
expect(ngModel.control.errors).toEqual({"required": true});
expect(ngModel.control.errors).toEqual({'required': true});
ngModel.control.updateValue("someValue");
ngModel.control.updateValue('someValue');
tick();
expect(ngModel.control.errors).toEqual({"async": true});
expect(ngModel.control.errors).toEqual({'async': true});
}));
});
describe("NgControlName", () => {
describe('NgControlName', () => {
var formModel: any /** TODO #9100 */;
var controlNameDir: any /** TODO #9100 */;
beforeEach(() => {
formModel = new Control("name");
formModel = new Control('name');
var parent = new NgFormModel([], []);
parent.form = new ControlGroup({"name": formModel});
parent.form = new ControlGroup({'name': formModel});
controlNameDir = new NgControlName(parent, [], [], [defaultAccessor]);
controlNameDir.name = "name";
controlNameDir.name = 'name';
});
it("should reexport control properties", () => {
it('should reexport control properties', () => {
expect(controlNameDir.control).toBe(formModel);
expect(controlNameDir.value).toBe(formModel.value);
expect(controlNameDir.valid).toBe(formModel.valid);

View File

@ -1,67 +1,59 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach
} from '@angular/core/testing/testing_internal';
import {Control, FormBuilder} from '@angular/common';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {PromiseWrapper} from '../../src/facade/promise';
export function main() {
function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ { return null; }
function asyncValidator(_: any /** TODO #9100 */) { return PromiseWrapper.resolve(null); }
describe("Form Builder", () => {
describe('Form Builder', () => {
var b: any /** TODO #9100 */;
beforeEach(() => { b = new FormBuilder(); });
it("should create controls from a value", () => {
var g = b.group({"login": "some value"});
it('should create controls from a value', () => {
var g = b.group({'login': 'some value'});
expect(g.controls["login"].value).toEqual("some value");
expect(g.controls['login'].value).toEqual('some value');
});
it("should create controls from an array", () => {
it('should create controls from an array', () => {
var g = b.group(
{"login": ["some value"], "password": ["some value", syncValidator, asyncValidator]});
{'login': ['some value'], 'password': ['some value', syncValidator, asyncValidator]});
expect(g.controls["login"].value).toEqual("some value");
expect(g.controls["password"].value).toEqual("some value");
expect(g.controls["password"].validator).toEqual(syncValidator);
expect(g.controls["password"].asyncValidator).toEqual(asyncValidator);
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['password'].value).toEqual('some value');
expect(g.controls['password'].validator).toEqual(syncValidator);
expect(g.controls['password'].asyncValidator).toEqual(asyncValidator);
});
it("should use controls", () => {
var g = b.group({"login": b.control("some value", syncValidator, asyncValidator)});
it('should use controls', () => {
var g = b.group({'login': b.control('some value', syncValidator, asyncValidator)});
expect(g.controls["login"].value).toEqual("some value");
expect(g.controls["login"].validator).toBe(syncValidator);
expect(g.controls["login"].asyncValidator).toBe(asyncValidator);
expect(g.controls['login'].value).toEqual('some value');
expect(g.controls['login'].validator).toBe(syncValidator);
expect(g.controls['login'].asyncValidator).toBe(asyncValidator);
});
it("should create groups with optional controls", () => {
var g = b.group({"login": "some value"}, {"optionals": {"login": false}});
it('should create groups with optional controls', () => {
var g = b.group({'login': 'some value'}, {'optionals': {'login': false}});
expect(g.contains("login")).toEqual(false);
expect(g.contains('login')).toEqual(false);
});
it("should create groups with a custom validator", () => {
var g = b.group({"login": "some value"},
{"validator": syncValidator, "asyncValidator": asyncValidator});
it('should create groups with a custom validator', () => {
var g = b.group(
{'login': 'some value'}, {'validator': syncValidator, 'asyncValidator': asyncValidator});
expect(g.validator).toBe(syncValidator);
expect(g.asyncValidator).toBe(asyncValidator);
});
it("should create control arrays", () => {
var c = b.control("three");
var a = b.array(["one", ["two", syncValidator], c, b.array(['four'])], syncValidator,
asyncValidator);
it('should create control arrays', () => {
var c = b.control('three');
var a = b.array(
['one', ['two', syncValidator], c, b.array(['four'])], syncValidator, asyncValidator);
expect(a.value).toEqual(['one', 'two', 'three', ['four']]);
expect(a.validator).toBe(syncValidator);

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,17 +1,9 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach
} from '@angular/core/testing/testing_internal';
import {fakeAsync, flushMicrotasks, Log, tick} from '@angular/core/testing';
import {ControlGroup, Control, Validators, AbstractControl, ControlArray} from '@angular/common';
import {PromiseWrapper} from '../../src/facade/promise';
import {AbstractControl, Control, ControlArray, ControlGroup, Validators} from '@angular/common';
import {Log, fakeAsync, flushMicrotasks, tick} from '@angular/core/testing';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {EventEmitter, ObservableWrapper, TimerWrapper} from '../../src/facade/async';
import {PromiseWrapper} from '../../src/facade/promise';
export function main() {
function validator(key: string, error: any) {
@ -22,95 +14,98 @@ export function main() {
}
}
describe("Validators", () => {
describe("required", () => {
it("should error on an empty string",
() => { expect(Validators.required(new Control(""))).toEqual({"required": true}); });
describe('Validators', () => {
describe('required', () => {
it('should error on an empty string',
() => { expect(Validators.required(new Control(''))).toEqual({'required': true}); });
it("should error on null",
() => { expect(Validators.required(new Control(null))).toEqual({"required": true}); });
it('should error on null',
() => { expect(Validators.required(new Control(null))).toEqual({'required': true}); });
it("should not error on a non-empty string",
() => { expect(Validators.required(new Control("not empty"))).toEqual(null); });
it('should not error on a non-empty string',
() => { expect(Validators.required(new Control('not empty'))).toEqual(null); });
it("should accept zero as valid",
it('should accept zero as valid',
() => { expect(Validators.required(new Control(0))).toEqual(null); });
});
describe("minLength", () => {
it("should not error on an empty string",
() => { expect(Validators.minLength(2)(new Control(""))).toEqual(null); });
describe('minLength', () => {
it('should not error on an empty string',
() => { expect(Validators.minLength(2)(new Control(''))).toEqual(null); });
it("should not error on null",
it('should not error on null',
() => { expect(Validators.minLength(2)(new Control(null))).toEqual(null); });
it("should not error on valid strings",
() => { expect(Validators.minLength(2)(new Control("aa"))).toEqual(null); });
it('should not error on valid strings',
() => { expect(Validators.minLength(2)(new Control('aa'))).toEqual(null); });
it("should error on short strings", () => {
expect(Validators.minLength(2)(new Control("a")))
.toEqual({"minlength": {"requiredLength": 2, "actualLength": 1}});
it('should error on short strings', () => {
expect(Validators.minLength(2)(new Control('a'))).toEqual({
'minlength': {'requiredLength': 2, 'actualLength': 1}
});
});
});
describe("maxLength", () => {
it("should not error on an empty string",
() => { expect(Validators.maxLength(2)(new Control(""))).toEqual(null); });
describe('maxLength', () => {
it('should not error on an empty string',
() => { expect(Validators.maxLength(2)(new Control(''))).toEqual(null); });
it("should not error on null",
it('should not error on null',
() => { expect(Validators.maxLength(2)(new Control(null))).toEqual(null); });
it("should not error on valid strings",
() => { expect(Validators.maxLength(2)(new Control("aa"))).toEqual(null); });
it('should not error on valid strings',
() => { expect(Validators.maxLength(2)(new Control('aa'))).toEqual(null); });
it("should error on long strings", () => {
expect(Validators.maxLength(2)(new Control("aaa")))
.toEqual({"maxlength": {"requiredLength": 2, "actualLength": 3}});
it('should error on long strings', () => {
expect(Validators.maxLength(2)(new Control('aaa'))).toEqual({
'maxlength': {'requiredLength': 2, 'actualLength': 3}
});
});
});
describe("pattern", () => {
it("should not error on an empty string",
() => { expect(Validators.pattern("[a-zA-Z ]*")(new Control(""))).toEqual(null); });
describe('pattern', () => {
it('should not error on an empty string',
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control(''))).toEqual(null); });
it("should not error on null",
() => { expect(Validators.pattern("[a-zA-Z ]*")(new Control(null))).toEqual(null); });
it('should not error on null',
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control(null))).toEqual(null); });
it("should not error on valid strings",
() => { expect(Validators.pattern("[a-zA-Z ]*")(new Control("aaAA"))).toEqual(null); });
it('should not error on valid strings',
() => { expect(Validators.pattern('[a-zA-Z ]*')(new Control('aaAA'))).toEqual(null); });
it("should error on failure to match string", () => {
expect(Validators.pattern("[a-zA-Z ]*")(new Control("aaa0")))
.toEqual({"pattern": {"requiredPattern": "^[a-zA-Z ]*$", "actualValue": "aaa0"}});
it('should error on failure to match string', () => {
expect(Validators.pattern('[a-zA-Z ]*')(new Control('aaa0'))).toEqual({
'pattern': {'requiredPattern': '^[a-zA-Z ]*$', 'actualValue': 'aaa0'}
});
});
});
describe("compose", () => {
it("should return null when given null",
describe('compose', () => {
it('should return null when given null',
() => { expect(Validators.compose(null)).toBe(null); });
it("should collect errors from all the validators", () => {
var c = Validators.compose([validator("a", true), validator("b", true)]);
expect(c(new Control(""))).toEqual({"a": true, "b": true});
it('should collect errors from all the validators', () => {
var c = Validators.compose([validator('a', true), validator('b', true)]);
expect(c(new Control(''))).toEqual({'a': true, 'b': true});
});
it("should run validators left to right", () => {
var c = Validators.compose([validator("a", 1), validator("a", 2)]);
expect(c(new Control(""))).toEqual({"a": 2});
it('should run validators left to right', () => {
var c = Validators.compose([validator('a', 1), validator('a', 2)]);
expect(c(new Control(''))).toEqual({'a': 2});
});
it("should return null when no errors", () => {
it('should return null when no errors', () => {
var c = Validators.compose([Validators.nullValidator, Validators.nullValidator]);
expect(c(new Control(""))).toEqual(null);
expect(c(new Control(''))).toEqual(null);
});
it("should ignore nulls", () => {
it('should ignore nulls', () => {
var c = Validators.compose([null, Validators.required]);
expect(c(new Control(""))).toEqual({"required": true});
expect(c(new Control(''))).toEqual({'required': true});
});
});
describe("composeAsync", () => {
describe('composeAsync', () => {
function asyncValidator(expected: any /** TODO #9100 */, response: any /** TODO #9100 */) {
return (c: any /** TODO #9100 */) => {
var emitter = new EventEmitter();
@ -127,43 +122,42 @@ export function main() {
};
}
it("should return null when given null",
it('should return null when given null',
() => { expect(Validators.composeAsync(null)).toEqual(null); });
it("should collect errors from all the validators", fakeAsync(() => {
it('should collect errors from all the validators', fakeAsync(() => {
var c = Validators.composeAsync([
asyncValidator("expected", {"one": true}),
asyncValidator("expected", {"two": true})
asyncValidator('expected', {'one': true}), asyncValidator('expected', {'two': true})
]);
var value: any /** TODO #9100 */ = null;
(<Promise<any>>c(new Control("invalid"))).then(v => value = v);
(<Promise<any>>c(new Control('invalid'))).then(v => value = v);
tick(1);
expect(value).toEqual({"one": true, "two": true});
expect(value).toEqual({'one': true, 'two': true});
}));
it("should return null when no errors", fakeAsync(() => {
var c = Validators.composeAsync([asyncValidator("expected", {"one": true})]);
it('should return null when no errors', fakeAsync(() => {
var c = Validators.composeAsync([asyncValidator('expected', {'one': true})]);
var value: any /** TODO #9100 */ = null;
(<Promise<any>>c(new Control("expected"))).then(v => value = v);
(<Promise<any>>c(new Control('expected'))).then(v => value = v);
tick(1);
expect(value).toEqual(null);
}));
it("should ignore nulls", fakeAsync(() => {
var c = Validators.composeAsync([asyncValidator("expected", {"one": true}), null]);
it('should ignore nulls', fakeAsync(() => {
var c = Validators.composeAsync([asyncValidator('expected', {'one': true}), null]);
var value: any /** TODO #9100 */ = null;
(<Promise<any>>c(new Control("invalid"))).then(v => value = v);
(<Promise<any>>c(new Control('invalid'))).then(v => value = v);
tick(1);
expect(value).toEqual({"one": true});
expect(value).toEqual({'one': true});
}));
});
});

View File

@ -1,31 +1,16 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach,
inject,
} from '@angular/core/testing/testing_internal';
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal';
import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {SpyChangeDetectorRef} from '../spies';
import {isBlank} from '../../src/facade/lang';
import {AsyncPipe} from '@angular/common';
import {WrappedValue} from '@angular/core';
import {
EventEmitter,
ObservableWrapper,
PromiseWrapper,
TimerWrapper
} from '../../src/facade/async';
import {EventEmitter, ObservableWrapper, PromiseWrapper, TimerWrapper} from '../../src/facade/async';
import {getDOM} from '@angular/platform-browser/src/dom/dom_adapter';
import {PromiseCompleter} from '../../src/facade/promise';
import {browserDetection} from '@angular/platform-browser/testing';
export function main() {
describe("AsyncPipe", () => {
describe('AsyncPipe', () => {
describe('Observable', () => {
var emitter: any /** TODO #9100 */;
@ -39,11 +24,11 @@ export function main() {
pipe = new AsyncPipe(ref);
});
describe("transform", () => {
it("should return null when subscribing to an observable",
describe('transform', () => {
it('should return null when subscribing to an observable',
() => { expect(pipe.transform(emitter)).toBe(null); });
it("should return the latest available value wrapped",
it('should return the latest available value wrapped',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter);
@ -56,7 +41,7 @@ export function main() {
}));
it("should return same value when nothing has changed since the last call",
it('should return same value when nothing has changed since the last call',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter);
ObservableWrapper.callEmit(emitter, message);
@ -68,7 +53,7 @@ export function main() {
}, 0)
}));
it("should dispose of the existing subscription when subscribing to a new observable",
it('should dispose of the existing subscription when subscribing to a new observable',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter);
@ -84,7 +69,7 @@ export function main() {
}, 0)
}));
it("should request a change detection check upon receiving a new value",
it('should request a change detection check upon receiving a new value',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter);
ObservableWrapper.callEmit(emitter, message);
@ -96,11 +81,12 @@ export function main() {
}));
});
describe("ngOnDestroy", () => {
it("should do nothing when no subscription",
describe('ngOnDestroy', () => {
it('should do nothing when no subscription',
() => { expect(() => pipe.ngOnDestroy()).not.toThrow(); });
it("should dispose of the existing subscription", inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
it('should dispose of the existing subscription',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter);
pipe.ngOnDestroy();
@ -114,7 +100,7 @@ export function main() {
});
});
describe("Promise", () => {
describe('Promise', () => {
var message = new Object();
var pipe: AsyncPipe;
var completer: PromiseCompleter<any>;
@ -128,11 +114,12 @@ export function main() {
pipe = new AsyncPipe(<any>ref);
});
describe("transform", () => {
it("should return null when subscribing to a promise",
describe('transform', () => {
it('should return null when subscribing to a promise',
() => { expect(pipe.transform(completer.promise)).toBe(null); });
it("should return the latest available value", inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
it('should return the latest available value',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(completer.promise);
completer.resolve(message);
@ -143,7 +130,7 @@ export function main() {
}, timer)
}));
it("should return unwrapped value when nothing has changed since the last call",
it('should return unwrapped value when nothing has changed since the last call',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(completer.promise);
completer.resolve(message);
@ -155,7 +142,7 @@ export function main() {
}, timer)
}));
it("should dispose of the existing subscription when subscribing to a new promise",
it('should dispose of the existing subscription when subscribing to a new promise',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(completer.promise);
@ -171,7 +158,7 @@ export function main() {
}, timer)
}));
it("should request a change detection check upon receiving a new value",
it('should request a change detection check upon receiving a new value',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var markForCheck = ref.spy('markForCheck');
pipe.transform(completer.promise);
@ -183,11 +170,12 @@ export function main() {
}, timer)
}));
describe("ngOnDestroy", () => {
it("should do nothing when no source",
describe('ngOnDestroy', () => {
it('should do nothing when no source',
() => { expect(() => pipe.ngOnDestroy()).not.toThrow(); });
it("should dispose of the existing source", inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
it('should dispose of the existing source',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(completer.promise);
expect(pipe.transform(completer.promise)).toBe(null);
completer.resolve(message)
@ -214,7 +202,7 @@ export function main() {
describe('other types', () => {
it('should throw when given an invalid object', () => {
var pipe = new AsyncPipe(null);
expect(() => pipe.transform(<any>"some bogus object")).toThrowError();
expect(() => pipe.transform(<any>'some bogus object')).toThrowError();
});
});
});

View File

@ -1,21 +1,12 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach
} from '@angular/core/testing/testing_internal';
import {DatePipe} from '@angular/common';
import {PipeResolver} from '@angular/compiler/src/pipe_resolver';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
import {browserDetection} from '@angular/platform-browser/testing';
import {DatePipe} from '@angular/common';
import {DateWrapper} from '../../src/facade/lang';
import {PipeResolver} from '@angular/compiler/src/pipe_resolver';
export function main() {
describe("DatePipe", () => {
describe('DatePipe', () => {
var date: any /** TODO #9100 */;
var pipe: any /** TODO #9100 */;
@ -27,23 +18,23 @@ export function main() {
it('should be marked as pure',
() => { expect(new PipeResolver().resolve(DatePipe).pure).toEqual(true); });
describe("supports", () => {
it("should support date", () => { expect(pipe.supports(date)).toBe(true); });
it("should support int", () => { expect(pipe.supports(123456789)).toBe(true); });
it("should support ISO string",
() => { expect(pipe.supports("2015-06-15T21:43:11Z")).toBe(true); });
describe('supports', () => {
it('should support date', () => { expect(pipe.supports(date)).toBe(true); });
it('should support int', () => { expect(pipe.supports(123456789)).toBe(true); });
it('should support ISO string',
() => { expect(pipe.supports('2015-06-15T21:43:11Z')).toBe(true); });
it("should not support other objects", () => {
it('should not support other objects', () => {
expect(pipe.supports(new Object())).toBe(false);
expect(pipe.supports(null)).toBe(false);
expect(pipe.supports("")).toBe(false);
expect(pipe.supports('')).toBe(false);
});
});
// TODO(mlaval): enable tests when Intl API is no longer used, see
// https://github.com/angular/angular/issues/3333
if (browserDetection.supportsIntlApi) {
describe("transform", () => {
describe('transform', () => {
it('should format each component correctly', () => {
expect(pipe.transform(date, 'y')).toEqual('2015');
expect(pipe.transform(date, 'yy')).toEqual('15');

View File

@ -1,57 +1,50 @@
import {
ddescribe,
describe,
it,
iit,
xit,
expect,
beforeEach,
afterEach
} from '@angular/core/testing/testing_internal';
import {I18nPluralPipe} from '@angular/common';
import {PipeResolver} from '@angular/compiler/src/pipe_resolver';
import {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_internal';
export function main() {
describe("I18nPluralPipe", () => {
describe('I18nPluralPipe', () => {
var pipe: any /** TODO #9100 */;
var mapping = {'=0': 'No messages.', '=1': 'One message.', 'other': 'There are some messages.'};
var interpolatedMapping =
{'=0': 'No messages.', '=1': 'One message.', 'other': 'There are # messages, that is #.'};
var interpolatedMapping = {
'=0': 'No messages.',
'=1': 'One message.',
'other': 'There are # messages, that is #.'
};
beforeEach(() => { pipe = new I18nPluralPipe(); });
it('should be marked as pure',
() => { expect(new PipeResolver().resolve(I18nPluralPipe).pure).toEqual(true); });
describe("transform", () => {
it("should return 0 text if value is 0", () => {
describe('transform', () => {
it('should return 0 text if value is 0', () => {
var val = pipe.transform(0, mapping);
expect(val).toEqual('No messages.');
});
it("should return 1 text if value is 1", () => {
it('should return 1 text if value is 1', () => {
var val = pipe.transform(1, mapping);
expect(val).toEqual('One message.');
});
it("should return other text if value is anything other than 0 or 1", () => {
it('should return other text if value is anything other than 0 or 1', () => {
var val = pipe.transform(6, mapping);
expect(val).toEqual('There are some messages.');
});
it("should interpolate the value into the text where indicated", () => {
it('should interpolate the value into the text where indicated', () => {
var val = pipe.transform(6, interpolatedMapping);
expect(val).toEqual('There are 6 messages, that is 6.');
});
it("should use 'other' if value is undefined", () => {
it('should use \'other\' if value is undefined', () => {
var messageLength: any /** TODO #9100 */;
var val = pipe.transform(messageLength, interpolatedMapping);
expect(val).toEqual('There are messages, that is .');
});
it("should not support bad arguments",
it('should not support bad arguments',
() => { expect(() => pipe.transform(0, 'hey')).toThrowError(); });
});

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