fix(ivy): injecting optional TemplateRef on element should not throw (#26664)

PR Close #26664
This commit is contained in:
Kara Erickson
2018-10-25 11:18:49 -07:00
committed by Matias Niemelä
parent d2e6d6978e
commit d52d82d744
4 changed files with 79 additions and 25 deletions

View File

@ -23,8 +23,6 @@ import {assertNodeOfPossibleTypes} from './node_assert';
import {getPreviousOrParentTNode, getViewData, setTNodeAndViewData} from './state';
import {getParentInjectorIndex, getParentInjectorView, getParentInjectorViewOffset, hasParentInjector, isComponent, stringify} from './util';
/**
* Defines if the call to `inject` should include `viewProviders` in its resolution.
*
@ -300,7 +298,12 @@ export function getOrCreateInjectable<T>(
const saveViewData = getViewData();
setTNodeAndViewData(tNode, lViewData);
try {
return bloomHash();
const value = bloomHash();
if (value == null && !(flags & InjectFlags.Optional)) {
throw new Error(`No provider for ${stringify(token)}`);
} else {
return value;
}
} finally {
setTNodeAndViewData(savePreviousOrParentTNode, saveViewData);
}

View File

@ -77,7 +77,7 @@ let R3TemplateRef: {
*/
export function injectTemplateRef<T>(
TemplateRefToken: typeof ViewEngine_TemplateRef,
ElementRefToken: typeof ViewEngine_ElementRef): ViewEngine_TemplateRef<T> {
ElementRefToken: typeof ViewEngine_ElementRef): ViewEngine_TemplateRef<T>|null {
return createTemplateRef<T>(
TemplateRefToken, ElementRefToken, getPreviousOrParentTNode(), getViewData());
}
@ -93,7 +93,7 @@ export function injectTemplateRef<T>(
*/
export function createTemplateRef<T>(
TemplateRefToken: typeof ViewEngine_TemplateRef, ElementRefToken: typeof ViewEngine_ElementRef,
hostTNode: TNode, hostView: LViewData): ViewEngine_TemplateRef<T> {
hostTNode: TNode, hostView: LViewData): ViewEngine_TemplateRef<T>|null {
if (!R3TemplateRef) {
// TODO: Fix class name, should be TemplateRef, but there appears to be a rollup bug
R3TemplateRef = class TemplateRef_<T> extends TemplateRefToken<T> {
@ -122,12 +122,15 @@ export function createTemplateRef<T>(
};
}
const hostContainer: LContainer = hostView[hostTNode.index];
ngDevMode && assertNodeType(hostTNode, TNodeType.Container);
ngDevMode && assertDefined(hostTNode.tViews, 'TView must be allocated');
return new R3TemplateRef(
hostView, createElementRef(ElementRefToken, hostTNode, hostView), hostTNode.tViews as TView,
getRenderer(), hostContainer[QUERIES], hostTNode.injectorIndex);
if (hostTNode.type === TNodeType.Container) {
const hostContainer: LContainer = hostView[hostTNode.index];
ngDevMode && assertDefined(hostTNode.tViews, 'TView must be allocated');
return new R3TemplateRef(
hostView, createElementRef(ElementRefToken, hostTNode, hostView), hostTNode.tViews as TView,
getRenderer(), hostContainer[QUERIES], hostTNode.injectorIndex);
} else {
return null;
}
}
let R3ViewContainerRef: {