From 67cf11d0710b898adabe0b126842ff99a8eee24f Mon Sep 17 00:00:00 2001 From: Trotyl Date: Sat, 17 Feb 2018 21:14:27 +0800 Subject: [PATCH] feat(common): better error message when non-template element used in NgIf (#22274) closes #16410 PR Close #22274 --- packages/common/src/directives/ng_if.ts | 11 +++++++++- packages/common/test/directives/ng_if_spec.ts | 22 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/packages/common/src/directives/ng_if.ts b/packages/common/src/directives/ng_if.ts index 07460feb3d..5b1a2b8543 100644 --- a/packages/common/src/directives/ng_if.ts +++ b/packages/common/src/directives/ng_if.ts @@ -6,7 +6,7 @@ * found in the LICENSE file at https://angular.io/license */ -import {Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef} from '@angular/core'; +import {Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef, ɵstringify as stringify} from '@angular/core'; /** @@ -118,6 +118,7 @@ export class NgIf { @Input() set ngIfThen(templateRef: TemplateRef) { + assertTemplate('ngIfThen', templateRef); this._thenTemplateRef = templateRef; this._thenViewRef = null; // clear previous view if any. this._updateView(); @@ -125,6 +126,7 @@ export class NgIf { @Input() set ngIfElse(templateRef: TemplateRef) { + assertTemplate('ngIfElse', templateRef); this._elseTemplateRef = templateRef; this._elseViewRef = null; // clear previous view if any. this._updateView(); @@ -163,3 +165,10 @@ export class NgIfContext { public $implicit: any = null; public ngIf: any = null; } + +function assertTemplate(property: string, templateRef: TemplateRef): void { + const isTemplateRef = templateRef.createEmbeddedView != null; + if (!isTemplateRef) { + throw new Error(`${property} must be a TemplateRef, but received '${stringify(templateRef)}'.`); + } +} diff --git a/packages/common/test/directives/ng_if_spec.ts b/packages/common/test/directives/ng_if_spec.ts index a7ac754601..ae8312146e 100644 --- a/packages/common/test/directives/ng_if_spec.ts +++ b/packages/common/test/directives/ng_if_spec.ts @@ -217,6 +217,28 @@ import {expect} from '@angular/platform-browser/testing/src/matchers'; expect(fixture.nativeElement).toHaveText('false'); })); }); + + describe('Type guarding', () => { + it('should throw when then block is not template', async(() => { + const template = 'IGNORE' + + '
THEN
'; + + fixture = createTestComponent(template); + + expect(() => fixture.detectChanges()) + .toThrowError(/ngIfThen must be a TemplateRef, but received/); + })); + + it('should throw when else block is not template', async(() => { + const template = 'IGNORE' + + '
ELSE
'; + + fixture = createTestComponent(template); + + expect(() => fixture.detectChanges()) + .toThrowError(/ngIfElse must be a TemplateRef, but received/); + })); + }); }); }