Skip to content

Commit bb2eda2

Browse files
committed
feat(element_injector): allow @optional for ProtoViewRef
1 parent 0114cd9 commit bb2eda2

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

modules/angular2/src/core/compiler/element_injector.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -851,6 +851,10 @@ export class ElementInjector extends TreeNode {
851851
}
852852
if (dep.key.id === StaticKeys.instance().protoViewId) {
853853
if (isBlank(this._preBuiltObjects.protoView)) {
854+
if (dep.optional) {
855+
return null;
856+
}
857+
854858
throw new NoBindingError(dep.key);
855859
}
856860
return new ProtoViewRef(this._preBuiltObjects.protoView);

modules/angular2/test/core/compiler/element_injector_spec.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,13 @@ class NeedsProtoViewRef {
150150
}
151151
}
152152

153+
class OptionallyInjectsProtoViewRef {
154+
protoViewRef;
155+
constructor(@Optional() ref:ProtoViewRef) {
156+
this.protoViewRef = ref;
157+
}
158+
}
159+
153160
class NeedsChangeDetectorRef {
154161
changeDetectorRef;
155162
constructor(cdr:ChangeDetectorRef) {
@@ -811,6 +818,12 @@ export function main() {
811818
() => injector([NeedsProtoViewRef])
812819
).toThrowError('No provider for ProtoViewRef! (NeedsProtoViewRef -> ProtoViewRef)');
813820
});
821+
822+
it('should inject null if there is no ProtoViewRef when the dependency is optional', () => {
823+
var inj = injector([OptionallyInjectsProtoViewRef]);
824+
var instance = inj.get(OptionallyInjectsProtoViewRef);
825+
expect(instance.protoViewRef).toBeNull();
826+
});
814827
});
815828

816829
describe('directive queries', () => {

0 commit comments

Comments
 (0)