Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions packages/compiler-cli/src/ngtsc/typecheck/test/diagnostics_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,135 @@ runInEachFileSystem(() => {
]);
});

it('checks unclaimed property bindings on <ng-template>', () => {
// https://github.com/angular/angular/issues/69322
const messages = diagnose(
`<ng-template [auiTypedOption]="searchResult"></ng-template>`,
`
class TestComponent {
searchResult: {name: string};
}`,
);

expect(messages).toEqual([
`TestComponent.html(1, 14): Can't bind to 'auiTypedOption' since it isn't a known property of 'ng-template'.\n1. If 'auiTypedOption' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`,
]);
});

it('does not report a property bound to a matched directive on <ng-template>', () => {
const messages = diagnose(
`<ng-template [auiTypedOption]="searchResult"></ng-template>`,
`
class TypedOptionDirective {
auiTypedOption: any;
}
class TestComponent {
searchResult: {name: string};
}`,
[
{
type: 'directive',
name: 'TypedOptionDirective',
selector: 'ng-template[auiTypedOption]',
inputs: {auiTypedOption: 'auiTypedOption'},
},
],
);

expect(messages).toEqual([]);
});

it('does not report ngTemplateOutlet bound on <ng-template>', () => {
const messages = diagnose(
`<ng-template [ngTemplateOutlet]="tpl"></ng-template>`,
`
import {TemplateRef} from '@angular/core';
class NgTemplateOutlet {
ngTemplateOutlet: TemplateRef<unknown> | null;
}
class TestComponent {
tpl: TemplateRef<unknown> | null = null;
}`,
[
{
type: 'directive',
name: 'NgTemplateOutlet',
selector: '[ngTemplateOutlet]',
inputs: {ngTemplateOutlet: 'ngTemplateOutlet'},
},
],
);

expect(messages).toEqual([]);
});

it('does not report *ngIf expanded onto <ng-template>', () => {
const messages = diagnose(
`<ng-template [ngIf]="cond"></ng-template>`,
`
class TestComponent {
cond = true;
}`,
[ngIfDeclaration()],
[ngIfDts()],
);

expect(messages).toEqual([]);
});

it('does not report a *ngIf shorthand wrapping an element with its own bound property', () => {
// The `[id]` binding on the inner `div` is hoisted onto the synthetic wrapper `Template`
// node generated for the `*ngIf` shorthand. It must only be checked once, against `div`,
// not a second time against the synthetic wrapper.
const messages = diagnose(
`<div *ngIf="cond" [id]="elId"></div>`,
`
class TestComponent {
cond = true;
elId = 'foo';
}`,
[ngIfDeclaration()],
[ngIfDts()],
);

expect(messages).toEqual([]);
});

it('does not report a *ngIf shorthand wrapping a directive-claimed property that is unrelated to NgIf', () => {
// `[input]` is hoisted onto the synthetic wrapper `Template`, but is only claimed by `Dir`
// on the inner `div` -- not by `NgIf`. The wrapper's own directive match set (based only on
// the `ngIf`/`ngIfElse`-style template attributes) must not cause this to be misreported as
// an unclaimed binding on the wrapper.
const messages = diagnose(
`<div dir *ngIf="cond" [input]="value"></div>`,
`
class Dir {
input: string;
}
class TestComponent {
cond = true;
value = 'foo';
}`,
[
ngIfDeclaration(),
{type: 'directive', name: 'Dir', selector: '[dir]', inputs: {input: 'input'}},
],
[ngIfDts()],
);

expect(messages).toEqual([]);
});

it('does not report <ng-template let-x>', () => {
const messages = diagnose(
`<ng-template let-x="foo">{{x}}</ng-template>`,
`
class TestComponent {}`,
);

expect(messages).toEqual([]);
});

