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

View File

@ -154,7 +154,7 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
visitElement(ast: ElementAst, parent: CompileElement): any { visitElement(ast: ElementAst, parent: CompileElement): any {
var nodeIndex = this.view.nodes.length; var nodeIndex = this.view.nodes.length;
var createRenderNodeExpr: any /** TODO #9100 */; var createRenderNodeExpr: o.InvokeMethodExpr;
var debugContextExpr = this.view.createMethod.resetDebugInfoExpr(nodeIndex, ast); var debugContextExpr = this.view.createMethod.resetDebugInfoExpr(nodeIndex, ast);
if (nodeIndex === 0 && this.view.viewType === ViewType.HOST) { if (nodeIndex === 0 && this.view.viewType === ViewType.HOST) {
createRenderNodeExpr = o.THIS_EXPR.callMethod( createRenderNodeExpr = o.THIS_EXPR.callMethod(
@ -213,7 +213,7 @@ class ViewBuilderVisitor implements TemplateAstVisitor {
compileElement.afterChildren(this.view.nodes.length - nodeIndex - 1); compileElement.afterChildren(this.view.nodes.length - nodeIndex - 1);
if (isPresent(compViewExpr)) { if (isPresent(compViewExpr)) {
var codeGenContentNodes: any /** TODO #9100 */; var codeGenContentNodes: o.Expression;
if (this.view.component.type.isHost) { if (this.view.component.type.isHost) {
codeGenContentNodes = ViewProperties.projectableNodes; codeGenContentNodes = ViewProperties.projectableNodes;
} else { } else {
@ -327,15 +327,12 @@ function _mergeHtmlAndDirectiveAttrs(
directives: CompileDirectiveMetadata[]): string[][] { directives: CompileDirectiveMetadata[]): string[][] {
var result: {[key: string]: string} = {}; var result: {[key: string]: string} = {};
StringMapWrapper.forEach( StringMapWrapper.forEach(
declaredHtmlAttrs, declaredHtmlAttrs, (value: string, key: string) => { result[key] = value; });
(value: any /** TODO #9100 */, key: any /** TODO #9100 */) => { result[key] = value; });
directives.forEach(directiveMeta => { directives.forEach(directiveMeta => {
StringMapWrapper.forEach( StringMapWrapper.forEach(directiveMeta.hostAttributes, (value: string, name: string) => {
directiveMeta.hostAttributes, var prevValue = result[name];
(value: any /** TODO #9100 */, name: any /** TODO #9100 */) => { result[name] = isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value;
var prevValue = result[name]; });
result[name] = isPresent(prevValue) ? mergeAttributeValue(name, prevValue, value) : value;
});
}); });
return mapToKeyValueArray(result); return mapToKeyValueArray(result);
} }
@ -355,16 +352,14 @@ function mergeAttributeValue(attrName: string, attrValue1: string, attrValue2: s
} }
function mapToKeyValueArray(data: {[key: string]: string}): string[][] { function mapToKeyValueArray(data: {[key: string]: string}): string[][] {
var entryArray: any[] /** TODO #9100 */ = []; var entryArray: string[][] = [];
StringMapWrapper.forEach(data, (value: any /** TODO #9100 */, name: any /** TODO #9100 */) => { StringMapWrapper.forEach(data, (value: string, name: string) => {
entryArray.push([name, value]); entryArray.push([name, value]);
}); });
// We need to sort to get a defined output order // We need to sort to get a defined output order
// for tests and for caching generated artifacts... // for tests and for caching generated artifacts...
ListWrapper.sort(entryArray, (entry1, entry2) => StringWrapper.compare(entry1[0], entry2[0])); ListWrapper.sort(entryArray, (entry1, entry2) => StringWrapper.compare(entry1[0], entry2[0]));
var keyValueArray: any[] /** TODO #9100 */ = []; return entryArray;
entryArray.forEach((entry) => { keyValueArray.push([entry[0], entry[1]]); });
return keyValueArray;
} }
function createViewTopLevelStmts(view: CompileView, targetStatements: o.Statement[]) { 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 compileElement = node instanceof CompileElement ? node : null;
var providerTokens: o.Expression[] = []; var providerTokens: o.Expression[] = [];
var componentToken: o.Expression = o.NULL_EXPR; var componentToken: o.Expression = o.NULL_EXPR;
var varTokenEntries: any[] /** TODO #9100 */ = []; var varTokenEntries: any[] = [];
if (isPresent(compileElement)) { if (isPresent(compileElement)) {
providerTokens = compileElement.getProviderTokens(); providerTokens = compileElement.getProviderTokens();
if (isPresent(compileElement.component)) { if (isPresent(compileElement.component)) {
componentToken = createDiTokenExpression(identifierToken(compileElement.component.type)); componentToken = createDiTokenExpression(identifierToken(compileElement.component.type));
} }
StringMapWrapper.forEach( StringMapWrapper.forEach(
compileElement.referenceTokens, compileElement.referenceTokens, (token: CompileTokenMetadata, varName: string) => {
(token: any /** TODO #9100 */, varName: any /** TODO #9100 */) => {
varTokenEntries.push( varTokenEntries.push(
[varName, isPresent(token) ? createDiTokenExpression(token) : o.NULL_EXPR]); [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.parentInjector.name, o.importType(Identifiers.Injector)),
new o.FnParam(ViewConstructorVars.declarationEl.name, o.importType(Identifiers.AppElement)) new o.FnParam(ViewConstructorVars.declarationEl.name, o.importType(Identifiers.AppElement))
]; ];
var initRenderCompTypeStmts: any[] /** TODO #9100 */ = []; var initRenderCompTypeStmts: any[] = [];
var templateUrlInfo: any /** TODO #9100 */; var templateUrlInfo: string;
if (view.component.template.templateUrl == view.component.type.moduleUrl) { if (view.component.template.templateUrl == view.component.type.moduleUrl) {
templateUrlInfo = templateUrlInfo =
`${view.component.type.moduleUrl} class ${view.component.type.name} - inline template`; `${view.component.type.moduleUrl} class ${view.component.type.name} - inline template`;
@ -508,7 +502,7 @@ function createViewFactory(
function generateCreateMethod(view: CompileView): o.Statement[] { function generateCreateMethod(view: CompileView): o.Statement[] {
var parentRenderNodeExpr: o.Expression = o.NULL_EXPR; var parentRenderNodeExpr: o.Expression = o.NULL_EXPR;
var parentRenderNodeStmts: any[] /** TODO #9100 */ = []; var parentRenderNodeStmts: any[] = [];
if (view.viewType === ViewType.COMPONENT) { if (view.viewType === ViewType.COMPONENT) {
parentRenderNodeExpr = ViewProperties.renderer.callMethod( parentRenderNodeExpr = ViewProperties.renderer.callMethod(
'createViewRoot', [o.THIS_EXPR.prop('declarationAppElement').prop('nativeElement')]); 'createViewRoot', [o.THIS_EXPR.prop('declarationAppElement').prop('nativeElement')]);
@ -523,7 +517,7 @@ function generateCreateMethod(view: CompileView): o.Statement[] {
} else { } else {
resultExpr = o.NULL_EXPR; resultExpr = o.NULL_EXPR;
} }
return parentRenderNodeStmts.concat(view.createMethod.finish()).concat([ return parentRenderNodeStmts.concat(view.createMethod.finish(), [
o.THIS_EXPR o.THIS_EXPR
.callMethod( .callMethod(
'init', 'init',
@ -538,7 +532,7 @@ function generateCreateMethod(view: CompileView): o.Statement[] {
} }
function generateDetectChangesMethod(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() && if (view.detectChangesInInputsMethod.isEmpty() && view.updateContentQueriesMethod.isEmpty() &&
view.afterContentLifecycleCallbacksMethod.isEmpty() && view.afterContentLifecycleCallbacksMethod.isEmpty() &&
view.detectChangesRenderPropertiesMethod.isEmpty() && view.detectChangesRenderPropertiesMethod.isEmpty() &&
@ -563,7 +557,7 @@ function generateDetectChangesMethod(view: CompileView): o.Statement[] {
stmts.push(new o.IfStmt(o.not(DetectChangesVars.throwOnChange), afterViewStmts)); stmts.push(new o.IfStmt(o.not(DetectChangesVars.throwOnChange), afterViewStmts));
} }
var varStmts: any[] /** TODO #9100 */ = []; var varStmts: any[] = [];
var readVars = o.findReadVarNames(stmts); var readVars = o.findReadVarNames(stmts);
if (SetWrapper.has(readVars, DetectChangesVars.changed.name)) { if (SetWrapper.has(readVars, DetectChangesVars.changed.name)) {
varStmts.push(DetectChangesVars.changed.set(o.literal(true)).toDeclStmt(o.BOOL_TYPE)); 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']}) @Directive({selector: '[message]', inputs: ['message']})
@Injectable()
class MessageDir { class MessageDir {
logger: Logger; logger: Logger;
@ -39,7 +38,6 @@ class MessageDir {
<span class="child" [innerHtml]="childBinding"></span>`, <span class="child" [innerHtml]="childBinding"></span>`,
directives: [MessageDir], directives: [MessageDir],
}) })
@Injectable()
class ChildComp { class ChildComp {
childBinding: string; childBinding: string;
@ -56,14 +54,12 @@ class ChildComp {
<child-comp class="child-comp-class"></child-comp>`, <child-comp class="child-comp-class"></child-comp>`,
directives: [ChildComp, MessageDir], directives: [ChildComp, MessageDir],
}) })
@Injectable()
class ParentComp { class ParentComp {
parentBinding: string; parentBinding: string;
constructor() { this.parentBinding = 'OriginalParent'; } constructor() { this.parentBinding = 'OriginalParent'; }
} }
@Directive({selector: 'custom-emitter', outputs: ['myevent']}) @Directive({selector: 'custom-emitter', outputs: ['myevent']})
@Injectable()
class CustomEmitter { class CustomEmitter {
myevent: EventEmitter<any>; myevent: EventEmitter<any>;
@ -76,7 +72,6 @@ class CustomEmitter {
<custom-emitter (myevent)="handleCustom()"></custom-emitter>`, <custom-emitter (myevent)="handleCustom()"></custom-emitter>`,
directives: [CustomEmitter], directives: [CustomEmitter],
}) })
@Injectable()
class EventsComp { class EventsComp {
clicked: boolean; clicked: boolean;
customed: boolean; customed: boolean;
@ -97,7 +92,6 @@ class EventsComp {
template: `<div class="child" message="child" *ngIf="myBool"><ng-content></ng-content></div>`, template: `<div class="child" message="child" *ngIf="myBool"><ng-content></ng-content></div>`,
directives: [NgIf, MessageDir], directives: [NgIf, MessageDir],
}) })
@Injectable()
class ConditionalContentComp { class ConditionalContentComp {
myBool: boolean = false; myBool: boolean = false;
} }
@ -111,7 +105,6 @@ class ConditionalContentComp {
</cond-content-comp>`, </cond-content-comp>`,
directives: [ConditionalContentComp], directives: [ConditionalContentComp],
}) })
@Injectable()
class ConditionalParentComp { class ConditionalParentComp {
parentBinding: string; parentBinding: string;
constructor() { this.parentBinding = 'OriginalParent'; } constructor() { this.parentBinding = 'OriginalParent'; }
@ -126,7 +119,6 @@ class ConditionalParentComp {
</ul>`, </ul>`,
directives: [NgFor, MessageDir], directives: [NgFor, MessageDir],
}) })
@Injectable()
class UsingFor { class UsingFor {
stuff: string[]; stuff: string[];
constructor() { this.stuff = ['one', 'two', 'three']; } constructor() { this.stuff = ['one', 'two', 'three']; }
@ -387,9 +379,8 @@ export function main() {
tcb.createAsync(ParentComp).then((fixture) => { tcb.createAsync(ParentComp).then((fixture) => {
fixture.detectChanges(); fixture.detectChanges();
expect((<Logger>(fixture.debugElement.children[0].inject(Logger))).logs).toEqual([ expect((<Logger>(fixture.debugElement.children[0].injector.get(Logger))).logs)
'parent', 'nestedparent', 'child', 'nestedchild' .toEqual(['parent', 'nestedparent', 'child', 'nestedchild']);
]);
async.done(); async.done();
}); });

View File

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

View File

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

View File

@ -185,7 +185,7 @@ export function main() {
var viewportDirectives = var viewportDirectives =
main.debugElement.children[0] main.debugElement.children[0]
.childNodes.filter(By.directive(ManualViewportDirective)) .childNodes.filter(By.directive(ManualViewportDirective))
.map(de => de.inject(ManualViewportDirective)); .map(de => de.injector.get(ManualViewportDirective));
expect(main.debugElement.nativeElement).toHaveText('(, B)'); expect(main.debugElement.nativeElement).toHaveText('(, B)');
viewportDirectives.forEach(d => d.show()); viewportDirectives.forEach(d => d.show());
@ -234,7 +234,7 @@ export function main() {
var viewportDirective = var viewportDirective =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0] main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective); .injector.get(ManualViewportDirective);
expect(main.debugElement.nativeElement) expect(main.debugElement.nativeElement)
.toHaveText('OUTER(INNER(INNERINNER(,BC)))'); .toHaveText('OUTER(INNER(INNERINNER(,BC)))');
@ -263,7 +263,7 @@ export function main() {
var viewportDirective = var viewportDirective =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0] main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective); .injector.get(ManualViewportDirective);
expect(main.debugElement.nativeElement).toHaveText('(, BC)'); expect(main.debugElement.nativeElement).toHaveText('(, BC)');
@ -342,13 +342,13 @@ export function main() {
// all. // all.
getAllDebugNodes().forEach((debug) => { getAllDebugNodes().forEach((debug) => {
if (debug.providerTokens.indexOf(ManualViewportDirective) !== -1) { if (debug.providerTokens.indexOf(ManualViewportDirective) !== -1) {
sourceDirective = debug.inject(ManualViewportDirective); sourceDirective = debug.injector.get(ManualViewportDirective);
} }
}); });
var projectDirective: ProjectDirective = var projectDirective: ProjectDirective =
main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0].inject( main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0]
ProjectDirective); .injector.get(ProjectDirective);
expect(main.debugElement.nativeElement).toHaveText('START()END'); expect(main.debugElement.nativeElement).toHaveText('START()END');
@ -373,10 +373,10 @@ export function main() {
var sourceDirective: ManualViewportDirective = var sourceDirective: ManualViewportDirective =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0] main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective); .injector.get(ManualViewportDirective);
var projectDirective: ProjectDirective = var projectDirective: ProjectDirective =
main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0].inject( main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0]
ProjectDirective); .injector.get(ProjectDirective);
expect(main.debugElement.nativeElement).toHaveText('SIMPLE()START()END'); expect(main.debugElement.nativeElement).toHaveText('SIMPLE()START()END');
projectDirective.show(sourceDirective.templateRef); projectDirective.show(sourceDirective.templateRef);
@ -405,10 +405,10 @@ export function main() {
var sourceDirective: ManualViewportDirective = var sourceDirective: ManualViewportDirective =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0] main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective); .injector.get(ManualViewportDirective);
var projectDirective: ProjectDirective = var projectDirective: ProjectDirective =
main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0].inject( main.debugElement.queryAllNodes(By.directive(ProjectDirective))[0]
ProjectDirective); .injector.get(ProjectDirective);
expect(main.debugElement.nativeElement).toHaveText('(, B)START()END'); expect(main.debugElement.nativeElement).toHaveText('(, B)START()END');
projectDirective.show(sourceDirective.templateRef); projectDirective.show(sourceDirective.templateRef);
@ -438,7 +438,7 @@ export function main() {
main.detectChanges(); main.detectChanges();
var manualDirective: ManualViewportDirective = var manualDirective: ManualViewportDirective =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0] main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective); .injector.get(ManualViewportDirective);
expect(main.debugElement.nativeElement).toHaveText('TREE(0:)'); expect(main.debugElement.nativeElement).toHaveText('TREE(0:)');
manualDirective.show(); manualDirective.show();
main.detectChanges(); main.detectChanges();
@ -470,14 +470,14 @@ export function main() {
var tree = main.debugElement.query(By.directive(Tree)); var tree = main.debugElement.query(By.directive(Tree));
var manualDirective: ManualViewportDirective = tree.queryAllNodes(By.directive( var manualDirective: ManualViewportDirective = tree.queryAllNodes(By.directive(
ManualViewportDirective))[0].inject(ManualViewportDirective); ManualViewportDirective))[0].injector.get(ManualViewportDirective);
manualDirective.show(); manualDirective.show();
main.detectChanges(); main.detectChanges();
expect(main.debugElement.nativeElement).toHaveText('TREE(0:TREE2(1:))'); expect(main.debugElement.nativeElement).toHaveText('TREE(0:TREE2(1:))');
var tree2 = main.debugElement.query(By.directive(Tree2)); var tree2 = main.debugElement.query(By.directive(Tree2));
manualDirective = manualDirective =
tree2.queryAllNodes(By.directive(ManualViewportDirective))[0].inject( tree2.queryAllNodes(By.directive(ManualViewportDirective))[0].injector.get(
ManualViewportDirective); ManualViewportDirective);
manualDirective.show(); manualDirective.show();
main.detectChanges(); main.detectChanges();
@ -568,12 +568,12 @@ export function main() {
var viewportElement = var viewportElement =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0]; main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[0];
viewportElement.inject(ManualViewportDirective).show(); viewportElement.injector.get(ManualViewportDirective).show();
expect(main.debugElement.nativeElement).toHaveText('MAIN(FIRST())'); expect(main.debugElement.nativeElement).toHaveText('MAIN(FIRST())');
viewportElement = viewportElement =
main.debugElement.queryAllNodes(By.directive(ManualViewportDirective))[1]; 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)))'); expect(main.debugElement.nativeElement).toHaveText('MAIN(FIRST(SECOND(a)))');
async.done(); async.done();
@ -639,7 +639,7 @@ export function main() {
var viewViewportDir = var viewViewportDir =
conditionalComp.queryAllNodes(By.directive(ManualViewportDirective))[0] conditionalComp.queryAllNodes(By.directive(ManualViewportDirective))[0]
.inject(ManualViewportDirective); .injector.get(ManualViewportDirective);
expect(main.debugElement.nativeElement).toHaveText('(, D)'); expect(main.debugElement.nativeElement).toHaveText('(, D)');
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 {isPresent, stringify} from '../../src/facade/lang';
import {ObservableWrapper} from '../../src/facade/async'; 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 {NgIf, NgFor} from '@angular/common';
import {asNativeElements, ViewContainerRef} from '@angular/core'; import {asNativeElements, ViewContainerRef} from '@angular/core';
@ -275,7 +275,7 @@ export function main() {
var template = '<needs-tpl><template><div>light</div></template></needs-tpl>'; var template = '<needs-tpl><template><div>light</div></template></needs-tpl>';
tcb.overrideTemplate(MyComp0, template).createAsync(MyComp0).then((view) => { tcb.overrideTemplate(MyComp0, template).createAsync(MyComp0).then((view) => {
view.detectChanges(); 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]) expect(needsTpl.vc.createEmbeddedView(needsTpl.query.first).rootNodes[0])
.toHaveText('light'); .toHaveText('light');
@ -294,7 +294,8 @@ export function main() {
'<needs-named-tpl><template #tpl><div>light</div></template></needs-named-tpl>'; '<needs-named-tpl><template #tpl><div>light</div></template></needs-named-tpl>';
tcb.overrideTemplate(MyComp0, template).createAsync(MyComp0).then((view) => { tcb.overrideTemplate(MyComp0, template).createAsync(MyComp0).then((view) => {
view.detectChanges(); 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]) expect(needsTpl.vc.createEmbeddedView(needsTpl.contentTpl).rootNodes[0])
.toHaveText('light'); .toHaveText('light');
expect(needsTpl.vc.createEmbeddedView(needsTpl.viewTpl).rootNodes[0]) expect(needsTpl.vc.createEmbeddedView(needsTpl.viewTpl).rootNodes[0])
@ -317,7 +318,7 @@ export function main() {
view.detectChanges(); view.detectChanges();
var comp: NeedsContentChildrenWithRead = var comp: NeedsContentChildrenWithRead =
view.debugElement.children[0].inject(NeedsContentChildrenWithRead); view.debugElement.children[0].injector.get(NeedsContentChildrenWithRead);
expect(comp.textDirChildren.map(textDirective => textDirective.text)).toEqual([ expect(comp.textDirChildren.map(textDirective => textDirective.text)).toEqual([
'ca', 'cb' 'ca', 'cb'
]); ]);
@ -337,7 +338,7 @@ export function main() {
view.detectChanges(); view.detectChanges();
var comp: NeedsContentChildWithRead = var comp: NeedsContentChildWithRead =
view.debugElement.children[0].inject(NeedsContentChildWithRead); view.debugElement.children[0].injector.get(NeedsContentChildWithRead);
expect(comp.textDirChild.text).toEqual('ca'); expect(comp.textDirChild.text).toEqual('ca');
async.done(); async.done();
@ -354,7 +355,7 @@ export function main() {
view.detectChanges(); view.detectChanges();
var comp: NeedsViewChildWithRead = var comp: NeedsViewChildWithRead =
view.debugElement.children[0].inject(NeedsViewChildWithRead); view.debugElement.children[0].injector.get(NeedsViewChildWithRead);
expect(comp.textDirChild.text).toEqual('va'); expect(comp.textDirChild.text).toEqual('va');
async.done(); async.done();
@ -371,7 +372,7 @@ export function main() {
view.detectChanges(); view.detectChanges();
var comp: NeedsViewChildrenWithRead = var comp: NeedsViewChildrenWithRead =
view.debugElement.children[0].inject(NeedsViewChildrenWithRead); view.debugElement.children[0].injector.get(NeedsViewChildrenWithRead);
expect(comp.textDirChildren.map(textDirective => textDirective.text)).toEqual([ expect(comp.textDirChildren.map(textDirective => textDirective.text)).toEqual([
'va', 'vb' 'va', 'vb'
]); ]);
@ -391,7 +392,7 @@ export function main() {
view.detectChanges(); view.detectChanges();
var comp: NeedsViewContainerWithRead = var comp: NeedsViewContainerWithRead =
view.debugElement.children[0].inject(NeedsViewContainerWithRead); view.debugElement.children[0].injector.get(NeedsViewContainerWithRead);
comp.createView(); comp.createView();
expect(view.debugElement.children[0].nativeElement).toHaveText('hello'); expect(view.debugElement.children[0].nativeElement).toHaveText('hello');
@ -804,7 +805,6 @@ export function main() {
} }
@Directive({selector: '[text]', inputs: ['text'], exportAs: 'textDir'}) @Directive({selector: '[text]', inputs: ['text'], exportAs: 'textDir'})
@Injectable()
class TextDirective { class TextDirective {
text: string; text: string;
constructor() {} constructor() {}
@ -890,7 +890,6 @@ class NeedsStaticContentAndViewChild {
} }
@Directive({selector: '[dir]'}) @Directive({selector: '[dir]'})
@Injectable()
class InertDirective { class InertDirective {
constructor() {} constructor() {}
} }
@ -900,7 +899,6 @@ class InertDirective {
directives: [NgFor, TextDirective], directives: [NgFor, TextDirective],
template: '<div text="ignoreme"></div><b *ngFor="let dir of query">{{dir.text}}|</b>' template: '<div text="ignoreme"></div><b *ngFor="let dir of query">{{dir.text}}|</b>'
}) })
@Injectable()
class NeedsQuery { class NeedsQuery {
query: QueryList<TextDirective>; query: QueryList<TextDirective>;
constructor(@Query(TextDirective) query: QueryList<TextDirective>) { this.query = query; } constructor(@Query(TextDirective) query: QueryList<TextDirective>) { this.query = query; }
@ -919,7 +917,6 @@ class NeedsFourQueries {
directives: [NgFor], directives: [NgFor],
template: '<ng-content></ng-content><div *ngFor="let dir of query">{{dir.text}}|</div>' template: '<ng-content></ng-content><div *ngFor="let dir of query">{{dir.text}}|</div>'
}) })
@Injectable()
class NeedsQueryDesc { class NeedsQueryDesc {
query: QueryList<TextDirective>; query: QueryList<TextDirective>;
constructor(@Query(TextDirective, {descendants: true}) 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>'}) @Component({selector: 'needs-query-by-ref-binding', directives: [], template: '<ng-content>'})
@Injectable()
class NeedsQueryByLabel { class NeedsQueryByLabel {
query: QueryList<any>; query: QueryList<any>;
constructor(@Query('textLabel', {descendants: true}) query: QueryList<any>) { constructor(@Query('textLabel', {descendants: true}) query: QueryList<any>) {
@ -941,14 +937,12 @@ class NeedsQueryByLabel {
directives: [], directives: [],
template: '<div #textLabel>text</div>' template: '<div #textLabel>text</div>'
}) })
@Injectable()
class NeedsViewQueryByLabel { class NeedsViewQueryByLabel {
query: QueryList<any>; query: QueryList<any>;
constructor(@ViewQuery('textLabel') query: QueryList<any>) { this.query = query; } constructor(@ViewQuery('textLabel') query: QueryList<any>) { this.query = query; }
} }
@Component({selector: 'needs-query-by-ref-bindings', directives: [], template: '<ng-content>'}) @Component({selector: 'needs-query-by-ref-bindings', directives: [], template: '<ng-content>'})
@Injectable()
class NeedsQueryByTwoLabels { class NeedsQueryByTwoLabels {
query: QueryList<any>; query: QueryList<any>;
constructor(@Query('textLabel1,textLabel2', {descendants: true}) query: QueryList<any>) { constructor(@Query('textLabel1,textLabel2', {descendants: true}) query: QueryList<any>) {
@ -961,7 +955,6 @@ class NeedsQueryByTwoLabels {
directives: [NgFor], directives: [NgFor],
template: '<div *ngFor="let dir of query">{{dir.text}}|</div><ng-content></ng-content>' template: '<div *ngFor="let dir of query">{{dir.text}}|</div><ng-content></ng-content>'
}) })
@Injectable()
class NeedsQueryAndProject { class NeedsQueryAndProject {
query: QueryList<TextDirective>; query: QueryList<TextDirective>;
constructor(@Query(TextDirective) query: QueryList<TextDirective>) { this.query = query; } constructor(@Query(TextDirective) query: QueryList<TextDirective>) { this.query = query; }
@ -973,7 +966,6 @@ class NeedsQueryAndProject {
template: '<div text="1"><div text="2"></div></div>' + template: '<div text="1"><div text="2"></div></div>' +
'<div text="3"></div><div text="4"></div>' '<div text="3"></div><div text="4"></div>'
}) })
@Injectable()
class NeedsViewQuery { class NeedsViewQuery {
query: QueryList<TextDirective>; query: QueryList<TextDirective>;
constructor(@ViewQuery(TextDirective) query: QueryList<TextDirective>) { this.query = query; } constructor(@ViewQuery(TextDirective) query: QueryList<TextDirective>) { this.query = query; }
@ -984,7 +976,6 @@ class NeedsViewQuery {
directives: [NgIf, TextDirective], directives: [NgIf, TextDirective],
template: '<div *ngIf="show" text="1"></div>' template: '<div *ngIf="show" text="1"></div>'
}) })
@Injectable()
class NeedsViewQueryIf { class NeedsViewQueryIf {
show: boolean; show: boolean;
query: QueryList<TextDirective>; query: QueryList<TextDirective>;
@ -1000,7 +991,6 @@ class NeedsViewQueryIf {
directives: [NgIf, InertDirective, TextDirective], directives: [NgIf, InertDirective, TextDirective],
template: '<div text="1"><div *ngIf="show"><div dir></div></div></div>' template: '<div text="1"><div *ngIf="show"><div dir></div></div></div>'
}) })
@Injectable()
class NeedsViewQueryNestedIf { class NeedsViewQueryNestedIf {
show: boolean; show: boolean;
query: QueryList<TextDirective>; query: QueryList<TextDirective>;
@ -1017,7 +1007,6 @@ class NeedsViewQueryNestedIf {
'<div *ngFor="let i of list" [text]="i"></div>' + '<div *ngFor="let i of list" [text]="i"></div>' +
'<div text="4"></div>' '<div text="4"></div>'
}) })
@Injectable()
class NeedsViewQueryOrder { class NeedsViewQueryOrder {
query: QueryList<TextDirective>; query: QueryList<TextDirective>;
list: string[]; list: string[];
@ -1034,7 +1023,6 @@ class NeedsViewQueryOrder {
'<div *ngFor="let i of list" [text]="i"></div>' + '<div *ngFor="let i of list" [text]="i"></div>' +
'<div text="4"></div></div>' '<div text="4"></div></div>'
}) })
@Injectable()
class NeedsViewQueryOrderWithParent { class NeedsViewQueryOrderWithParent {
query: QueryList<TextDirective>; query: QueryList<TextDirective>;
list: string[]; list: string[];
@ -1143,7 +1131,6 @@ class HasNullQueryCondition {
], ],
template: '' template: ''
}) })
@Injectable()
class MyComp0 { class MyComp0 {
shouldShow: boolean; shouldShow: boolean;
list: any /** TODO #9100 */; list: any /** TODO #9100 */;
@ -1154,6 +1141,5 @@ class MyComp0 {
} }
@Component({selector: 'my-comp', directives: [HasNullQueryCondition], template: ''}) @Component({selector: 'my-comp', directives: [HasNullQueryCondition], template: ''})
@Injectable()
class MyCompBroken0 { class MyCompBroken0 {
} }

View File

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

View File

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

View File

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