From bb2eda2d151092cdd318cbdbb6b22edc1dd39896 Mon Sep 17 00:00:00 2001 From: Jeremy Elbourn Date: Fri, 15 May 2015 16:10:16 -0700 Subject: [PATCH] feat(element_injector): allow @Optional for ProtoViewRef --- .../angular2/src/core/compiler/element_injector.js | 4 ++++ .../test/core/compiler/element_injector_spec.js | 13 +++++++++++++ 2 files changed, 17 insertions(+) diff --git a/modules/angular2/src/core/compiler/element_injector.js b/modules/angular2/src/core/compiler/element_injector.js index f46ff60e68..e2bfead4d4 100644 --- a/modules/angular2/src/core/compiler/element_injector.js +++ b/modules/angular2/src/core/compiler/element_injector.js @@ -851,6 +851,10 @@ export class ElementInjector extends TreeNode { } if (dep.key.id === StaticKeys.instance().protoViewId) { if (isBlank(this._preBuiltObjects.protoView)) { + if (dep.optional) { + return null; + } + throw new NoBindingError(dep.key); } return new ProtoViewRef(this._preBuiltObjects.protoView); diff --git a/modules/angular2/test/core/compiler/element_injector_spec.js b/modules/angular2/test/core/compiler/element_injector_spec.js index 0f50a8ec3a..470f745f78 100644 --- a/modules/angular2/test/core/compiler/element_injector_spec.js +++ b/modules/angular2/test/core/compiler/element_injector_spec.js @@ -150,6 +150,13 @@ class NeedsProtoViewRef { } } +class OptionallyInjectsProtoViewRef { + protoViewRef; + constructor(@Optional() ref:ProtoViewRef) { + this.protoViewRef = ref; + } +} + class NeedsChangeDetectorRef { changeDetectorRef; constructor(cdr:ChangeDetectorRef) { @@ -811,6 +818,12 @@ export function main() { () => injector([NeedsProtoViewRef]) ).toThrowError('No provider for ProtoViewRef! (NeedsProtoViewRef -> ProtoViewRef)'); }); + + it('should inject null if there is no ProtoViewRef when the dependency is optional', () => { + var inj = injector([OptionallyInjectsProtoViewRef]); + var instance = inj.get(OptionallyInjectsProtoViewRef); + expect(instance.protoViewRef).toBeNull(); + }); }); describe('directive queries', () => {