refactor(ViewBuilder): cleanup

This commit is contained in:
Victor Berchet 2016-06-14 14:53:01 -07:00
parent 0dbff55bc6
commit 8a54c1a115
10 changed files with 187 additions and 242 deletions

View File

@ -1089,7 +1089,7 @@ export function main() {
fixture.debugElement.componentInstance.name = null;
fixture.detectChanges();
var form = fixture.debugElement.children[0].inject(NgForm);
var form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.controls['user']).not.toBeDefined();
tick();
@ -1142,7 +1142,7 @@ export function main() {
fixture.debugElement.componentInstance.name = 'show';
fixture.detectChanges();
tick();
var form = fixture.debugElement.children[0].inject(NgForm);
var form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.controls['login']).toBeDefined();
@ -1168,7 +1168,7 @@ export function main() {
fixture.debugElement.componentInstance.name = 'show';
fixture.detectChanges();
tick();
var form = fixture.debugElement.children[0].inject(NgForm);
var form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.controls['user']).toBeDefined();

View File

@ -154,7 +154,7 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
visitElement(ast: ElementAst, parent: CompileElement): any {
var nodeIndex = this.view.nodes.length;
var createRenderNodeExpr: any /** TODO #9100 */;
var createRenderNodeExpr: o.InvokeMethodExpr;
var debugContextExpr = this.view.createMethod.resetDebugInfoExpr(nodeIndex, ast);
if (nodeIndex === 0 && this.view.viewType === ViewType.HOST) {
createRenderNodeExpr = o.THIS_EXPR.callMethod(
@ -213,7 +213,7 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
compileElement.afterChildren(this.view.nodes.length - nodeIndex - 1);
if (isPresent(compViewExpr)) {
var codeGenContentNodes: any /** TODO #9100 */;
var codeGenContentNodes: o.Expression;
if (this.view.component.type.isHost) {
codeGenContentNodes = ViewProperties.projectableNodes;
} else {
@ -327,15 +327,12 @@ function _mergeHtmlAndDirectiveAttrs(
directives: CompileDirectiveMetadata[]): string[][] {
var result: {[key: string]: string} = {};
StringMapWrapper.forEach(
declaredHtmlAttrs,
(value: any /** TODO #9100 */, key: any /** TODO #9100 */) => { result[key] = value; });
declaredHtmlAttrs, (value: string, key: string) => { result[key] = value; });
directives.forEach(directiveMeta => {
StringMapWrapper.forEach(
directiveMeta.hostAttributes,
(value: any /** TODO #9100 */, name: any /** TODO #9100 */) => {
var prevValue = result[name];
result[name] = isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value;
});
StringMapWrapper.forEach(directiveMeta.hostAttributes, (value: string, name: string) => {
var prevValue = result[name];
result[name] = isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value;
});
});
return mapToKeyValueArray(result);
}
@ -355,16 +352,14 @@ function mergeAttributeValue(attrName: string, attrValue1: string, attrValue2: s
}
function mapToKeyValueArray(data: {[key: string]: string}): string[][] {
var entryArray: any[] /** TODO #9100 */ = [];
StringMapWrapper.forEach(data, (value: any /** TODO #9100 */, name: any /** TODO #9100 */) => {
var entryArray: string[][] = [];
StringMapWrapper.forEach(data, (value: string, name: string) => {
entryArray.push([name, value]);
});
// We need to sort to get a defined output order
// for tests and for caching generated artifacts...
ListWrapper.sort(entryArray, (entry1, entry2) => StringWrapper.compare(entry1[0], entry2[0]));
var keyValueArray: any[] /** TODO #9100 */ = [];
entryArray.forEach((entry) => { keyValueArray.push([entry[0], entry[1]]); });
return keyValueArray;
return entryArray;
}
function createViewTopLevelStmts(view: CompileView, targetStatements: o.Statement[]) {
@ -398,15 +393,14 @@ function createStaticNodeDebugInfo(node: CompileNode): o.Expression {
var compileElement = node instanceof CompileElement ? node : null;
var providerTokens: o.Expression[] = [];
var componentToken: o.Expression = o.NULL_EXPR;
var varTokenEntries: any[] /** TODO #9100 */ = [];
var varTokenEntries: any[] = [];
if (isPresent(compileElement)) {
providerTokens = compileElement.getProviderTokens();
if (isPresent(compileElement.component)) {
componentToken = createDiTokenExpression(identifierToken(compileElement.component.type));
}
StringMapWrapper.forEach(
compileElement.referenceTokens,
(token: any /** TODO #9100 */, varName: any /** TODO #9100 */) => {
compileElement.referenceTokens, (token: CompileTokenMetadata, varName: string) => {
varTokenEntries.push(
[varName, isPresent(token) ? createDiTokenExpression(token) : o.NULL_EXPR]);
});
@ -476,8 +470,8 @@ function createViewFactory(
new o.FnParam(ViewConstructorVars.parentInjector.name, o.importType(Identifiers.Injector)),
new o.FnParam(ViewConstructorVars.declarationEl.name, o.importType(Identifiers.AppElement))
];
var initRenderCompTypeStmts: any[] /** TODO #9100 */ = [];
var templateUrlInfo: any /** TODO #9100 */;
var initRenderCompTypeStmts: any[] = [];
var templateUrlInfo: string;
if (view.component.template.templateUrl == view.component.type.moduleUrl) {
templateUrlInfo =
`${view.component.type.moduleUrl} class ${view.component.type.name} - inline template`;
@ -508,7 +502,7 @@ function createViewFactory(
function generateCreateMethod(view: CompileView): o.Statement[] {
var parentRenderNodeExpr: o.Expression = o.NULL_EXPR;
var parentRenderNodeStmts: any[] /** TODO #9100 */ = [];
var parentRenderNodeStmts: any[] = [];
if (view.viewType === ViewType.COMPONENT) {
parentRenderNodeExpr = ViewProperties.renderer.callMethod(
'createViewRoot', [o.THIS_EXPR.prop('declarationAppElement').prop('nativeElement')]);
@ -523,7 +517,7 @@ function generateCreateMethod(view: CompileView): o.Statement[] {
} else {
resultExpr = o.NULL_EXPR;
}
return parentRenderNodeStmts.concat(view.createMethod.finish()).concat([
return parentRenderNodeStmts.concat(view.createMethod.finish(), [
o.THIS_EXPR
.callMethod(
'init',
@ -538,7 +532,7 @@ function generateCreateMethod(view: CompileView): o.Statement[] {
}
function generateDetectChangesMethod(view: CompileView): o.Statement[] {
var stmts: any[] /** TODO #9100 */ = [];
var stmts: any[] = [];
if (view.detectChangesInInputsMethod.isEmpty() && view.updateContentQueriesMethod.isEmpty() &&
view.afterContentLifecycleCallbacksMethod.isEmpty() &&
view.detectChangesRenderPropertiesMethod.isEmpty() &&
@ -563,7 +557,7 @@ function generateDetectChangesMethod(view: CompileView): o.Statement[] {
stmts.push(new o.IfStmt(o.not(DetectChangesVars.throwOnChange), afterViewStmts));
}
var varStmts: any[] /** TODO #9100 */ = [];
var varStmts: any[] = [];
var readVars = o.findReadVarNames(stmts);
if (SetWrapper.has(readVars, DetectChangesVars.changed.name)) {
varStmts.push(DetectChangesVars.changed.set(o.literal(true)).toDeclStmt(o.BOOL_TYPE));

View File

@ -22,7 +22,6 @@ class Logger {
}
@Directive({selector: '[message]', inputs: ['message']})
@Injectable()
class MessageDir {
logger: Logger;
@ -39,7 +38,6 @@ class MessageDir {
<span class="child" [innerHtml]="childBinding"></span>`,
directives: [MessageDir],
})
@Injectable()
class ChildComp {
childBinding: string;
@ -56,14 +54,12 @@ class ChildComp {
<child-comp class="child-comp-class"></child-comp>`,
directives: [ChildComp, MessageDir],
})
@Injectable()
class ParentComp {
parentBinding: string;
constructor() { this.parentBinding = 'OriginalParent'; }
}
@Directive({selector: 'custom-emitter', outputs: ['myevent']})
@Injectable()
class CustomEmitter {
myevent: EventEmitter<any>;
@ -76,7 +72,6 @@ class CustomEmitter {
<custom-emitter (myevent)="handleCustom()"></custom-emitter>`,
directives: [CustomEmitter],
})
@Injectable()
class EventsComp {
clicked: boolean;
customed: boolean;
@ -97,7 +92,6 @@ class EventsComp {
template: `<div class="child" message="child" *ngIf="myBool"><ng-content></ng-content></div>`,
directives: [NgIf, MessageDir],
})
@Injectable()
class ConditionalContentComp {
myBool: boolean = false;
}
@ -111,7 +105,6 @@ class ConditionalContentComp {
</cond-content-comp>`,
directives: [ConditionalContentComp],
})
@Injectable()
class ConditionalParentComp {
parentBinding: string;
constructor() { this.parentBinding = 'OriginalParent'; }
@ -126,7 +119,6 @@ class ConditionalParentComp {
</ul>`,
directives: [NgFor, MessageDir],
})
@Injectable()
class UsingFor {
stuff: string[];
constructor() { this.stuff = ['one', 'two', 'three']; }
@ -387,9 +379,8 @@ export function main() {
tcb.createAsync(ParentComp).then((fixture) => {
fixture.detectChanges();
expect((<Logger>(fixture.debugElement.children[0].inject(Logger))).logs).toEqual([
'parent', 'nestedparent', 'child', 'nestedchild'
]);
expect((<Logger>(fixture.debugElement.children[0].injector.get(Logger))).logs)
.toEqual(['parent', 'nestedparent', 'child', 'nestedchild']);
async.done();
});

View File

@ -48,7 +48,7 @@ export function main() {
function queryDirs(el: DebugElement, dirType: Type): any {
var nodes = el.queryAllNodes(By.directive(dirType));
return nodes.map(node => node.inject(dirType));
return nodes.map(node => node.injector.get(dirType));
}
function _bindSimpleProp(

View File

@ -288,11 +288,13 @@ function declareTests({useJit}: {useJit: boolean}) {
var containerSpan = fixture.debugElement.children[0];
expect(containerSpan.children[0].inject(MyDir).dirProp)
expect(containerSpan.children[0].injector.get(MyDir).dirProp)
.toEqual('Hello World!');
expect(containerSpan.children[1].inject(MyDir).dirProp).toEqual('Hi there!');
expect(containerSpan.children[2].inject(MyDir).dirProp).toEqual('Hi there!');
expect(containerSpan.children[3].inject(MyDir).dirProp)
expect(containerSpan.children[1].injector.get(MyDir).dirProp)
.toEqual('Hi there!');
expect(containerSpan.children[2].injector.get(MyDir).dirProp)
.toEqual('Hi there!');
expect(containerSpan.children[3].injector.get(MyDir).dirProp)
.toEqual('One more Hello World!');
async.done();
});
@ -358,8 +360,8 @@ function declareTests({useJit}: {useJit: boolean}) {
var tc = fixture.debugElement.children[0];
expect(tc.inject(MyDir).dirProp).toEqual('Hello World!');
expect(tc.inject(ChildComp).dirProp).toEqual(null);
expect(tc.injector.get(MyDir).dirProp).toEqual('Hello World!');
expect(tc.injector.get(ChildComp).dirProp).toEqual(null);
async.done();
});
@ -406,7 +408,7 @@ function declareTests({useJit}: {useJit: boolean}) {
.createAsync(MyComp)
.then((fixture) => {
var tc = fixture.debugElement.children[0];
var idDir = tc.inject(IdDir);
var idDir = tc.injector.get(IdDir);
fixture.debugElement.componentInstance.ctxProp = 'some_id';
fixture.detectChanges();
@ -432,7 +434,7 @@ function declareTests({useJit}: {useJit: boolean}) {
.createAsync(MyComp)
.then((fixture) => {
var tc = fixture.debugElement.children[0];
expect(tc.inject(EventDir)).not.toBe(null);
expect(tc.injector.get(EventDir)).not.toBe(null);
async.done();
});
}));
@ -493,7 +495,8 @@ function declareTests({useJit}: {useJit: boolean}) {
fixture.detectChanges();
var ngIfEl = fixture.debugElement.children[0];
var someViewport: SomeViewport = ngIfEl.childNodes[0].inject(SomeViewport);
var someViewport: SomeViewport =
ngIfEl.childNodes[0].injector.get(SomeViewport);
expect(someViewport.container.length).toBe(2);
expect(ngIfEl.children.length).toBe(2);
@ -816,8 +819,8 @@ function declareTests({useJit}: {useJit: boolean}) {
fixture.detectChanges();
var cmpEl = fixture.debugElement.children[0];
var cmp: PushCmpWithHostEvent = cmpEl.inject(PushCmpWithHostEvent);
cmp.ctxCallback = (_: any /** TODO #9100 */) => fixture.destroy();
var cmp: PushCmpWithHostEvent = cmpEl.injector.get(PushCmpWithHostEvent);
cmp.ctxCallback = (_: any) => fixture.destroy();
expect(() => cmpEl.triggerEventHandler('click', <Event>{})).not.toThrow();
})));
@ -987,8 +990,8 @@ function declareTests({useJit}: {useJit: boolean}) {
.then((fixture) => {
var tc = fixture.debugElement.children[0];
var emitter = tc.inject(DirectiveEmittingEvent);
var listener = tc.inject(DirectiveListeningEvent);
var emitter = tc.injector.get(DirectiveEmittingEvent);
var listener = tc.injector.get(DirectiveListeningEvent);
expect(listener.msg).toEqual('');
var eventCount = 0;
@ -1025,9 +1028,9 @@ function declareTests({useJit}: {useJit: boolean}) {
var tc = fixture.debugElement.childNodes[0];
var emitter = tc.inject(DirectiveEmittingEvent);
var myComp = fixture.debugElement.inject(MyComp);
var listener = tc.inject(DirectiveListeningEvent);
var emitter = tc.injector.get(DirectiveEmittingEvent);
var myComp = fixture.debugElement.injector.get(MyComp);
var listener = tc.injector.get(DirectiveListeningEvent);
myComp.ctxProp = '';
expect(listener.msg).toEqual('');
@ -1054,7 +1057,7 @@ function declareTests({useJit}: {useJit: boolean}) {
.createAsync(MyComp)
.then((fixture) => {
var tc = fixture.debugElement.children[0];
var dir = tc.inject(DirectiveWithTwoWayBinding);
var dir = tc.injector.get(DirectiveWithTwoWayBinding);
fixture.debugElement.componentInstance.ctxProp = 'one';
fixture.detectChanges();
@ -1083,7 +1086,7 @@ function declareTests({useJit}: {useJit: boolean}) {
.then((fixture) => {
var tc = fixture.debugElement.children[0];
var listener = tc.inject(DirectiveListeningDomEvent);
var listener = tc.injector.get(DirectiveListeningDomEvent);
dispatchEvent(tc.nativeElement, 'domEvent');
@ -1112,7 +1115,7 @@ function declareTests({useJit}: {useJit: boolean}) {
.createAsync(MyComp)
.then((fixture) => {
var tc = fixture.debugElement.children[0];
var listener = tc.inject(DirectiveListeningDomEvent);
var listener = tc.injector.get(DirectiveListeningDomEvent);
dispatchEvent(getDOM().getGlobalEventTarget('window'), 'domEvent');
expect(listener.eventTypes).toEqual(['window_domEvent']);
@ -1162,7 +1165,7 @@ function declareTests({useJit}: {useJit: boolean}) {
.createAsync(MyComp)
.then((fixture) => {
var tc = fixture.debugElement.children[0];
var updateHost = tc.inject(DirectiveUpdatingHostProperties);
var updateHost = tc.injector.get(DirectiveUpdatingHostProperties);
updateHost.id = 'newId';
@ -1227,8 +1230,8 @@ function declareTests({useJit}: {useJit: boolean}) {
var tc = fixture.debugElement.children[0];
var listener = tc.inject(DirectiveListeningDomEvent);
var listenerother = tc.inject(DirectiveListeningDomEventOther);
var listener = tc.injector.get(DirectiveListeningDomEvent);
var listenerother = tc.injector.get(DirectiveListeningDomEventOther);
dispatchEvent(getDOM().getGlobalEventTarget('window'), 'domEvent');
expect(listener.eventTypes).toEqual(['window_domEvent']);
expect(listenerother.eventType).toEqual('other_domEvent');
@ -1266,7 +1269,7 @@ function declareTests({useJit}: {useJit: boolean}) {
.createAsync(MyComp)
.then((fixture) => {
var tc = fixture.debugElement.children[0].children[0];
var dynamicVp: DynamicViewport = tc.inject(DynamicViewport);
var dynamicVp: DynamicViewport = tc.injector.get(DynamicViewport);
dynamicVp.done.then((_) => {
fixture.detectChanges();
expect(fixture.debugElement.children[0].children[1].nativeElement)
@ -1289,7 +1292,7 @@ function declareTests({useJit}: {useJit: boolean}) {
.createAsync(MyComp)
.then((fixture) => {
var tc = fixture.debugElement.children[0];
var needsAttribute = tc.inject(NeedsAttribute);
var needsAttribute = tc.injector.get(NeedsAttribute);
expect(needsAttribute.typeAttribute).toEqual('text');
expect(needsAttribute.staticAttribute).toEqual('');
expect(needsAttribute.fooAttribute).toEqual(null);
@ -1401,9 +1404,9 @@ function declareTests({useJit}: {useJit: boolean}) {
var parentComp = gpComp.children[0];
var childComp = parentComp.children[0];
var grandParent = gpComp.inject(GrandParentProvidingEventBus);
var parent = parentComp.inject(ParentProvidingEventBus);
var child = childComp.inject(ChildConsumingEventBus);
var grandParent = gpComp.injector.get(GrandParentProvidingEventBus);
var parent = parentComp.injector.get(ParentProvidingEventBus);
var child = childComp.injector.get(ChildConsumingEventBus);
expect(grandParent.bus.name).toEqual('grandparent');
expect(parent.bus.name).toEqual('parent');
@ -1484,12 +1487,12 @@ function declareTests({useJit}: {useJit: boolean}) {
}));
it('should report a meaningful error when a component is missing view annotation',
inject([TestComponentBuilder], (tcb: TestComponentBuilder): any /** TODO #9100 */ => {
inject([TestComponentBuilder], (tcb: TestComponentBuilder) => {
try {
tcb.createAsync(ComponentWithoutView);
expect(true).toBe(false);
} catch (e) {
expect(e.message).toContain(`must have either 'template' or 'templateUrl' set.`);
return null;
}
}));
@ -1497,7 +1500,6 @@ function declareTests({useJit}: {useJit: boolean}) {
inject(
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
tcb =
tcb.overrideView(MyComp, new ViewMetadata({directives: [[null]], template: ''}));
@ -1593,7 +1595,7 @@ function declareTests({useJit}: {useJit: boolean}) {
try {
tc.inject(DirectiveEmittingEvent).fireEvent('boom');
tc.injector.get(DirectiveEmittingEvent).fireEvent('boom');
} catch (e) {
clearPendingTimers();
@ -1613,7 +1615,7 @@ function declareTests({useJit}: {useJit: boolean}) {
[TestComponentBuilder, AsyncTestCompleter],
(tcb: TestComponentBuilder, async: AsyncTestCompleter) => {
var undefinedValue: any /** TODO #9100 */;
var undefinedValue: any = void(0);
tcb = tcb.overrideView(
MyComp, new ViewMetadata({directives: [undefinedValue], template: ''}));
@ -1688,8 +1690,7 @@ function declareTests({useJit}: {useJit: boolean}) {
it('should support moving embedded views around',
inject(
[TestComponentBuilder, AsyncTestCompleter, ANCHOR_ELEMENT],
(tcb: TestComponentBuilder, async: AsyncTestCompleter,
anchorElement: any /** TODO #9100 */) => {
(tcb: TestComponentBuilder, async: AsyncTestCompleter, anchorElement: any) => {
tcb.overrideView(MyComp, new ViewMetadata({
template: '<div><div *someImpvp="ctxBoolProp">hello</div></div>',
directives: [SomeImperativeViewport]
@ -1843,7 +1844,8 @@ function declareTests({useJit}: {useJit: boolean}) {
.createAsync(MyComp)
.then((fixture) => {
fixture.detectChanges();
var dir = fixture.debugElement.children[0].inject(DirectiveWithPropDecorators);
var dir =
fixture.debugElement.children[0].injector.get(DirectiveWithPropDecorators);
expect(dir.dirProp).toEqual('aaa');
async.done();
});
@ -1860,7 +1862,8 @@ function declareTests({useJit}: {useJit: boolean}) {
.createAsync(MyComp)
.then((fixture) => {
fixture.detectChanges();
var dir = fixture.debugElement.children[0].inject(DirectiveWithPropDecorators);
var dir =
fixture.debugElement.children[0].injector.get(DirectiveWithPropDecorators);
dir.myAttr = 'aaa';
fixture.detectChanges();
@ -1882,7 +1885,8 @@ function declareTests({useJit}: {useJit: boolean}) {
let fixture = tcb.createFakeAsync(MyComp);
tick();
var emitter = fixture.debugElement.children[0].inject(DirectiveWithPropDecorators);
var emitter =
fixture.debugElement.children[0].injector.get(DirectiveWithPropDecorators);
emitter.fireEvent('fired !');
tick();
@ -1902,8 +1906,8 @@ function declareTests({useJit}: {useJit: boolean}) {
.createAsync(MyComp)
.then((fixture) => {
fixture.detectChanges();
var dir =
fixture.debugElement.children[0].inject(DirectiveWithPropDecorators);
var dir = fixture.debugElement.children[0].injector.get(
DirectiveWithPropDecorators);
var native = fixture.debugElement.children[0].nativeElement;
getDOM().dispatchEvent(native, getDOM().createMouseEvent('click'));
@ -2026,9 +2030,8 @@ class MyService {
}
@Component({selector: 'simple-imp-cmp', template: ''})
@Injectable()
class SimpleImperativeViewComponent {
done: any /** TODO #9100 */;
done: any;
constructor(self: ElementRef, renderer: Renderer) {
var hostElement = self.nativeElement;
@ -2037,7 +2040,6 @@ class SimpleImperativeViewComponent {
}
@Directive({selector: 'dynamic-vp'})
@Injectable()
class DynamicViewport {
done: Promise<any>;
constructor(vc: ViewContainerRef, compiler: ComponentResolver) {
@ -2052,7 +2054,6 @@ class DynamicViewport {
}
@Directive({selector: '[my-dir]', inputs: ['dirProp: elprop'], exportAs: 'mydir'})
@Injectable()
class MyDir {
dirProp: string;
constructor() { this.dirProp = ''; }
@ -2081,10 +2082,9 @@ class EventCmp {
'{{field}}<div (click)="noop()"></div><div *ngIf="true" (click)="noop()"></div><event-cmp></event-cmp>',
directives: [EventCmp, NgIf]
})
@Injectable()
class PushCmp {
numberOfChecks: number;
prop: any /** TODO #9100 */;
prop: any;
constructor() { this.numberOfChecks = 0; }
@ -2102,11 +2102,10 @@ class PushCmp {
changeDetection: ChangeDetectionStrategy.OnPush,
template: '{{field}}'
})
@Injectable()
class PushCmpWithRef {
numberOfChecks: number;
ref: ChangeDetectorRef;
prop: any /** TODO #9100 */;
prop: any;
constructor(ref: ChangeDetectorRef) {
this.numberOfChecks = 0;
@ -2128,7 +2127,7 @@ class PushCmpWithRef {
template: ''
})
class PushCmpWithHostEvent {
ctxCallback: Function = (_: any /** TODO #9100 */) => {};
ctxCallback: Function = (_: any) => {};
}
@Component({
@ -2137,7 +2136,6 @@ class PushCmpWithHostEvent {
template: '{{field | async}}',
pipes: [AsyncPipe]
})
@Injectable()
class PushCmpWithAsyncPipe {
numberOfChecks: number = 0;
promise: Promise<any>;
@ -2153,11 +2151,10 @@ class PushCmpWithAsyncPipe {
return this.promise;
}
resolve(value: any /** TODO #9100 */) { this.completer.resolve(value); }
resolve(value: any) { this.completer.resolve(value); }
}
@Component({selector: 'my-comp', directives: []})
@Injectable()
class MyComp {
ctxProp: string;
ctxNumProp: number;
@ -2178,7 +2175,6 @@ class MyComp {
directives: [MyDir],
template: '{{ctxProp}}'
})
@Injectable()
class ChildComp {
ctxProp: string;
dirProp: string;
@ -2189,20 +2185,17 @@ class ChildComp {
}
@Component({selector: 'child-cmp-no-template', directives: [], template: ''})
@Injectable()
class ChildCompNoTemplate {
ctxProp: string = 'hello';
}
@Component({selector: 'child-cmp-svc', template: '{{ctxProp}}'})
@Injectable()
class ChildCompUsingService {
ctxProp: string;
constructor(service: MyService) { this.ctxProp = service.greeting; }
}
@Directive({selector: 'some-directive'})
@Injectable()
class SomeDirective {
}
@ -2213,14 +2206,12 @@ class SomeDirectiveMissingAnnotation {}
template: '<p>Component with an injected host</p>',
directives: [SomeDirective]
})
@Injectable()
class CompWithHost {
myHost: SomeDirective;
constructor(@Host() someComp: SomeDirective) { this.myHost = someComp; }
}
@Component({selector: '[child-cmp2]', viewProviders: [MyService]})
@Injectable()
class ChildComp2 {
ctxProp: string;
dirProp: string;
@ -2235,7 +2226,6 @@ class SomeViewportContext {
}
@Directive({selector: '[some-viewport]'})
@Injectable()
class SomeViewport {
constructor(public container: ViewContainerRef, templateRef: TemplateRef<SomeViewportContext>) {
container.createEmbeddedView(templateRef, new SomeViewportContext('hello'));
@ -2246,11 +2236,10 @@ class SomeViewport {
@Pipe({name: 'double'})
class DoublePipe implements PipeTransform, OnDestroy {
ngOnDestroy() {}
transform(value: any /** TODO #9100 */) { return `${value}${value}`; }
transform(value: any) { return `${value}${value}`; }
}
@Directive({selector: '[emitter]', outputs: ['event']})
@Injectable()
class DirectiveEmittingEvent {
msg: string;
event: EventEmitter<any>;
@ -2264,12 +2253,10 @@ class DirectiveEmittingEvent {
}
@Directive({selector: '[update-host-attributes]', host: {'role': 'button'}})
@Injectable()
class DirectiveUpdatingHostAttributes {
}
@Directive({selector: '[update-host-properties]', host: {'[id]': 'id'}})
@Injectable()
class DirectiveUpdatingHostProperties {
id: string;
@ -2277,7 +2264,6 @@ class DirectiveUpdatingHostProperties {
}
@Directive({selector: '[listener]', host: {'(event)': 'onEvent($event)'}})
@Injectable()
class DirectiveListeningEvent {
msg: string;
@ -2295,7 +2281,6 @@ class DirectiveListeningEvent {
'(body:domEvent)': 'onBodyEvent($event.type)'
}
})
@Injectable()
class DirectiveListeningDomEvent {
eventTypes: string[] = [];
onEvent(eventType: string) { this.eventTypes.push(eventType); }
@ -2306,7 +2291,6 @@ class DirectiveListeningDomEvent {
var globalCounter = 0;
@Directive({selector: '[listenerother]', host: {'(window:domEvent)': 'onEvent($event.type)'}})
@Injectable()
class DirectiveListeningDomEventOther {
eventType: string;
constructor() { this.eventType = ''; }
@ -2317,39 +2301,34 @@ class DirectiveListeningDomEventOther {
}
@Directive({selector: '[listenerprevent]', host: {'(click)': 'onEvent($event)'}})
@Injectable()
class DirectiveListeningDomEventPrevent {
onEvent(event: any /** TODO #9100 */) { return false; }
onEvent(event: any) { return false; }
}
@Directive({selector: '[listenernoprevent]', host: {'(click)': 'onEvent($event)'}})
@Injectable()
class DirectiveListeningDomEventNoPrevent {
onEvent(event: any /** TODO #9100 */) { return true; }
onEvent(event: any) { return true; }
}
@Directive({selector: '[id]', inputs: ['id']})
@Injectable()
class IdDir {
id: string;
}
@Directive({selector: '[customEvent]'})
@Injectable()
class EventDir {
@Output() customEvent = new EventEmitter();
doSomething() {}
}
@Directive({selector: '[static]'})
@Injectable()
class NeedsAttribute {
typeAttribute: any /** TODO #9100 */;
staticAttribute: any /** TODO #9100 */;
fooAttribute: any /** TODO #9100 */;
typeAttribute: string;
staticAttribute: string;
fooAttribute: string;
constructor(
@Attribute('type') typeAttribute: String, @Attribute('static') staticAttribute: String,
@Attribute('foo') fooAttribute: String) {
@Attribute('type') typeAttribute: string, @Attribute('static') staticAttribute: string,
@Attribute('foo') fooAttribute: string) {
this.typeAttribute = typeAttribute;
this.staticAttribute = staticAttribute;
this.fooAttribute = fooAttribute;
@ -2366,12 +2345,10 @@ class PublicApi {
/* @ts2dart_Provider */ {provide: PublicApi, useExisting: PrivateImpl, deps: []}
]
})
@Injectable()
class PrivateImpl extends PublicApi {
}
@Directive({selector: '[needs-public-api]'})
@Injectable()
class NeedsPublicApi {
constructor(@Host() api: PublicApi) { expect(api instanceof PrivateImpl).toBe(true); }
}
@ -2381,14 +2358,12 @@ class ToolbarContext {
}
@Directive({selector: '[toolbarpart]'})
@Injectable()
class ToolbarPart {
templateRef: TemplateRef<ToolbarContext>;
constructor(templateRef: TemplateRef<ToolbarContext>) { this.templateRef = templateRef; }
}
@Directive({selector: '[toolbarVc]', inputs: ['toolbarVc']})
@Injectable()
class ToolbarViewContainer {
vc: ViewContainerRef;
constructor(vc: ViewContainerRef) { this.vc = vc; }
@ -2403,7 +2378,6 @@ class ToolbarViewContainer {
template: 'TOOLBAR(<div *ngFor="let part of query" [toolbarVc]="part"></div>)',
directives: [ToolbarViewContainer, NgFor]
})
@Injectable()
class ToolbarComponent {
query: QueryList<ToolbarPart>;
ctxProp: string;
@ -2415,14 +2389,11 @@ class ToolbarComponent {
}
@Directive({selector: '[two-way]', inputs: ['control'], outputs: ['controlChange']})
@Injectable()
class DirectiveWithTwoWayBinding {
controlChange = new EventEmitter();
control: any /** TODO #9100 */ = null;
control: any = null;
triggerChange(value: any /** TODO #9100 */) {
ObservableWrapper.callEmit(this.controlChange, value);
}
triggerChange(value: any) { ObservableWrapper.callEmit(this.controlChange, value); }
}
@Injectable()
@ -2445,14 +2416,12 @@ function createInjectableWithLogging(inj: Injector) {
],
template: ''
})
@Injectable()
class ComponentProvidingLoggingInjectable {
created: boolean = false;
}
@Directive({selector: 'directive-providing-injectable', providers: [[InjectableService]]})
@Injectable()
class DirectiveProvidingInjectable {
}
@ -2461,7 +2430,6 @@ class DirectiveProvidingInjectable {
viewProviders: [[InjectableService]],
template: ''
})
@Injectable()
class DirectiveProvidingInjectableInView {
}
@ -2471,33 +2439,27 @@ class DirectiveProvidingInjectableInView {
viewProviders: [/* @ts2dart_Provider */ {provide: InjectableService, useValue: 'view'}],
template: ''
})
@Injectable()
class DirectiveProvidingInjectableInHostAndView {
}
@Component({selector: 'directive-consuming-injectable', template: ''})
@Injectable()
class DirectiveConsumingInjectable {
injectable: any /** TODO #9100 */;
injectable: any;
constructor(@Host() @Inject(InjectableService) injectable: any /** TODO #9100 */) {
this.injectable = injectable;
}
constructor(@Host() @Inject(InjectableService) injectable: any) { this.injectable = injectable; }
}
@Component({selector: 'directive-containing-directive-consuming-an-injectable'})
@Injectable()
class DirectiveContainingDirectiveConsumingAnInjectable {
directive: any /** TODO #9100 */;
directive: any;
}
@Component({selector: 'directive-consuming-injectable-unbounded', template: ''})
@Injectable()
class DirectiveConsumingInjectableUnbounded {
injectable: any /** TODO #9100 */;
injectable: any;
constructor(
injectable: InjectableService,
@ -2531,7 +2493,7 @@ class GrandParentProvidingEventBus {
constructor(bus: EventBus) { this.bus = bus; }
}
function createParentBus(peb: any /** TODO #9100 */) {
function createParentBus(peb: EventBus) {
return new EventBus(peb, 'parent');
}
@ -2561,13 +2523,12 @@ class ChildConsumingEventBus {
}
@Directive({selector: '[someImpvp]', inputs: ['someImpvp']})
@Injectable()
class SomeImperativeViewport {
view: EmbeddedViewRef<Object>;
anchor: any /** TODO #9100 */;
anchor: any;
constructor(
public vc: ViewContainerRef, public templateRef: TemplateRef<Object>,
@Inject(ANCHOR_ELEMENT) anchor: any /** TODO #9100 */) {
@Inject(ANCHOR_ELEMENT) anchor: any) {
this.view = null;
this.anchor = anchor;
}
@ -2626,16 +2587,16 @@ class ComponentWithTemplate {
@Directive({selector: 'with-prop-decorators'})
class DirectiveWithPropDecorators {
target: any /** TODO #9100 */;
target: any;
@Input('elProp') dirProp: string;
@Output('elEvent') event = new EventEmitter();
@HostBinding('attr.my-attr') myAttr: string;
@HostListener('click', ['$event.target'])
onClick(target: any /** TODO #9100 */) { this.target = target; }
onClick(target: any) { this.target = target; }
fireEvent(msg: any /** TODO #9100 */) { ObservableWrapper.callEmit(this.event, msg); }
fireEvent(msg: any) { ObservableWrapper.callEmit(this.event, msg); }
}
@Component({selector: 'some-cmp'})

View File

@ -185,7 +185,7 @@ export function main() {
var viewportDirectives =
main.debugElement.children[0]
.childNodes.filter(By.directive(ManualViewportDirective))
.map(de => de.inject(ManualViewportDirective));
.map(de => de.injector.get(ManualViewportDirective));
expect(main.debugElement.nativeElement).toHaveText('(, B)');
viewportDirectives.forEach(d => d.show());
@ -234,7 +234,7 @@ export function main() {
var viewportDirective =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective);
.injector.get(ManualViewportDirective);
expect(main.debugElement.nativeElement)
.toHaveText('OUTER(INNER(INNERINNER(,BC)))');
@ -263,7 +263,7 @@ export function main() {
var viewportDirective =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective);
.injector.get(ManualViewportDirective);
expect(main.debugElement.nativeElement).toHaveText('(, BC)');
@ -342,13 +342,13 @@ export function main() {
// all.
getAllDebugNodes().forEach((debug) => {
if (debug.providerTokens.indexOf(ManualViewportDirective) !== -1) {
sourceDirective = debug.inject(ManualViewportDirective);
sourceDirective = debug.injector.get(ManualViewportDirective);
}
});
var projectDirective: ProjectDirective =
main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0].inject(
ProjectDirective);
main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0]
.injector.get(ProjectDirective);
expect(main.debugElement.nativeElement).toHaveText('START()END');
@ -373,10 +373,10 @@ export function main() {
var sourceDirective: ManualViewportDirective =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective);
.injector.get(ManualViewportDirective);
var projectDirective: ProjectDirective =
main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0].inject(
ProjectDirective);
main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0]
.injector.get(ProjectDirective);
expect(main.debugElement.nativeElement).toHaveText('SIMPLE()START()END');
projectDirective.show(sourceDirective.templateRef);
@ -405,10 +405,10 @@ export function main() {
var sourceDirective: ManualViewportDirective =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective);
.injector.get(ManualViewportDirective);
var projectDirective: ProjectDirective =
main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0].inject(
ProjectDirective);
main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0]
.injector.get(ProjectDirective);
expect(main.debugElement.nativeElement).toHaveText('(, B)START()END');
projectDirective.show(sourceDirective.templateRef);
@ -438,7 +438,7 @@ export function main() {
main.detectChanges();
var manualDirective: ManualViewportDirective =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective);
.injector.get(ManualViewportDirective);
expect(main.debugElement.nativeElement).toHaveText('TREE(0:)');
manualDirective.show();
main.detectChanges();
@ -470,14 +470,14 @@ export function main() {
var tree = main.debugElement.query(By.directive(Tree));
var manualDirective: ManualViewportDirective = tree.queryAllNodes(By.directive(
ManualViewportDirective))[0].inject(ManualViewportDirective);
ManualViewportDirective))[0].injector.get(ManualViewportDirective);
manualDirective.show();
main.detectChanges();
expect(main.debugElement.nativeElement).toHaveText('TREE(0:TREE2(1:))');
var tree2 = main.debugElement.query(By.directive(Tree2));
manualDirective =
tree2.queryAllNodes(By.directive(ManualViewportDirective))[0].inject(
tree2.queryAllNodes(By.directive(ManualViewportDirective))[0].injector.get(
ManualViewportDirective);
manualDirective.show();
main.detectChanges();
@ -568,12 +568,12 @@ export function main() {
var viewportElement =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0];
viewportElement.inject(ManualViewportDirective).show();
viewportElement.injector.get(ManualViewportDirective).show();
expect(main.debugElement.nativeElement).toHaveText('MAIN(FIRST())');
viewportElement =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[1];
viewportElement.inject(ManualViewportDirective).show();
viewportElement.injector.get(ManualViewportDirective).show();
expect(main.debugElement.nativeElement).toHaveText('MAIN(FIRST(SECOND(a)))');
async.done();
@ -639,7 +639,7 @@ export function main() {
var viewViewportDir =
conditionalComp.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective);
.injector.get(ManualViewportDirective);
expect(main.debugElement.nativeElement).toHaveText('(, D)');
expect(main.debugElement.nativeElement).toHaveText('(, D)');

View File

@ -5,7 +5,7 @@ import {AsyncTestCompleter} from '@angular/core/testing/testing_internal';
import {isPresent, stringify} from '../../src/facade/lang';
import {ObservableWrapper} from '../../src/facade/async';
import {Component, Directive, Injectable, Optional, TemplateRef, Query, QueryList, ViewQuery, ContentChildren, ViewChildren, ContentChild, ViewChild, AfterContentInit, AfterViewInit, AfterContentChecked, AfterViewChecked} from '@angular/core';
import {Component, Directive, TemplateRef, Query, QueryList, ViewQuery, ContentChildren, ViewChildren, ContentChild, ViewChild, AfterContentInit, AfterViewInit, AfterContentChecked, AfterViewChecked} from '@angular/core';
import {NgIf, NgFor} from '@angular/common';
import {asNativeElements, ViewContainerRef} from '@angular/core';
@ -275,7 +275,7 @@ export function main() {
var template = '<needs-tpl><template><div>light</div></template></needs-tpl>';
tcb.overrideTemplate(MyComp0, template).createAsync(MyComp0).then((view) => {
view.detectChanges();
var needsTpl: NeedsTpl = view.debugElement.children[0].inject(NeedsTpl);
var needsTpl: NeedsTpl = view.debugElement.children[0].injector.get(NeedsTpl);
expect(needsTpl.vc.createEmbeddedView(needsTpl.query.first).rootNodes[0])
.toHaveText('light');
@ -294,7 +294,8 @@ export function main() {
'<needs-named-tpl><template #tpl><div>light</div></template></needs-named-tpl>';
tcb.overrideTemplate(MyComp0, template).createAsync(MyComp0).then((view) => {
view.detectChanges();
var needsTpl: NeedsNamedTpl = view.debugElement.children[0].inject(NeedsNamedTpl);
var needsTpl: NeedsNamedTpl =
view.debugElement.children[0].injector.get(NeedsNamedTpl);
expect(needsTpl.vc.createEmbeddedView(needsTpl.contentTpl).rootNodes[0])
.toHaveText('light');
expect(needsTpl.vc.createEmbeddedView(needsTpl.viewTpl).rootNodes[0])
@ -317,7 +318,7 @@ export function main() {
view.detectChanges();
var comp: NeedsContentChildrenWithRead =
view.debugElement.children[0].inject(NeedsContentChildrenWithRead);
view.debugElement.children[0].injector.get(NeedsContentChildrenWithRead);
expect(comp.textDirChildren.map(textDirective => textDirective.text)).toEqual([
'ca', 'cb'
]);
@ -337,7 +338,7 @@ export function main() {
view.detectChanges();
var comp: NeedsContentChildWithRead =
view.debugElement.children[0].inject(NeedsContentChildWithRead);
view.debugElement.children[0].injector.get(NeedsContentChildWithRead);
expect(comp.textDirChild.text).toEqual('ca');
async.done();
@ -354,7 +355,7 @@ export function main() {
view.detectChanges();
var comp: NeedsViewChildWithRead =
view.debugElement.children[0].inject(NeedsViewChildWithRead);
view.debugElement.children[0].injector.get(NeedsViewChildWithRead);
expect(comp.textDirChild.text).toEqual('va');
async.done();
@ -371,7 +372,7 @@ export function main() {
view.detectChanges();
var comp: NeedsViewChildrenWithRead =
view.debugElement.children[0].inject(NeedsViewChildrenWithRead);
view.debugElement.children[0].injector.get(NeedsViewChildrenWithRead);
expect(comp.textDirChildren.map(textDirective => textDirective.text)).toEqual([
'va', 'vb'
]);
@ -391,7 +392,7 @@ export function main() {
view.detectChanges();
var comp: NeedsViewContainerWithRead =
view.debugElement.children[0].inject(NeedsViewContainerWithRead);
view.debugElement.children[0].injector.get(NeedsViewContainerWithRead);
comp.createView();
expect(view.debugElement.children[0].nativeElement).toHaveText('hello');
@ -804,7 +805,6 @@ export function main() {
}
@Directive({selector: '[text]', inputs: ['text'], exportAs: 'textDir'})
@Injectable()
class TextDirective {
text: string;
constructor() {}
@ -890,7 +890,6 @@ class NeedsStaticContentAndViewChild {
}
@Directive({selector: '[dir]'})
@Injectable()
class InertDirective {
constructor() {}
}
@ -900,7 +899,6 @@ class InertDirective {
directives: [NgFor, TextDirective],
template: '<div text="ignoreme"></div><b *ngFor="let dir of query">{{dir.text}}|</b>'
})
@Injectable()
class NeedsQuery {
query: QueryList<TextDirective>;
constructor(@Query(TextDirective) query: QueryList<TextDirective>) { this.query = query; }
@ -919,7 +917,6 @@ class NeedsFourQueries {
directives: [NgFor],
template: '<ng-content></ng-content><div *ngFor="let dir of query">{{dir.text}}|</div>'
})
@Injectable()
class NeedsQueryDesc {
query: QueryList<TextDirective>;
constructor(@Query(TextDirective, {descendants: true}) query: QueryList<TextDirective>) {
@ -928,7 +925,6 @@ class NeedsQueryDesc {
}
@Component({selector: 'needs-query-by-ref-binding', directives: [], template: '<ng-content>'})
@Injectable()
class NeedsQueryByLabel {
query: QueryList<any>;
constructor(@Query('textLabel', {descendants: true}) query: QueryList<any>) {
@ -941,14 +937,12 @@ class NeedsQueryByLabel {
directives: [],
template: '<div #textLabel>text</div>'
})
@Injectable()
class NeedsViewQueryByLabel {
query: QueryList<any>;
constructor(@ViewQuery('textLabel') query: QueryList<any>) { this.query = query; }
}
@Component({selector: 'needs-query-by-ref-bindings', directives: [], template: '<ng-content>'})
@Injectable()
class NeedsQueryByTwoLabels {
query: QueryList<any>;
constructor(@Query('textLabel1,textLabel2', {descendants: true}) query: QueryList<any>) {
@ -961,7 +955,6 @@ class NeedsQueryByTwoLabels {
directives: [NgFor],
template: '<div *ngFor="let dir of query">{{dir.text}}|</div><ng-content></ng-content>'
})
@Injectable()
class NeedsQueryAndProject {
query: QueryList<TextDirective>;
constructor(@Query(TextDirective) query: QueryList<TextDirective>) { this.query = query; }
@ -973,7 +966,6 @@ class NeedsQueryAndProject {
template: '<div text="1"><div text="2"></div></div>' +
'<div text="3"></div><div text="4"></div>'
})
@Injectable()
class NeedsViewQuery {
query: QueryList<TextDirective>;
constructor(@ViewQuery(TextDirective) query: QueryList<TextDirective>) { this.query = query; }
@ -984,7 +976,6 @@ class NeedsViewQuery {
directives: [NgIf, TextDirective],
template: '<div *ngIf="show" text="1"></div>'
})
@Injectable()
class NeedsViewQueryIf {
show: boolean;
query: QueryList<TextDirective>;
@ -1000,7 +991,6 @@ class NeedsViewQueryIf {
directives: [NgIf, InertDirective, TextDirective],
template: '<div text="1"><div *ngIf="show"><div dir></div></div></div>'
})
@Injectable()
class NeedsViewQueryNestedIf {
show: boolean;
query: QueryList<TextDirective>;
@ -1017,7 +1007,6 @@ class NeedsViewQueryNestedIf {
'<div *ngFor="let i of list" [text]="i"></div>' +
'<div text="4"></div>'
})
@Injectable()
class NeedsViewQueryOrder {
query: QueryList<TextDirective>;
list: string[];
@ -1034,7 +1023,6 @@ class NeedsViewQueryOrder {
'<div *ngFor="let i of list" [text]="i"></div>' +
'<div text="4"></div></div>'
})
@Injectable()
class NeedsViewQueryOrderWithParent {
query: QueryList<TextDirective>;
list: string[];
@ -1143,7 +1131,6 @@ class HasNullQueryCondition {
],
template: ''
})
@Injectable()
class MyComp0 {
shouldShow: boolean;
list: any /** TODO #9100 */;
@ -1154,6 +1141,5 @@ class MyComp0 {
}
@Component({selector: 'my-comp', directives: [HasNullQueryCondition], template: ''})
@Injectable()
class MyCompBroken0 {
}

View File

@ -24,7 +24,6 @@ export function main() {
}
@Component({selector: 'my-comp', directives: []})
@Injectable()
class SecuredComponent {
ctxProp: string;
constructor() { this.ctxProp = 'some value'; }

View File

@ -266,13 +266,13 @@ export function main() {
describe('injection', () => {
it('should instantiate directives that have no dependencies', fakeAsync(() => {
var el = createComp('<div simpleDirective>', tcb);
expect(el.children[0].inject(SimpleDirective)).toBeAnInstanceOf(SimpleDirective);
expect(el.children[0].injector.get(SimpleDirective)).toBeAnInstanceOf(SimpleDirective);
}));
it('should instantiate directives that depend on another directive', fakeAsync(() => {
var el = createComp('<div simpleDirective needsDirective>', tcb);
var d = el.children[0].inject(NeedsDirective);
var d = el.children[0].injector.get(NeedsDirective);
expect(d).toBeAnInstanceOf(NeedsDirective);
expect(d.dependency).toBeAnInstanceOf(SimpleDirective);
@ -289,14 +289,14 @@ export function main() {
{provide: 'instance', useValue: new TestValue('a')},
{provide: 'nested', useValue: [{'a': [1]}, new TestValue('b')]},
]));
expect(el.inject('numLiteral')).toBe(0);
expect(el.inject('boolLiteral')).toBe(true);
expect(el.inject('strLiteral')).toBe('a');
expect(el.inject('null')).toBe(null);
expect(el.inject('array')).toEqual([1]);
expect(el.inject('map')).toEqual({'a': 1});
expect(el.inject('instance')).toEqual(new TestValue('a'));
expect(el.inject('nested')).toEqual([{'a': [1]}, new TestValue('b')]);
expect(el.injector.get('numLiteral')).toBe(0);
expect(el.injector.get('boolLiteral')).toBe(true);
expect(el.injector.get('strLiteral')).toBe('a');
expect(el.injector.get('null')).toBe(null);
expect(el.injector.get('array')).toEqual([1]);
expect(el.injector.get('map')).toEqual({'a': 1});
expect(el.injector.get('instance')).toEqual(new TestValue('a'));
expect(el.injector.get('nested')).toEqual([{'a': [1]}, new TestValue('b')]);
}));
it('should instantiate providers that have dependencies with SkipSelf', fakeAsync(() => {
@ -311,7 +311,7 @@ export function main() {
deps: [[new InjectMetadata('injectable1'), new SkipSelfMetadata()]]
}
]));
expect(el.children[0].children[0].inject('injectable2'))
expect(el.children[0].children[0].injector.get('injectable2'))
.toEqual('injectable1-injectable2');
}));
@ -325,7 +325,7 @@ export function main() {
];
var el = createComp(
'<div simpleDirective></div>', tcb.overrideProviders(SimpleDirective, providers));
expect(el.children[0].inject('injectable2')).toEqual('injectable1-injectable2');
expect(el.children[0].injector.get('injectable2')).toEqual('injectable1-injectable2');
}));
it('should instantiate viewProviders that have dependencies', fakeAsync(() => {
@ -340,7 +340,7 @@ export function main() {
var el = createComp(
'<div simpleComponent></div>',
tcb.overrideViewProviders(SimpleComponent, viewProviders));
expect(el.children[0].inject('injectable2')).toEqual('injectable1-injectable2');
expect(el.children[0].injector.get('injectable2')).toEqual('injectable1-injectable2');
}));
it('should instantiate components that depend on viewProviders providers', fakeAsync(() => {
@ -348,7 +348,7 @@ export function main() {
'<div needsServiceComponent></div>',
tcb.overrideViewProviders(
NeedsServiceComponent, [{provide: 'service', useValue: 'service'}]));
expect(el.children[0].inject(NeedsServiceComponent).service).toEqual('service');
expect(el.children[0].injector.get(NeedsServiceComponent).service).toEqual('service');
}));
it('should instantiate multi providers', fakeAsync(() => {
@ -358,7 +358,9 @@ export function main() {
];
var el = createComp(
'<div simpleDirective></div>', tcb.overrideProviders(SimpleDirective, providers));
expect(el.children[0].inject('injectable1')).toEqual(['injectable11', 'injectable12']);
expect(el.children[0].injector.get('injectable1')).toEqual([
'injectable11', 'injectable12'
]);
}));
it('should instantiate providers lazily', fakeAsync(() => {
@ -370,7 +372,7 @@ export function main() {
expect(created).toBe(false);
el.children[0].inject('service');
el.children[0].injector.get('service');
expect(created).toBe(true);
}));
@ -384,7 +386,7 @@ export function main() {
expect(created).toBe(false);
el.children[0].inject('service');
el.children[0].injector.get('service');
expect(created).toBe(true);
}));
@ -405,7 +407,8 @@ export function main() {
'<div simpleDirective><div needsService></div></div>',
tcb.overrideProviders(
SimpleDirective, [{provide: 'service', useValue: 'parentService'}]));
expect(el.children[0].children[0].inject(NeedsService).service).toEqual('parentService');
expect(el.children[0].children[0].injector.get(NeedsService).service)
.toEqual('parentService');
}));
it('should instantiate directives that depend on providers in a parent view',
@ -414,7 +417,8 @@ export function main() {
'<div simpleDirective><template [ngIf]="true"><div *ngIf="true" needsService></div></template></div>',
tcb.overrideProviders(
SimpleDirective, [{provide: 'service', useValue: 'parentService'}]));
expect(el.children[0].children[0].inject(NeedsService).service).toEqual('parentService');
expect(el.children[0].children[0].injector.get(NeedsService).service)
.toEqual('parentService');
}));
it('should instantiate directives that depend on providers of a component', fakeAsync(() => {
@ -423,7 +427,8 @@ export function main() {
tcb.overrideTemplate(SimpleComponent, '<div needsService></div>')
.overrideProviders(
SimpleComponent, [{provide: 'service', useValue: 'hostService'}]));
expect(el.children[0].children[0].inject(NeedsService).service).toEqual('hostService');
expect(el.children[0].children[0].injector.get(NeedsService).service)
.toEqual('hostService');
}));
it('should instantiate directives that depend on view providers of a component',
@ -433,7 +438,8 @@ export function main() {
tcb.overrideTemplate(SimpleComponent, '<div needsService></div>')
.overrideViewProviders(
SimpleComponent, [{provide: 'service', useValue: 'hostService'}]));
expect(el.children[0].children[0].inject(NeedsService).service).toEqual('hostService');
expect(el.children[0].children[0].injector.get(NeedsService).service)
.toEqual('hostService');
}));
it('should instantiate directives in a root embedded view that depend on view providers of a component',
@ -443,13 +449,14 @@ export function main() {
tcb.overrideTemplate(SimpleComponent, '<div *ngIf="true" needsService></div>')
.overrideViewProviders(
SimpleComponent, [{provide: 'service', useValue: 'hostService'}]));
expect(el.children[0].children[0].inject(NeedsService).service).toEqual('hostService');
expect(el.children[0].children[0].injector.get(NeedsService).service)
.toEqual('hostService');
}));
it('should instantiate directives that depend on instances in the app injector',
fakeAsync(() => {
var el = createComp('<div needsAppService></div>', tcb);
expect(el.children[0].inject(NeedsAppService).service).toEqual('appService');
expect(el.children[0].injector.get(NeedsAppService).service).toEqual('appService');
}));
it('should not instantiate a directive with cyclic dependencies', fakeAsync(() => {
@ -495,7 +502,7 @@ export function main() {
it('should instantiate directives that depend on other directives', fakeAsync(() => {
var el = createComp('<div simpleDirective><div needsDirective></div></div>', tcb);
var d = el.children[0].children[0].inject(NeedsDirective);
var d = el.children[0].children[0].injector.get(NeedsDirective);
expect(d).toBeAnInstanceOf(NeedsDirective);
expect(d.dependency).toBeAnInstanceOf(SimpleDirective);
@ -508,7 +515,7 @@ export function main() {
it('should inject null when an optional dependency cannot be resolved', fakeAsync(() => {
var el = createComp('<div optionallyNeedsDirective></div>', tcb);
var d = el.children[0].inject(OptionallyNeedsDirective);
var d = el.children[0].injector.get(OptionallyNeedsDirective);
expect(d.dependency).toEqual(null);
}));
@ -516,7 +523,7 @@ export function main() {
var el = createComp(
'<div simpleComponent></div>',
tcb.overrideTemplate(SimpleComponent, '<div needsComponentFromHost></div>'));
var d = el.children[0].children[0].inject(NeedsComponentFromHost);
var d = el.children[0].children[0].injector.get(NeedsComponentFromHost);
expect(d.dependency).toBeAnInstanceOf(SimpleComponent);
}));
@ -540,7 +547,7 @@ export function main() {
describe('static attributes', () => {
it('should be injectable', fakeAsync(() => {
var el = createComp('<div needsAttribute type="text" title></div>', tcb);
var needsAttribute = el.children[0].inject(NeedsAttribute);
var needsAttribute = el.children[0].injector.get(NeedsAttribute);
expect(needsAttribute.typeAttribute).toEqual('text');
expect(needsAttribute.titleAttribute).toEqual('');
@ -549,7 +556,7 @@ export function main() {
it('should be injectable without type annotation', fakeAsync(() => {
var el = createComp('<div needsAttributeNoType foo="bar"></div>', tcb);
var needsAttribute = el.children[0].inject(NeedsAttributeNoType);
var needsAttribute = el.children[0].injector.get(NeedsAttributeNoType);
expect(needsAttribute.fooAttribute).toEqual('bar');
}));
@ -558,7 +565,7 @@ export function main() {
describe('refs', () => {
it('should inject ElementRef', fakeAsync(() => {
var el = createComp('<div needsElementRef></div>', tcb);
expect(el.children[0].inject(NeedsElementRef).elementRef.nativeElement)
expect(el.children[0].injector.get(NeedsElementRef).elementRef.nativeElement)
.toBe(el.children[0].nativeElement);
}));
@ -567,7 +574,7 @@ export function main() {
var cf = createCompFixture('<div componentNeedsChangeDetectorRef></div>', tcb);
cf.detectChanges();
var compEl = cf.debugElement.children[0];
var comp = compEl.inject(PushComponentNeedsChangeDetectorRef);
var comp = compEl.injector.get(PushComponentNeedsChangeDetectorRef);
comp.counter = 1;
cf.detectChanges();
expect(compEl.nativeElement).toHaveText('0');
@ -586,13 +593,15 @@ export function main() {
cf.detectChanges();
var compEl = cf.debugElement.children[0];
var comp: PushComponentNeedsChangeDetectorRef =
compEl.inject(PushComponentNeedsChangeDetectorRef);
compEl.injector.get(PushComponentNeedsChangeDetectorRef);
comp.counter = 1;
cf.detectChanges();
expect(compEl.nativeElement).toHaveText('0');
expect(compEl.children[0].inject(DirectiveNeedsChangeDetectorRef).changeDetectorRef)
expect(
compEl.children[0].injector.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef)
.toBe(comp.changeDetectorRef);
expect(compEl.children[1].inject(DirectiveNeedsChangeDetectorRef).changeDetectorRef)
expect(
compEl.children[1].injector.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef)
.toBe(comp.changeDetectorRef);
comp.changeDetectorRef.markForCheck();
cf.detectChanges();
@ -601,14 +610,16 @@ export function main() {
it('should inject ViewContainerRef', fakeAsync(() => {
var el = createComp('<div needsViewContainerRef></div>', tcb);
expect(el.children[0].inject(NeedsViewContainerRef).viewContainer.element.nativeElement)
expect(el.children[0]
.injector.get(NeedsViewContainerRef)
.viewContainer.element.nativeElement)
.toBe(el.children[0].nativeElement);
}));
it('should inject TemplateRef', fakeAsync(() => {
var el = createComp('<template needsViewContainerRef needsTemplateRef></template>', tcb);
expect(el.childNodes[0].inject(NeedsTemplateRef).templateRef.elementRef)
.toEqual(el.childNodes[0].inject(NeedsViewContainerRef).viewContainer.element);
expect(el.childNodes[0].injector.get(NeedsTemplateRef).templateRef.elementRef)
.toEqual(el.childNodes[0].injector.get(NeedsViewContainerRef).viewContainer.element);
}));
it('should throw if there is no TemplateRef', fakeAsync(() => {
@ -619,7 +630,7 @@ export function main() {
it('should inject null if there is no TemplateRef when the dependency is optional',
fakeAsync(() => {
var el = createComp('<div optionallyNeedsTemplateRef></div>', tcb);
var instance = el.children[0].inject(OptionallyNeedsTemplateRef);
var instance = el.children[0].injector.get(OptionallyNeedsTemplateRef);
expect(instance.templateRef).toBeNull();
}));
});
@ -629,20 +640,23 @@ export function main() {
var el = createComp(
'<div [simpleDirective]="true | pipeNeedsService"></div>',
tcb.overrideProviders(TestComp, [{provide: 'service', useValue: 'pipeService'}]));
expect(el.children[0].inject(SimpleDirective).value.service).toEqual('pipeService');
expect(el.children[0].injector.get(SimpleDirective).value.service)
.toEqual('pipeService');
}));
it('should overwrite pipes with later entry in the pipes array', fakeAsync(() => {
var el = createComp('<div [simpleDirective]="true | duplicatePipe"></div>', tcb);
expect(el.children[0].inject(SimpleDirective).value).toBeAnInstanceOf(DuplicatePipe2);
expect(el.children[0].injector.get(SimpleDirective).value)
.toBeAnInstanceOf(DuplicatePipe2);
}));
it('should inject ChangeDetectorRef into pipes', fakeAsync(() => {
var el = createComp(
'<div [simpleDirective]="true | pipeNeedsChangeDetectorRef" directiveNeedsChangeDetectorRef></div>',
tcb);
var cdRef = el.children[0].inject(DirectiveNeedsChangeDetectorRef).changeDetectorRef;
expect(el.children[0].inject(SimpleDirective).value.changeDetectorRef).toBe(cdRef);
var cdRef =
el.children[0].injector.get(DirectiveNeedsChangeDetectorRef).changeDetectorRef;
expect(el.children[0].injector.get(SimpleDirective).value.changeDetectorRef).toBe(cdRef);
}));
it('should cache pure pipes', fakeAsync(() => {
@ -650,10 +664,10 @@ export function main() {
'<div [simpleDirective]="true | purePipe"></div><div [simpleDirective]="true | purePipe"></div>' +
'<div *ngFor="let x of [1,2]" [simpleDirective]="true | purePipe"></div>',
tcb);
var purePipe1 = el.children[0].inject(SimpleDirective).value;
var purePipe2 = el.children[1].inject(SimpleDirective).value;
var purePipe3 = el.children[2].inject(SimpleDirective).value;
var purePipe4 = el.children[3].inject(SimpleDirective).value;
var purePipe1 = el.children[0].injector.get(SimpleDirective).value;
var purePipe2 = el.children[1].injector.get(SimpleDirective).value;
var purePipe3 = el.children[2].injector.get(SimpleDirective).value;
var purePipe4 = el.children[3].injector.get(SimpleDirective).value;
expect(purePipe1).toBeAnInstanceOf(PurePipe);
expect(purePipe2).toBe(purePipe1);
expect(purePipe3).toBe(purePipe1);
@ -665,10 +679,10 @@ export function main() {
'<div [simpleDirective]="true | impurePipe"></div><div [simpleDirective]="true | impurePipe"></div>' +
'<div *ngFor="let x of [1,2]" [simpleDirective]="true | impurePipe"></div>',
tcb);
var purePipe1 = el.children[0].inject(SimpleDirective).value;
var purePipe2 = el.children[1].inject(SimpleDirective).value;
var purePipe3 = el.children[2].inject(SimpleDirective).value;
var purePipe4 = el.children[3].inject(SimpleDirective).value;
var purePipe1 = el.children[0].injector.get(SimpleDirective).value;
var purePipe2 = el.children[1].injector.get(SimpleDirective).value;
var purePipe3 = el.children[2].injector.get(SimpleDirective).value;
var purePipe4 = el.children[3].injector.get(SimpleDirective).value;
expect(purePipe1).toBeAnInstanceOf(ImpurePipe);
expect(purePipe2).toBeAnInstanceOf(ImpurePipe);
expect(purePipe2).not.toBe(purePipe1);

View File

@ -1201,7 +1201,7 @@ export function main() {
fixture.debugElement.componentInstance.name = null;
fixture.detectChanges();
var form = fixture.debugElement.children[0].inject(NgForm);
var form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.controls['user']).not.toBeDefined();
tick();
@ -1257,7 +1257,7 @@ export function main() {
fixture.debugElement.componentInstance.name = 'show';
fixture.detectChanges();
tick();
var form = fixture.debugElement.children[0].inject(NgForm);
var form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.controls['login']).toBeDefined();
@ -1283,7 +1283,7 @@ export function main() {
fixture.debugElement.componentInstance.name = 'show';
fixture.detectChanges();
tick();
var form = fixture.debugElement.children[0].inject(NgForm);
var form = fixture.debugElement.children[0].injector.get(NgForm);
expect(form.controls['user']).toBeDefined();
@ -1348,7 +1348,7 @@ export function main() {
tick();
fixture.debugElement.componentInstance.name = 'Nancy';
fixture.detectChanges();
var form = fixture.debugElement.children[0].inject(NgForm);
var form = fixture.debugElement.children[0].injector.get(NgForm);
tick();
expect(form.value).toEqual({first: 'Nancy'});
@ -1387,7 +1387,7 @@ export function main() {
tick();
fixture.debugElement.componentInstance.data = 'some data';
fixture.detectChanges();
const form = fixture.debugElement.children[0].inject(NgForm);
const form = fixture.debugElement.children[0].injector.get(NgForm);
tick();
expect(form.value).toEqual({two: 'some data'});