Skip to content

Commit 67cf11d

Browse files
trotylvicb
authored andcommitted
feat(common): better error message when non-template element used in NgIf (#22274)
closes #16410 PR Close #22274
1 parent 49082d7 commit 67cf11d

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

packages/common/src/directives/ng_if.ts

+10-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
* found in the LICENSE file at https://angular.io/license
77
*/
88

9-
import {Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef} from '@angular/core';
9+
import {Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef, ɵstringify as stringify} from '@angular/core';
1010

1111

1212
/**
@@ -118,13 +118,15 @@ export class NgIf {
118118

119119
@Input()
120120
set ngIfThen(templateRef: TemplateRef<NgIfContext>) {
121+
assertTemplate('ngIfThen', templateRef);
121122
this._thenTemplateRef = templateRef;
122123
this._thenViewRef = null; // clear previous view if any.
123124
this._updateView();
124125
}
125126

126127
@Input()
127128
set ngIfElse(templateRef: TemplateRef<NgIfContext>) {
129+
assertTemplate('ngIfElse', templateRef);
128130
this._elseTemplateRef = templateRef;
129131
this._elseViewRef = null; // clear previous view if any.
130132
this._updateView();
@@ -163,3 +165,10 @@ export class NgIfContext {
163165
public $implicit: any = null;
164166
public ngIf: any = null;
165167
}
168+
169+
function assertTemplate(property: string, templateRef: TemplateRef<any>): void {
170+
const isTemplateRef = templateRef.createEmbeddedView != null;
171+
if (!isTemplateRef) {
172+
throw new Error(`${property} must be a TemplateRef, but received '${stringify(templateRef)}'.`);
173+
}
174+
}

packages/common/test/directives/ng_if_spec.ts

+22
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,28 @@ import {expect} from '@angular/platform-browser/testing/src/matchers';
217217
expect(fixture.nativeElement).toHaveText('false');
218218
}));
219219
});
220+
221+
describe('Type guarding', () => {
222+
it('should throw when then block is not template', async(() => {
223+
const template = '<span *ngIf="booleanCondition; then thenBlock">IGNORE</span>' +
224+
'<div #thenBlock>THEN</div>';
225+
226+
fixture = createTestComponent(template);
227+
228+
expect(() => fixture.detectChanges())
229+
.toThrowError(/ngIfThen must be a TemplateRef, but received/);
230+
}));
231+
232+
it('should throw when else block is not template', async(() => {
233+
const template = '<span *ngIf="booleanCondition; else elseBlock">IGNORE</span>' +
234+
'<div #elseBlock>ELSE</div>';
235+
236+
fixture = createTestComponent(template);
237+
238+
expect(() => fixture.detectChanges())
239+
.toThrowError(/ngIfElse must be a TemplateRef, but received/);
240+
}));
241+
});
220242
});
221243
}
222244

0 commit comments

Comments
 (0)