it('should disallow binding to event properties starting with on', () => {
const messages = diagnose(
`<div [onclick]="handler"></div>`,
Expand Down
55 changes: 55 additions & 0 deletions packages/compiler-cli/test/ngtsc/ngtsc_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5656,6 +5656,61 @@ runInEachFileSystem((os: string) => {
);
});

// https://github.com/angular/angular/issues/69322
it('should report a missing import for a directive applied on <ng-template>', () => {
env.write(
'test.ts',
`
import {Component, Directive, input, signal} from '@angular/core';

@Directive({selector: 'ng-template[auiTypedOption]'})
export class TypedOptionDirective {
auiTypedOption = input.required<any>();
}

@Component({
imports: [], // TypedOptionDirective is intentionally not imported.
template: '<ng-template [auiTypedOption]="searchResult()"></ng-template>',
})
export class TestCmp {
searchResult = signal({name: 'test'});
}
`,
);

const errors = env.driveDiagnostics();
expect(errors.length).toBe(1);
expect(errors[0].messageText).toContain(
`Can't bind to 'auiTypedOption' since it isn't a known property of 'ng-template'.`,
);
});

// https://github.com/angular/angular/issues/69322
it('should not report a directive applied on <ng-template> when it is imported', () => {
env.write(
'test.ts',
`
import {Component, Directive, input, signal} from '@angular/core';

@Directive({selector: 'ng-template[auiTypedOption]'})
export class TypedOptionDirective {
auiTypedOption = input.required<any>();
}

@Component({
imports: [TypedOptionDirective],
template: '<ng-template [auiTypedOption]="searchResult()"></ng-template>',
})
export class TestCmp {
searchResult = signal({name: 'test'});
}
`,
);

const errors = env.driveDiagnostics();
expect(errors.length).toBe(0);
});

it('should handle $any used inside a listener', () => {
env.write(
'test.ts',
Expand Down
7 changes: 6 additions & 1 deletion packages/compiler-cli/test/ngtsc/template_mapping_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -792,13 +792,15 @@ runInEachFileSystem((os) => {
import {Component, Directive, Input, Output, EventEmitter, Pipe, NgModule} from '@angular/core';

@Directive({
selector: '[ngModel],[attr],[ngModelChange]',
selector: '[ngModel],[attr],[ngModelChange],[ngIf],[ngForOf]',
standalone: false,
})
export class AllDirective {
@Input() ngModel!: any;
@Output() ngModelChange = new EventEmitter<any>();
@Input() attr!: any;
@Input() ngIf!: any;
@Input() ngForOf!: any;
}

@Pipe({
Expand All @@ -817,6 +819,9 @@ runInEachFileSystem((os) => {
export class TestCmp {
name = '';
isInitial = false;
showMessage() {
return true;
}
doSomething() {}
items: any[] = [];
greeting = '';
Expand Down
21 changes: 16 additions & 5 deletions packages/compiler/src/typecheck/ops/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import {BindingType} from '../../expression_parser/ast';
import {Component, Element, HostElement} from '../../render3/r3_ast';
import {Component, Element, HostElement, Template} from '../../render3/r3_ast';
import {DomElementSchemaRegistry} from '../../schema/dom_element_schema_registry';
const REGISTRY = new DomElementSchemaRegistry();
import {TcbOp} from './base';
Expand All @@ -28,7 +28,7 @@ import {getComponentTagName} from './selectorless';
export class TcbDomSchemaCheckerOp extends TcbOp {
constructor(
private tcb: Context,
private element: Element | Component | HostElement,
private element: Element | Component | Template | HostElement,
private checkElement: boolean,
private claimedInputs: Set<string> | null,
) {
Expand All @@ -41,7 +41,8 @@ export class TcbDomSchemaCheckerOp extends TcbOp {

override execute(): TcbExpr | null {
const element = this.element;
const isTemplateElement = element instanceof Element || element instanceof Component;
const isTemplateElement =
element instanceof Element || element instanceof Component || element instanceof Template;
const bindings = isTemplateElement ? element.inputs : element.bindings;

if (this.checkElement && isTemplateElement) {
Expand Down Expand Up @@ -91,7 +92,17 @@ export class TcbDomSchemaCheckerOp extends TcbOp {
return null;
}

private getTagName(node: Element | Component): string {
return node instanceof Element ? node.name : getComponentTagName(node);
private getTagName(node: Element | Component | Template): string {
if (node instanceof Element) {
return node.name;
} else if (node instanceof Template) {
// `tagName` is `null` for synthetic `Template` nodes generated for structural directive
// shorthand (e.g. `<div *ngIf="cond">`). Such nodes are never passed to this op with
// `isTemplateElement` bindings of their own to check (see `appendDirectivesAndInputsOfElementLikeNode`),
// but fall back to `ng-template` for safety.
return node.tagName ?? 'ng-template';
} else {
return getComponentTagName(node);
}
}
}
51 changes: 42 additions & 9 deletions packages/compiler/src/typecheck/ops/scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,20 @@ export class Scope {
}
}

/**
* Whether `node` is a literal `<ng-template>` element written directly in the template, as
* opposed to a synthetic `Template` node generated for structural directive shorthand (e.g.
* `<div *ngIf="cond">`, whose `tagName` is `'div'`, or `<ng-template *ngIf="cond">`, whose
* `tagName` is `null`).
*
* Property bindings on synthetic `Template` nodes are hoisted copies of bindings that already
* live (and are separately checked) on the wrapped element, so they must not be treated as
* unclaimed inputs of the wrapper itself. See https://github.com/angular/angular/issues/69322.
*/
private isLiteralNgTemplate(node: Template): boolean {
return node.tagName === 'ng-template';
}

private appendDirectivesAndInputsOfElementLikeNode(node: Element | Template): void {
// Collect all the inputs on the element.
const claimedInputs = new Set<string>();
Expand All @@ -573,6 +587,18 @@ export class Scope {
new TcbDomSchemaCheckerOp(this.tcb, node, /* checkElement */ true, claimedInputs),
);
}
} else if (node instanceof Template && this.isLiteralNgTemplate(node)) {
// A literal `<ng-template>` (as opposed to a synthetic `Template` generated for
// structural directive shorthand, e.g. `<div *ngIf="cond">`) behaves like an element for
// the purposes of unclaimed property bindings: `<ng-template [foo]="bar">` should be
// reported the same way `<div [foo]="bar">` would be if no directive claims `foo`.
// See https://github.com/angular/angular/issues/69322.
this.opQueue.push(
new TcbUnclaimedInputsOp(this.tcb, this, node.inputs, node, claimedInputs),
);
this.opQueue.push(
new TcbDomSchemaCheckerOp(this.tcb, node, /* checkElement */ false, claimedInputs),
);
}
return;
}
Expand Down Expand Up @@ -633,7 +659,7 @@ export class Scope {

// After expanding the directives, we might need to queue an operation to check any unclaimed
// inputs.
if (node instanceof Element) {
if (node instanceof Element || (node instanceof Template && this.isLiteralNgTemplate(node))) {
// Go through the directives and remove any inputs that it claims from `elementInputs`.
for (const dir of directives) {
for (const propertyName of dir.inputs.propertyNames) {
Expand All @@ -645,8 +671,10 @@ export class Scope {
// If there are no directives which match this element, then it's a "plain" DOM element (or a
// web component), and should be checked against the DOM schema. If any directives match,
// we must assume that the element could be custom (either a component, or a directive like
// <router-outlet>) and shouldn't validate the element name itself.
const checkElement = directives.length === 0;
// <router-outlet>) and shouldn't validate the element name itself. `<ng-template>` itself is
// always a known element, so `checkElement` is irrelevant for `Template` nodes (see
// `TcbDomSchemaCheckerOp`, which only checks the element name for `Element`/`Component`).
const checkElement = node instanceof Element && directives.length === 0;
this.opQueue.push(new TcbDomSchemaCheckerOp(this.tcb, node, checkElement, claimedInputs));
}
}
Expand Down Expand Up @@ -853,7 +881,7 @@ export class Scope {
continue;
}

if (node instanceof Element) {
if (node instanceof Element || this.isLiteralNgTemplate(node)) {
const claimedInputs = new Set<string>();
let directives = this.tcb.boundTarget.getDirectivesOfNode(node);

Expand All @@ -877,11 +905,16 @@ export class Scope {
}
}
}
const isForeign = this.tcb.boundTarget.getForeignComponent(node) !== null;
if (!isForeign) {
this.opQueue.push(
new TcbDomSchemaCheckerOp(this.tcb, node, !hasDirectives, claimedInputs),
);
if (node instanceof Element) {
const isForeign = this.tcb.boundTarget.getForeignComponent(node) !== null;
if (!isForeign) {
this.opQueue.push(
new TcbDomSchemaCheckerOp(this.tcb, node, !hasDirectives, claimedInputs),
);
}
} else {
// `<ng-template>` itself is always a known element; `checkElement` is not applicable.
this.opQueue.push(new TcbDomSchemaCheckerOp(this.tcb, node, false, claimedInputs));
}
}

Expand Down