id
stringlengths 6
6
| text
stringlengths 20
17.2k
| title
stringclasses 1
value |
|---|---|---|
010894
|
it('should migrate if/else with let variable in wrong place with no semicolons', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
user$ = of({ name: 'Jane' }})
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<div *ngIf="user of users; let tooltipContent else noUserBlock">{{ user.name }}</div>`,
`<ng-template #noUserBlock>No user</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (user of users; as tooltipContent) {`,
` <div>{{ user.name }}</div>`,
` } @else {`,
` No user`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate if/then/else with alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
user$ = of({ name: 'Jane' }})
}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
`<ng-container *ngIf="user$ | async as user; then userBlock; else noUserBlock">Ignored</ng-container>`,
`<ng-template #userBlock>User</ng-template>`,
`<ng-template #noUserBlock>No user</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @if (user$ | async; as user) {`,
` User`,
` } @else {`,
` No user`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate a nested class', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
function foo() {
@Component({
imports: [NgIf],
template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\`
})
class Comp {
toggle = false;
}
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@if (toggle) {<span>This should be hidden</span>}</div>`',
);
});
it('should migrate a nested class', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
function foo() {
@Component({
imports: [NgIf],
template: \`<div><span *ngIf="toggle">This should be hidden</span></div>\`
})
class Comp {
toggle = false;
}
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@if (toggle) {<span>This should be hidden</span>}</div>`',
);
});
});
| |
010895
|
describe('ngFor', () => {
it('should migrate an inline template', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let item of items">{{item.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (item of items; track item) {<li>{{item.text}}</li>}</ul>`',
);
});
it('should migrate multiple inline templates in the same file', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
const items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let item of items">{{item.text}}</li></ul>\`
})
class Comp {
items: Item[] = s;
}
@Component({
imports: [NgFor],
template: \`<article><div *ngFor="let item of items">{{item.text}}</div></article>\`
})
class OtherComp {
items: Item[] = s;
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (item of items; track item) {<li>{{item.text}}</li>}</ul>`',
);
expect(content).toContain(
'template: `<article>@for (item of items; track item) {<div>{{item.text}}</div>}</article>`',
);
});
it('should migrate an external template', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
interface Item {
id: number;
text: string;
}
const items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
@Component({
templateUrl: './comp.html'
})
class Comp {
items: Item[] = s;
}
`,
);
writeFile(
'/comp.html',
[`<ul>`, `<li *ngFor="let item of items">{{item.text}}</li>`, `</ul>`].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<ul>`,
` @for (item of items; track item) {`,
` <li>{{item.text}}</li>`,
` }`,
`</ul>`,
].join('\n'),
);
});
it('should migrate a template referenced by multiple components', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
interface Item {
id: number;
text: string;
}
const items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
@Component({
templateUrl: './comp.html'
})
class Comp {
items: Item[] = s;
}
`,
);
writeFile(
'/other-comp.ts',
`
import {Component} from '@angular/core';
interface Item {
id: number;
text: string;
}
const items: Item[] = [{id: 3, text: 'things'},{id: 4, text: 'yup'}];
@Component({
templateUrl: './comp.html'
})
class OtherComp {
items: Item[] = s;
}
`,
);
writeFile(
'/comp.html',
[`<ul>`, `<li *ngFor="let item of items">{{item.text}}</li>`, `</ul>`].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<ul>`,
` @for (item of items; track item) {`,
` <li>{{item.text}}</li>`,
` }`,
`</ul>`,
].join('\n'),
);
});
it('should migrate with a trackBy function', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; trackBy: trackMeFn;">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track trackMeFn($index, itm)) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should migrate with an index alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; let index = index">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let index = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should migrate with a comma-separated index alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items, let index = index">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let index = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
| |
010896
|
it('should migrate with an old style alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <tr *ngFor="let row of field(); let y = index; trackBy: trackByIndex">`,
` <td`,
` *ngFor="let cell of row; let x = index; trackBy: trackByIndex"`,
` ></td>`,
` </tr>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (row of field(); track trackByIndex(y, row); let y = $index) {`,
` <tr>`,
` @for (cell of row; track trackByIndex(x, cell); let x = $index) {`,
` <td`,
` ></td>`,
` }`,
` </tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate an index alias after an expression containing commas', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of foo({a: 1, b: 2}, [1, 2]), let index = index">{{itm.text}}</li></ul>\`
})
class Comp {}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of foo({a: 1, b: 2}, [1, 2]); track itm; let index = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should migrate with an index alias with no spaces', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; let index=index">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let index = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should migrate with alias declared with as', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; index as myIndex">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let myIndex = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should migrate with alias declared with a comma-separated `as` expression', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items, index as myIndex">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let myIndex = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should not generate aliased variables declared via the `as` syntax with the same name as the original', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<div *ngFor="let item of items; index as $index;">{{$index}}</div>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'}, {id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `@for (item of items; track item) {<div>{{$index}}</div>}`',
);
});
it('should not generate aliased variables declared via the `let` syntax with the same name as the original', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<div *ngFor="let item of items; let $index = index">{{$index}}</div>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'}, {id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `@for (item of items; track item) {<div>{{$index}}</div>}`',
);
});
it('should migrate with a trackBy function and an aliased index', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; trackBy: trackMeFn; index as i">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track trackMeFn(i, itm); let i = $index) {<li>{{itm.text}}</li>}</ul>`',
);
});
| |
010897
|
it('should migrate with multiple aliases', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of items; let count = count; let first = first; let last = last; let ev = even; let od = odd;">{{itm.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (itm of items; track itm; let count = $count; let first = $first; let last = $last; let ev = $even; let od = $odd) {<li>{{itm.text}}</li>}</ul>`',
);
});
it('should remove unneeded ng-containers', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ng-container *ngFor="let item of items"><p>{{item.text}}</p></ng-container>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `@for (item of items; track item) {<p>{{item.text}}</p>}`',
);
});
it('should leave ng-containers with additional attributes', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
template: \`<ng-container *ngFor="let item of items" [bindMe]="stuff"><p>{{item.text}}</p></ng-container>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `@for (item of items; track item) {<ng-container [bindMe]="stuff"><p>{{item.text}}</p></ng-container>}`',
);
});
it('should migrate a nested class', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
function foo() {
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let item of items">{{item.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (item of items; track item) {<li>{{item.text}}</li>}</ul>`',
);
});
it('should migrate a nested class', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
function foo() {
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let item of items">{{item.text}}</li></ul>\`
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<ul>@for (item of items; track item) {<li>{{item.text}}</li>}</ul>`',
);
});
it('should migrate an ngFor with quoted semicolon in expression', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of '1;2;3'">{{itm}}</li></ul>\`
})
class Comp {}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
"template: `<ul>@for (itm of '1;2;3'; track itm) {<li>{{itm}}</li>}</ul>`",
);
});
it('should migrate an ngFor with quoted semicolon in expression', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
@Component({
imports: [NgFor],
template: \`<ul><li *ngFor="let itm of '1,2,3'">{{itm}}</li></ul>\`
})
class Comp {}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
"template: `<ul>@for (itm of '1,2,3'; track itm) {<li>{{itm}}</li>}</ul>`",
);
});
it('should migrate ngForTemplate', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<ng-container *ngFor="let item of things; template: itemTemplate"></ng-container>`,
`<ng-container *ngFor="let item of items; template: itemTemplate"></ng-container>`,
`<ng-template #itemTemplate let-item>`,
` <p>Stuff</p>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`@for (item of things; track item) {`,
` <ng-container *ngTemplateOutlet="itemTemplate; context: {$implicit: item}"></ng-container>`,
`}`,
`@for (item of items; track item) {`,
` <ng-container *ngTemplateOutlet="itemTemplate; context: {$implicit: item}"></ng-container>`,
`}`,
`<ng-template #itemTemplate let-item>`,
` <p>Stuff</p>`,
`</ng-template>`,
].join('\n');
expect(actual).toBe(expected);
});
| |
010898
|
it('should migrate ngForTemplate when template is only used once', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<ng-container *ngFor="let item of items; template: itemTemplate"></ng-container>`,
`<ng-template #itemTemplate let-item>`,
` <p>Stuff</p>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [`@for (item of items; track item) {`, ` <p>Stuff</p>`, `}\n`].join('\n');
expect(actual).toBe(expected);
});
});
| |
010899
|
describe('ngForOf', () => {
it('should migrate a basic ngForOf', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <ng-template ngFor let-rowData [ngForOf]="things">`,
` <tr><td>{{rowData}}</td></tr>`,
` </ng-template>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (rowData of things; track rowData) {`,
` <tr><td>{{rowData}}</td></tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate ngForOf with an alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <ng-template ngFor let-rowData let-rowIndex="index" [ngForOf]="things">`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` </ng-template>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (rowData of things; track rowData; let rowIndex = $index) {`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate ngForOf with track by', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <ng-template ngFor let-rowData [ngForOf]="things" [ngForTrackBy]="trackMe">`,
` <tr><td>{{rowData}}</td></tr>`,
` </ng-template>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (rowData of things; track trackMe($index, rowData)) {`,
` <tr><td>{{rowData}}</td></tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate ngForOf with track by and alias', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <ng-template ngFor let-rowData let-rowIndex="index" [ngForOf]="things" [ngForTrackBy]="trackMe">`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` </ng-template>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (rowData of things; track trackMe(rowIndex, rowData); let rowIndex = $index) {`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate ngFor with a long ternary and trackby', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<div`,
` *ngFor="`,
` let item of section === 'manage'`,
` ? filteredPermissions?.manage`,
` : section === 'customFields'`,
` ? filteredPermissions?.customFields`,
` : section === 'createAndDelete'`,
` ? filteredPermissions?.createAndDelete`,
` : filteredPermissions?.team;`,
` trackBy: trackById`,
` "`,
`>`,
` {{ item }}`,
`</div>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`@for (`,
` item of section === 'manage'`,
` ? filteredPermissions?.manage`,
` : section === 'customFields'`,
` ? filteredPermissions?.customFields`,
` : section === 'createAndDelete'`,
` ? filteredPermissions?.createAndDelete`,
` : filteredPermissions?.team; track trackById($index,`,
` item)) {`,
` <div`,
` >`,
` {{ item }}`,
` </div>`,
`}`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate ngForOf with track by and multiple aliases', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor,NgForOf],
templateUrl: 'comp.html',
})
class Comp {
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<tbody>`,
` <ng-template ngFor let-rowData let-rowIndex="index" let-rCount="count" [ngForOf]="things" [ngForTrackBy]="trackMe">`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` </ng-template>`,
`</tbody>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<tbody>`,
` @for (rowData of things; track trackMe(rowIndex, rowData); let rowIndex = $index; let rCount = $count) {`,
` <tr><td>{{rowIndex}}</td><td>{{rowData}}</td></tr>`,
` }`,
`</tbody>`,
].join('\n');
expect(actual).toBe(expected);
});
});
| |
010900
|
describe('ngSwitch', () => {
it('should migrate an inline template', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
template: \`<div [ngSwitch]="testOpts">` +
`<p *ngSwitchCase="1">Option 1</p>` +
`<p *ngSwitchCase="2">Option 2</p>` +
`</div>\`
})
class Comp {
testOpts = "1";
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>',
);
});
it('should migrate multiple inline templates in the same file', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
template: \`<div [ngSwitch]="testOpts">` +
`<p *ngSwitchCase="1">Option 1</p>` +
`<p *ngSwitchCase="2">Option 2</p>` +
`</div>\`
})
class Comp1 {
testOpts = "1";
}
@Component({
template: \`<div [ngSwitch]="choices">` +
`<p *ngSwitchCase="A">Choice A</p>` +
`<p *ngSwitchCase="B">Choice B</p>` +
`<p *ngSwitchDefault>Choice Default</p>` +
`</div>\`
})
class Comp2 {
choices = "C";
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>`',
);
expect(content).toContain(
'template: `<div>@switch (choices) { @case (A) { <p>Choice A</p> } @case (B) { <p>Choice B</p> } @default { <p>Choice Default</p> }}</div>`',
);
});
it('should migrate an external template', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
@Component({
templateUrl: './comp.html'
})
class Comp {
testOpts = 2;
}
`,
);
writeFile(
'/comp.html',
[
`<div [ngSwitch]="testOpts">`,
`<p *ngSwitchCase="1">Option 1</p>`,
`<p *ngSwitchCase="2">Option 2</p>`,
`<p *ngSwitchDefault>Option 3</p>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @switch (testOpts) {`,
` @case (1) {`,
` <p>Option 1</p>`,
` }`,
` @case (2) {`,
` <p>Option 2</p>`,
` }`,
` @default {`,
` <p>Option 3</p>`,
` }`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should migrate a template referenced by multiple components', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
testOpts = 2;
}
`,
);
writeFile(
'/other-comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class OtherComp {
testOpts = 1;
}
`,
);
writeFile(
'/comp.html',
[
`<div [ngSwitch]="testOpts">`,
`<p *ngSwitchCase="1">Option 1</p>`,
`<p *ngSwitchCase="2">Option 2</p>`,
`<p *ngSwitchDefault>Option 3</p>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @switch (testOpts) {`,
` @case (1) {`,
` <p>Option 1</p>`,
` }`,
` @case (2) {`,
` <p>Option 2</p>`,
` }`,
` @default {`,
` <p>Option 3</p>`,
` }`,
` }`,
`</div>`,
].join('\n'),
);
});
it('should remove unnecessary ng-containers', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
template: \`<div [ngSwitch]="testOpts">` +
`<ng-container *ngSwitchCase="1"><p>Option 1</p></ng-container>` +
`<ng-container *ngSwitchCase="2"><p>Option 2</p></ng-container>` +
`</div>\`
})
class Comp {
testOpts = "1";
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>',
);
});
it('should remove unnecessary ng-container on ngswitch', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
template: \`<div>` +
`<ng-container [ngSwitch]="testOpts">` +
`<p *ngSwitchCase="1">Option 1</p>` +
`<p *ngSwitchCase="2">Option 2</p>` +
`</ng-container>` +
`</div>\`
})
class Comp {
testOpts = "1";
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>',
);
});
it('should handle cases with missing star', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
template: \`<div [ngSwitch]="testOpts">` +
`<ng-template ngSwitchCase="1"><p>Option 1</p></ng-template>` +
`<ng-template ngSwitchCase="2"><p>Option 2</p></ng-template>` +
`<ng-template ngSwitchDefault><p>Option 3</p></ng-template>` +
`</div>\`
})
class Comp {
testOpts = "1";
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> } @default { <p>Option 3</p> }}</div>',
);
});
| |
010901
|
it('should handle cases with binding', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
template: \`<div [ngSwitch]="testOpts">` +
`<ng-template [ngSwitchCase]="1"><p>Option 1</p></ng-template>` +
`<ng-template [ngSwitchCase]="2"><p>Option 2</p></ng-template>` +
`<ng-template ngSwitchDefault><p>Option 3</p></ng-template>` +
`</div>\`
})
class Comp {
testOpts = "1";
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> } @default { <p>Option 3</p> }}</div>',
);
});
it('should handle empty default cases', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
testOpts = "1";
}
`,
);
writeFile(
'/comp.html',
[
`<ng-container [ngSwitch]="type">`,
`<ng-container *ngSwitchCase="'foo'"> Foo </ng-container>`,
`<ng-container *ngSwitchCase="'bar'"> Bar </ng-container>`,
`<ng-container *ngSwitchDefault></ng-container>`,
`</ng-container>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`\n@switch (type) {`,
` @case ('foo') {`,
` Foo`,
` }`,
` @case ('bar') {`,
` Bar`,
` }`,
` @default {`,
` }`,
`}\n`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate a nested class', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {ngSwitch, ngSwitchCase} from '@angular/common';
function foo() {
@Component({
template: \`<div [ngSwitch]="testOpts">` +
`<p *ngSwitchCase="1">Option 1</p>` +
`<p *ngSwitchCase="2">Option 2</p>` +
`</div>\`
})
class Comp {
testOpts = "1";
}
}
`,
);
await runMigration();
const content = tree.readContent('/comp.ts');
expect(content).toContain(
'template: `<div>@switch (testOpts) { @case (1) { <p>Option 1</p> } @case (2) { <p>Option 2</p> }}</div>`',
);
});
it('should migrate nested switches', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
imports: [NgFor, NgIf],
templateUrl: './comp.html'
})
class Comp {
show = false;
nest = true;
again = true;
more = true;
}`,
);
writeFile(
'/comp.html',
[
`<div [ngSwitch]="thing">`,
` <div *ngSwitchCase="'item'" [ngSwitch]="anotherThing">`,
` <img *ngSwitchCase="'png'" src="/img.png" alt="PNG" />`,
` <img *ngSwitchDefault src="/default.jpg" alt="default" />`,
` </div>`,
` <img *ngSwitchDefault src="/default.jpg" alt="default" />`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<div>`,
` @switch (thing) {`,
` @case ('item') {`,
` <div>`,
` @switch (anotherThing) {`,
` @case ('png') {`,
` <img src="/img.png" alt="PNG" />`,
` }`,
` @default {`,
` <img src="/default.jpg" alt="default" />`,
` }`,
` }`,
` </div>`,
` }`,
` @default {`,
` <img src="/default.jpg" alt="default" />`,
` }`,
` }`,
`</div>`,
].join('\n'),
);
});
});
| |
010903
|
it('should migrate a simple for inside an if', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
imports: [NgFor, NgIf],
templateUrl: './comp.html'
})
class Comp {
show = false;
nest = true;
again = true;
more = true;
}
`,
);
writeFile(
'/comp.html',
[
`<ul *ngIf="show">`,
`<li *ngFor="let h of heroes" [ngValue]="h">{{h.name}} ({{h.emotion}})</li>`,
`</ul>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (show) {`,
` <ul>`,
` @for (h of heroes; track h) {`,
` <li [ngValue]="h">{{h.name}} ({{h.emotion}})</li>`,
` }`,
` </ul>`,
`}`,
].join('\n'),
);
});
it('should migrate an if inside a for loop', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
imports: [NgFor, NgIf],
templateUrl: './comp.html'
})
class Comp {
heroes = [{name: 'cheese', emotion: 'happy'},{name: 'stuff', emotion: 'sad'}];
show = true;
}
`,
);
writeFile(
'/comp.html',
[
`<select id="hero">`,
`<span *ngFor="let h of heroes">`,
`<span *ngIf="show">`,
`<option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>`,
`</span>`,
`</span>`,
`</select>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<select id="hero">`,
` @for (h of heroes; track h) {`,
` <span>`,
` @if (show) {`,
` <span>`,
` <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>`,
` </span>`,
` }`,
` </span>`,
` }`,
`</select>`,
].join('\n'),
);
});
it('should migrate an if inside a for loop with ng-containers', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
imports: [NgFor, NgIf],
templateUrl: './comp.html'
})
class Comp {
heroes = [{name: 'cheese', emotion: 'happy'},{name: 'stuff', emotion: 'sad'}];
show = true;
}
`,
);
writeFile(
'/comp.html',
[
`<select id="hero">`,
`<ng-container *ngFor="let h of heroes">`,
`<ng-container *ngIf="show">`,
`<option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>`,
`</ng-container>`,
`</ng-container>`,
`</select>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`<select id="hero">`,
` @for (h of heroes; track h) {`,
` @if (show) {`,
` <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option>`,
` }`,
` }`,
`</select>`,
].join('\n'),
);
});
it('should migrate an inline template with if and for loops', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf, NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor, NgIf],
templateUrl: './comp.html'
})
class Comp {
show = false;
nest = true;
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<div *ngIf="show">`,
`<ul *ngIf="nest">`,
`<li *ngFor="let item of items">{{item.text}}</li>`,
`</ul>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (show) {`,
` <div>`,
` @if (nest) {`,
` <ul>`,
` @for (item of items; track item) {`,
` <li>{{item.text}}</li>`,
` }`,
` </ul>`,
` }`,
` </div>`,
`}`,
].join('\n'),
);
});
it('should migrate template with if, else, and for loops', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf, NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor, NgIf],
templateUrl: './comp.html'
})
class Comp {
show = false;
nest = true;
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
}
`,
);
writeFile(
'/comp.html',
[
`<div *ngIf="show">`,
`<ul *ngIf="nest; else elseTmpl">`,
`<li *ngFor="let item of items">{{item.text}}</li>`,
`</ul>`,
`<ng-template #elseTmpl><p>Else content</p></ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (show) {`,
` <div>`,
` @if (nest) {`,
` <ul>`,
` @for (item of items; track item) {`,
` <li>{{item.text}}</li>`,
` }`,
` </ul>`,
` } @else {`,
` <p>Else content</p>`,
` }`,
` </div>`,
`}`,
].join('\n'),
);
});
| |
010904
|
it('should migrate an inline template with if, for loops, and switches', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf, NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor, NgIf],
templateUrl: './comp.html'
})
class Comp {
show = false;
nest = true;
again = true;
more = true;
items: Item[] = [{id: 1, text: 'blah'},{id: 2, text: 'stuff'}];
testOpts = 2;
}
`,
);
writeFile(
'/comp.html',
[
`<div *ngIf="show">`,
`<div *ngIf="again">`,
`<div *ngIf="more">`,
`<div [ngSwitch]="testOpts">`,
`<p *ngSwitchCase="1">Option 1</p>`,
`<p *ngSwitchCase="2">Option 2</p>`,
`<p *ngSwitchDefault>Option 3</p>`,
`</div>`,
`</div>`,
`</div>`,
`<ul *ngIf="nest">`,
`<li *ngFor="let item of items">{{item.text}}</li>`,
`</ul>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (show) {`,
` <div>`,
` @if (again) {`,
` <div>`,
` @if (more) {`,
` <div>`,
` <div>`,
` @switch (testOpts) {`,
` @case (1) {`,
` <p>Option 1</p>`,
` }`,
` @case (2) {`,
` <p>Option 2</p>`,
` }`,
` @default {`,
` <p>Option 3</p>`,
` }`,
` }`,
` </div>`,
` </div>`,
` }`,
` </div>`,
` }`,
` @if (nest) {`,
` <ul>`,
` @for (item of items; track item) {`,
` <li>{{item.text}}</li>`,
` }`,
` </ul>`,
` }`,
` </div>`,
`}`,
].join('\n'),
);
});
it('complicated case', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf, NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor, NgIf],
templateUrl: './comp.html'
})
class Comp {
}
`,
);
writeFile(
'/comp.html',
[
`<div class="docs-breadcrumb" *ngFor="let breadcrumb of breadcrumbItems()">`,
`<ng-container *ngIf="breadcrumb.path; else breadcrumbWithoutLinkTemplate">`,
`<ng-container *ngIf="breadcrumb.isExternal; else internalLinkTemplate">`,
`<a [href]="breadcrumb.path">{{ breadcrumb.label }}</a>`,
`</ng-container>`,
`<ng-template #internalLinkTemplate>`,
`<a [routerLink]="'/' + breadcrumb.path">{{ breadcrumb.label }}</a>`,
`</ng-template>`,
`</ng-container>`,
`<ng-template #breadcrumbWithoutLinkTemplate>`,
`<span>{{ breadcrumb.label }}</span>`,
`</ng-template>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
const result = [
`@for (breadcrumb of breadcrumbItems(); track breadcrumb) {`,
` <div class="docs-breadcrumb">`,
` @if (breadcrumb.path) {`,
` @if (breadcrumb.isExternal) {`,
` <a [href]="breadcrumb.path">{{ breadcrumb.label }}</a>`,
` } @else {`,
` <a [routerLink]="'/' + breadcrumb.path">{{ breadcrumb.label }}</a>`,
` }`,
` } @else {`,
` <span>{{ breadcrumb.label }}</span>`,
` }`,
` </div>`,
`}`,
].join('\n');
expect(content).toBe(result);
});
| |
010905
|
it('long file', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf, NgFor} from '@angular/common';
interface Item {
id: number;
text: string;
}
@Component({
imports: [NgFor, NgIf],
templateUrl: './comp.html'
})
class Comp {
}
`,
);
writeFile(
'/comp.html',
[
`<div class="class">`,
`<iframe `,
`#preview `,
`class="special-class" `,
`*ngIf="stuff" `,
`></iframe>`,
`<ng-container *ngIf="shouldDoIt">`,
`<ng-container `,
`*ngComponentOutlet="outletComponent; inputs: {errorMessage: errorMessage()}" `,
`/>`,
`</ng-container>`,
`<div `,
`class="what"`,
`*ngIf="`,
`shouldWhat`,
`"`,
`>`,
`<ng-container [ngSwitch]="currentCase()">`,
`<span `,
`class="case-stuff"`,
`*ngSwitchCase="A"`,
`>`,
`Case A`,
`</span>`,
`<span class="b-class" *ngSwitchCase="B">`,
`Case B`,
`</span>`,
`<span `,
`class="thing-1" `,
`*ngSwitchCase="C" `,
`>`,
`Case C`,
`</span>`,
`<span `,
`class="thing-2"`,
`*ngSwitchCase="D"`,
`>`,
`Case D`,
`</span>`,
`<span `,
`class="thing-3" `,
`*ngSwitchCase="E" `,
`>`,
`Case E`,
`</span>`,
`</ng-container>`,
`<progress [value]="progress()" [max]="ready"></progress>`,
`</div>`,
`</div>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
const result = [
`<div class="class">`,
` @if (stuff) {`,
` <iframe`,
` #preview`,
` class="special-class"`,
` ></iframe>`,
` }`,
` @if (shouldDoIt) {`,
` <ng-container`,
` *ngComponentOutlet="outletComponent; inputs: {errorMessage: errorMessage()}"`,
` />`,
` }`,
` @if (`,
` shouldWhat`,
` ) {`,
` <div`,
` class="what"`,
` >`,
` @switch (currentCase()) {`,
` @case (A) {`,
` <span`,
` class="case-stuff"`,
` >`,
` Case A`,
` </span>`,
` }`,
` @case (B) {`,
` <span class="b-class">`,
` Case B`,
` </span>`,
` }`,
` @case (C) {`,
` <span`,
` class="thing-1"`,
` >`,
` Case C`,
` </span>`,
` }`,
` @case (D) {`,
` <span`,
` class="thing-2"`,
` >`,
` Case D`,
` </span>`,
` }`,
` @case (E) {`,
` <span`,
` class="thing-3"`,
` >`,
` Case E`,
` </span>`,
` }`,
` }`,
` <progress [value]="progress()" [max]="ready"></progress>`,
` </div>`,
` }`,
`</div>`,
].join('\n');
expect(content).toBe(result);
});
it('should handle empty cases safely without offset issues', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
selector: 'declare-comp',
templateUrl: 'comp.html',
})
class DeclareComp {}
`,
);
writeFile(
'/comp.html',
[
`<ng-container *ngIf="generic; else specific">`,
` <ng-container [ngSwitch]="dueWhen">`,
` <ng-container *ngSwitchCase="due.NOW">`,
` <p>Now></p>`,
` </ng-container>`,
` <ng-container *ngSwitchCase="due.SOON">`,
` <p>Soon></p>`,
` </ng-container>`,
` <ng-container *ngSwitchDefault></ng-container>`,
` </ng-container>`,
`</ng-container>`,
`<ng-template #specific>`,
` <ng-container [ngSwitch]="dueWhen">`,
` <ng-container *ngSwitchCase="due.NOW">`,
` <p>Now></p>`,
` </ng-container>`,
` <ng-container *ngSwitchCase="due.SOON">`,
` <p>Soon></p>`,
` </ng-container>`,
` <ng-container *ngSwitchDefault>`,
` <p>Default></p>`,
` </ng-container>`,
` </ng-container>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`@if (generic) {`,
` @switch (dueWhen) {`,
` @case (due.NOW) {`,
` <p>Now></p>`,
` }`,
` @case (due.SOON) {`,
` <p>Soon></p>`,
` }`,
` @default {`,
` }`,
` }`,
`} @else {`,
` @switch (dueWhen) {`,
` @case (due.NOW) {`,
` <p>Now></p>`,
` }`,
` @case (due.SOON) {`,
` <p>Soon></p>`,
` }`,
` @default {`,
` <p>Default></p>`,
` }`,
` }`,
`}\n`,
].join('\n');
expect(actual).toBe(expected);
});
});
| |
010908
|
it('should move templates after they were migrated to new syntax', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
selector: 'declare-comp',
templateUrl: 'comp.html',
})
class DeclareComp {}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
` <ng-container *ngIf="cond; else testTpl">`,
` bla bla`,
` </ng-container>`,
`</div>`,
`<ng-template #testTpl>`,
` <div class="test" *ngFor="let item of items"></div>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<div>`,
` @if (cond) {`,
` bla bla`,
` } @else {`,
` @for (item of items; track item) {`,
` <div class="test"></div>`,
` }`,
` }`,
`</div>\n`,
].join('\n');
expect(actual).toBe(expected);
});
it('should preserve i18n attribute on ng-templates in an if/else', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
selector: 'declare-comp',
templateUrl: 'comp.html',
})
class DeclareComp {}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
` <ng-container *ngIf="cond; else testTpl">`,
` bla bla`,
` </ng-container>`,
`</div>`,
`<ng-template #testTpl i18n="@@test_key">`,
` <div class="test" *ngFor="let item of items"></div>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<div>`,
` @if (cond) {`,
` bla bla`,
` } @else {`,
` <ng-container i18n="@@test_key">`,
` @for (item of items; track item) {`,
`<div class="test"></div>`,
`}`,
`</ng-container>`,
` }`,
`</div>\n`,
].join('\n');
expect(actual).toBe(expected);
});
it('should migrate multiple if/else using the same ng-template', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
selector: 'declare-comp',
templateUrl: 'comp.html',
})
class DeclareComp {}
`,
);
writeFile(
'/comp.html',
[
`<div>`,
` <div *ngIf="hasPermission; else noPermission">presentation</div>`,
` <div *ngIf="someOtherPermission; else noPermission">presentation</div>`,
`</div>`,
`<ng-template #noPermission>`,
` <p>No Permissions</p>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`<div>`,
` @if (hasPermission) {`,
` <div>presentation</div>`,
` } @else {`,
` <p>No Permissions</p>`,
` }`,
` @if (someOtherPermission) {`,
` <div>presentation</div>`,
` } @else {`,
` <p>No Permissions</p>`,
` }`,
`</div>\n`,
].join('\n');
expect(actual).toBe(expected);
});
it('should remove a template with no overlap with following elements', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-container *ngIf="stuff">`,
` <div>`,
` <ul>`,
` <li>`,
` <span>`,
` <ng-container *ngIf="things; else elseTmpl">`,
` <p>Hmm</p>`,
` </ng-container>`,
` <ng-template #elseTmpl> 0 </ng-template></span>`,
` </li>`,
` </ul>`,
` </div>`,
`</ng-container>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (stuff) {`,
` <div>`,
` <ul>`,
` <li>`,
` <span>`,
` @if (things) {`,
` <p>Hmm</p>`,
` } @else {`,
` 0`,
` }`,
` </span>`,
` </li>`,
` </ul>`,
` </div>`,
`}`,
].join('\n'),
);
});
it('should migrate nested template usage correctly', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-container *ngIf="!(condition$ | async); else template">`,
` Hello!`,
`</ng-container>`,
`<ng-template #bar>Bar</ng-template>`,
`<ng-template #foo>Foo</ng-template>`,
`<ng-template #template>`,
` <ng-container`,
` *ngIf="(foo$ | async) === true; then foo; else bar"`,
` ></ng-container>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (!(condition$ | async)) {`,
` Hello!`,
`} @else {`,
` @if ((foo$ | async) === true) {`,
` Foo`,
` } @else {`,
` Bar`,
` }`,
`}\n`,
].join('\n'),
);
});
it('should add an ngTemplateOutlet when the template placeholder does not match a template', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[`<button *ngIf="active; else defaultTemplate">`, ` Hello!`, `</button>`].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (active) {`,
` <button>`,
` Hello!`,
` </button>`,
`} @else {`,
` <ng-template [ngTemplateOutlet]="defaultTemplate"></ng-template>`,
`}`,
].join('\n'),
);
});
| |
010909
|
it('should handle OR logic in ngIf else case', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div *ngIf="condition; else titleTemplate || defaultTemplate">Hello!</div>`,
`<ng-template #defaultTemplate> Default </ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (condition) {`,
` <div>Hello!</div>`,
`} @else {`,
` <ng-template [ngTemplateOutlet]="titleTemplate || defaultTemplate"></ng-template>`,
`}`,
`<ng-template #defaultTemplate> Default </ng-template>`,
].join('\n'),
);
});
it('should handle ternaries in ngIfElse', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-template`,
` [ngIf]="customClearTemplate"`,
` [ngIfElse]="isSidebarV3 || variant === 'v3' ? clearTemplateV3 : clearTemplate"`,
` [ngTemplateOutlet]="customClearTemplate"`,
`></ng-template>`,
`<ng-template #clearTemplateV3>v3</ng-template>`,
`<ng-template #clearTemplate>clear</ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (customClearTemplate) {`,
` <ng-template`,
` [ngTemplateOutlet]="customClearTemplate"`,
` ></ng-template>`,
`} @else {`,
` <ng-template [ngTemplateOutlet]="isSidebarV3 || variant === 'v3' ? clearTemplateV3 : clearTemplate"></ng-template>`,
`}`,
`<ng-template #clearTemplateV3>v3</ng-template>`,
`<ng-template #clearTemplate>clear</ng-template>`,
].join('\n'),
);
});
it('should handle ternaries in ngIf', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div *ngIf="!vm.isEmpty; else vm.loading ? loader : empty"></div>`,
`<ng-template #loader>Loading</ng-template>`,
`<ng-template #empty>Empty</ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (!vm.isEmpty) {`,
` <div></div>`,
`} @else {`,
` <ng-template [ngTemplateOutlet]="vm.loading ? loader : empty"></ng-template>`,
`}`,
`<ng-template #loader>Loading</ng-template>`,
`<ng-template #empty>Empty</ng-template>`,
].join('\n'),
);
});
it('should replace all instances of template placeholders', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div *ngIf="condition; else otherTemplate">`,
` <ng-container *ngIf="!defaultTemplate; else defaultTemplate">`,
` Hello!`,
` </ng-container>`,
`</div>`,
`<ng-template #otherTemplate>`,
` <div>`,
` <ng-container *ngIf="!defaultTemplate; else defaultTemplate">`,
` Hello again!`,
` </ng-container>`,
` </div>`,
`</ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (condition) {`,
` <div>`,
` @if (!defaultTemplate) {`,
` Hello!`,
` } @else {`,
` <ng-template [ngTemplateOutlet]="defaultTemplate"></ng-template>`,
` }`,
` </div>`,
`} @else {`,
` <div>`,
` @if (!defaultTemplate) {`,
` Hello again!`,
` } @else {`,
` <ng-template [ngTemplateOutlet]="defaultTemplate"></ng-template>`,
` }`,
` </div>`,
`}\n`,
].join('\n'),
);
});
it('should trim newlines in ngIf conditions', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-template`,
` [ngIf]="customClearTemplate"`,
` [ngIfElse]="`,
` isSidebarV3 || variant === 'v3' ? clearTemplateV3 : clearTemplate`,
` "`,
`></ng-template>`,
].join('\n'),
);
await runMigration();
const content = tree.readContent('/comp.html');
expect(content).toBe(
[
`@if (customClearTemplate) {`,
`} @else {`,
` <ng-template [ngTemplateOutlet]="isSidebarV3 || variant === 'v3' ? clearTemplateV3 : clearTemplate"></ng-template>`,
`}`,
].join('\n'),
);
});
it('should migrate a template using the θδ characters', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
selector: 'declare-comp',
templateUrl: './comp.html',
standalone: true,
imports: [NgIf],
})
class DeclareComp {
show = false;
}
`,
);
writeFile('/comp.html', `<div *ngIf="show">Some greek characters: θδ!</div>`);
await runMigration();
expect(tree.readContent('/comp.html')).toBe(
'@if (show) {<div>Some greek characters: θδ!</div>}',
);
});
});
de
| |
010912
|
ould indent multi-line attribute strings as single quotes to the right place', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div *ngIf="show">show</div>`,
`<span i18n-message='this is a multi-`,
` line attribute`,
` with cool things'>`,
` Content here`,
`</span>`,
`<span`,
` i18n-message='this is a multi-`,
` line attribute`,
` that starts`,
` on a newline'>`,
` Different here`,
`</span>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`@if (show) {`,
` <div>show</div>`,
`}`,
`<span i18n-message='this is a multi-`,
` line attribute`,
` with cool things'>`,
` Content here`,
`</span>`,
`<span`,
` i18n-message='this is a multi-`,
` line attribute`,
` that starts`,
` on a newline'>`,
` Different here`,
`</span>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should handle dom nodes with underscores mixed in', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({
templateUrl: './comp.html'
})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<div *ngIf="show">show</div>`,
`<a-very-long-component-name-that-has_underscores-too`,
` [selected]="selected | async "`,
`>`,
`</a-very-long-component-name-that-has_underscores-too>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`@if (show) {`,
` <div>show</div>`,
`}`,
`<a-very-long-component-name-that-has_underscores-too`,
` [selected]="selected | async "`,
` >`,
`</a-very-long-component-name-that-has_underscores-too>`,
].join('\n');
expect(actual).toBe(expected);
});
it('should handle single-line element with a log tag name and a closing bracket on a new line', async () => {
writeFile(
'/comp.ts',
`
import {Component} from '@angular/core';
import {NgIf} from '@angular/common';
@Component({templateUrl: './comp.html'})
class Comp {
show = false;
}
`,
);
writeFile(
'/comp.html',
[
`<ng-container *ngIf="true">`,
`<component-name-with-several-dashes></component-name-with-several-dashes`,
`></ng-container>`,
].join('\n'),
);
await runMigration();
const actual = tree.readContent('/comp.html');
const expected = [
`@if (true) {`,
` <component-name-with-several-dashes></component-name-with-several-dashes`,
` >`,
` }`,
].join('\n');
expect(actual).toBe(expected);
});
});
de
| |
010991
|
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import {ChangeTracker, PendingChange} from '../../utils/change_tracker';
import {findClassDeclaration} from '../../utils/typescript/class_declaration';
import {findLiteralProperty} from '../../utils/typescript/property_name';
import {
isAngularRoutesArray,
isProvideRoutesCallExpression,
isRouterCallExpression,
isRouterModuleCallExpression,
isRouterProviderCallExpression,
isStandaloneComponent,
} from './util';
interface RouteData {
routeFilePath: string;
routeFileImports: ts.ImportDeclaration[];
array: ts.ArrayLiteralExpression;
}
export interface RouteMigrationData {
path: string;
file: string;
}
/**
* Converts all application routes that are using standalone components to be lazy loaded.
* @param sourceFile File that should be migrated.
* @param program
*/
export function migrateFileToLazyRoutes(
sourceFile: ts.SourceFile,
program: ts.Program,
): {
pendingChanges: PendingChange[];
migratedRoutes: RouteMigrationData[];
skippedRoutes: RouteMigrationData[];
} {
const typeChecker = program.getTypeChecker();
const printer = ts.createPrinter();
const tracker = new ChangeTracker(printer);
const routeArraysToMigrate = findRoutesArrayToMigrate(sourceFile, typeChecker);
if (routeArraysToMigrate.length === 0) {
return {pendingChanges: [], skippedRoutes: [], migratedRoutes: []};
}
const {skippedRoutes, migratedRoutes} = migrateRoutesArray(
routeArraysToMigrate,
typeChecker,
tracker,
);
return {
pendingChanges: tracker.recordChanges().get(sourceFile) || [],
skippedRoutes,
migratedRoutes,
};
}
/** Finds route object that can be migrated */
function findRoutesArrayToMigrate(sourceFile: ts.SourceFile, typeChecker: ts.TypeChecker) {
const routesArrays: RouteData[] = [];
sourceFile.forEachChild(function walk(node) {
if (ts.isCallExpression(node)) {
if (
isRouterModuleCallExpression(node, typeChecker) ||
isRouterProviderCallExpression(node, typeChecker) ||
isRouterCallExpression(node, typeChecker) ||
isProvideRoutesCallExpression(node, typeChecker)
) {
const arg = node.arguments[0]; // ex: RouterModule.forRoot(routes) or provideRouter(routes)
const routeFileImports = sourceFile.statements.filter(ts.isImportDeclaration);
if (ts.isArrayLiteralExpression(arg) && arg.elements.length > 0) {
// ex: inline routes array: RouterModule.forRoot([{ path: 'test', component: TestComponent }])
routesArrays.push({
routeFilePath: sourceFile.fileName,
array: arg as ts.ArrayLiteralExpression,
routeFileImports,
});
} else if (ts.isIdentifier(arg)) {
// ex: reference to routes array: RouterModule.forRoot(routes)
// RouterModule.forRoot(routes), provideRouter(routes), provideRoutes(routes)
const symbol = typeChecker.getSymbolAtLocation(arg);
if (!symbol?.declarations) return;
for (const declaration of symbol.declarations) {
if (ts.isVariableDeclaration(declaration)) {
const initializer = declaration.initializer;
if (initializer && ts.isArrayLiteralExpression(initializer)) {
// ex: const routes = [{ path: 'test', component: TestComponent }];
routesArrays.push({
routeFilePath: sourceFile.fileName,
array: initializer,
routeFileImports,
});
}
}
}
}
}
}
if (ts.isVariableDeclaration(node)) {
if (isAngularRoutesArray(node, typeChecker)) {
const initializer = node.initializer;
if (
initializer &&
ts.isArrayLiteralExpression(initializer) &&
initializer.elements.length > 0
) {
// ex: const routes: Routes = [{ path: 'test', component: TestComponent }];
if (routesArrays.find((x) => x.array === initializer)) {
// already exists
return;
}
routesArrays.push({
routeFilePath: sourceFile.fileName,
array: initializer,
routeFileImports: sourceFile.statements.filter(ts.isImportDeclaration),
});
}
}
}
node.forEachChild(walk);
});
return routesArrays;
}
/** Migrate a routes object standalone components to be lazy loaded. */
function migrateRoutesArray(
routesArray: RouteData[],
typeChecker: ts.TypeChecker,
tracker: ChangeTracker,
): {migratedRoutes: RouteMigrationData[]; skippedRoutes: RouteMigrationData[]} {
const migratedRoutes: RouteMigrationData[] = [];
const skippedRoutes: RouteMigrationData[] = [];
const importsToRemove: ts.ImportDeclaration[] = [];
for (const route of routesArray) {
route.array.elements.forEach((element) => {
if (ts.isObjectLiteralExpression(element)) {
const {
migratedRoutes: migrated,
skippedRoutes: toBeSkipped,
importsToRemove: toBeRemoved,
} = migrateRoute(element, route, typeChecker, tracker);
migratedRoutes.push(...migrated);
skippedRoutes.push(...toBeSkipped);
importsToRemove.push(...toBeRemoved);
}
});
}
for (const importToRemove of importsToRemove) {
tracker.removeNode(importToRemove);
}
return {migratedRoutes, skippedRoutes};
}
/**
* Migrates a single route object and returns the results of the migration
* It recursively migrates the children routes if they exist
*/
function migrateRoute(
element: ts.ObjectLiteralExpression,
route: RouteData,
typeChecker: ts.TypeChecker,
tracker: ChangeTracker,
): {
migratedRoutes: RouteMigrationData[];
skippedRoutes: RouteMigrationData[];
importsToRemove: ts.ImportDeclaration[];
} {
const skippedRoutes: RouteMigrationData[] = [];
const migratedRoutes: RouteMigrationData[] = [];
const importsToRemove: ts.ImportDeclaration[] = [];
const component = findLiteralProperty(element, 'component');
// this can be empty string or a variable that is not a string, or not present at all
const routePath = findLiteralProperty(element, 'path')?.getText() ?? '';
const children = findLiteralProperty(element, 'children') as ts.PropertyAssignment | undefined;
// recursively migrate children routes first if they exist
if (children && ts.isArrayLiteralExpression(children.initializer)) {
for (const childRoute of children.initializer.elements) {
if (ts.isObjectLiteralExpression(childRoute)) {
const {
migratedRoutes: migrated,
skippedRoutes: toBeSkipped,
importsToRemove: toBeRemoved,
} = migrateRoute(childRoute, route, typeChecker, tracker);
migratedRoutes.push(...migrated);
skippedRoutes.push(...toBeSkipped);
importsToRemove.push(...toBeRemoved);
}
}
}
const routeMigrationResults = {migratedRoutes, skippedRoutes, importsToRemove};
if (!component) {
return routeMigrationResults;
}
const componentDeclaration = findClassDeclaration(component, typeChecker);
if (!componentDeclaration) {
return routeMigrationResults;
}
// if component is not a standalone component, skip it
if (!isStandaloneComponent(componentDeclaration)) {
skippedRoutes.push({path: routePath, file: route.routeFilePath});
return routeMigrationResults;
}
const componentClassName =
componentDeclaration.name && ts.isIdentifier(componentDeclaration.name)
? componentDeclaration.name.text
: null;
if (!componentClassName) {
return routeMigrationResults;
}
// if component is in the same file as the routes array, skip it
if (componentDeclaration.getSourceFile().fileName === route.routeFilePath) {
return routeMigrationResults;
}
const componentImport = route.routeFileImports.find((importDecl) =>
importDecl.importClause?.getText().includes(componentClassName),
)!;
// remove single and double quotes from the import path
let componentImportPath = ts.isStringLiteral(componentImport?.moduleSpecifier)
? componentImport.moduleSpecifier.text
: null;
// if the import path is not a string literal, skip it
if (!componentImportPath) {
skippedRoutes.push({path: routePath, file: route.routeFilePath});
return routeMigrationResults;
}
const isDefaultExport =
componentDeclaration.modifiers?.some((x) => x.kind === ts.SyntaxKind.DefaultKeyword) ?? false;
const loadComponent = createLoadComponentPropertyAssignment(
componentImportPath,
componentClassName,
isDefaultExport,
);
tracker.replaceNode(component, loadComponent);
// Add the import statement for the standalone component
if (!importsToRemove.includes(componentImport)) {
importsToRemove.push(componentImport);
}
migratedRoutes.push({path: routePath, file: route.routeFilePath});
// the component was migrated, so we return the results
return routeMigrationResults;
}
| |
010993
|
# Route lazy loading migration
This schematic helps developers to convert eagerly loaded component routes to lazy loaded routes.
By lazy loading components we can split the production bundle into smaller chunks,
to avoid big JS bundle that includes all routes, which negatively affects initial page load of an application.
## How to run this migration?
The migration can be run using the following command:
```bash
ng generate @angular/core:route-lazy-loading
```
By default, migration will go over the entire application. If you want to apply this migration to a subset of the files, you can pass the path argument as shown below:
```bash
ng generate @angular/core:route-lazy-loading --path src/app/sub-component
```
The value of the path parameter is a relative path within the project.
### How does it work?
The schematic will attempt to find all the places where the application routes as defined:
- `RouterModule.forRoot` and `RouterModule.forChild`
- `Router.resetConfig`
- `provideRouter`
- `provideRoutes`
- variables of type `Routes` or `Route[]` (e.g. `const routes: Routes = [{...}]`)
The migration will check all the components in the routes, check if they are standalone and eagerly loaded, and if so, it will convert them to lazy loaded routes.
**Before:**
```typescript
// app.module.ts
import { HomeComponent } from './home/home.component';
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'home',
component: HomeComponent, // HomeComponent is standalone and eagerly loaded
},
]),
],
})
export class AppModule {}
```
**After:**
```typescript
// app.module.ts
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'home',
// ↓ HomeComponent is now lazy loaded
loadComponent: () => import('./home/home.component').then(m => m.HomeComponent),
},
]),
],
})
export class AppModule {}
```
> This migration will also collect information about all the components declared in NgModules
and output the list of routes that use them (including corresponding location of the file).
Consider making those components standalone and run this migration again.
You can use an existing migration (see https://angular.dev/reference/migrations/standalone)
to convert those components to standalone.
| |
011002
|
## Inject migration
Automated migration that converts classes using constructor-based injection to the `inject`
function. It can be run using:
```bash
ng generate @angular/core:inject-migration
```
**Before:**
```typescript
import { Component, Inject, Optional } from '@angular/core';
import { MyService } from './service';
import { DI_TOKEN } from './token';
@Component({})
export class MyComp {
constructor(private service: MyService, @Inject(TOKEN) @Optional() readonly token: string) {}
}
```
**After:**
```typescript
import { Component, inject } from '@angular/core';
import { MyService } from './service';
import { DI_TOKEN } from './token';
@Component({})
export class MyComp {
private service = inject(MyService);
readonly token = inject(DI_TOKEN, { optional: true });
}
```
### Options
The migration includes several options to customize its output.
#### `path`
Determines which sub-path in your project should be migrated. Pass in `.` or leave it blank to
migrate the entire directory.
#### `migrateAbstractClasses`
Angular doesn't validate that parameters of abstract classes are injectable. This means that the
migration can't reliably migrate them to `inject` without risking breakages which is why they're
disabled by default. Enable this option if you want abstract classes to be migrated, but note
that you may have to **fix some breakages manually**.
#### `backwardsCompatibleConstructors`
By default the migration tries to clean up the code as much as it can, which includes deleting
parameters from the constructor, or even the entire constructor if it doesn't include any code.
In some cases this can lead to compilation errors when classes with Angular decorators inherit from
other classes with Angular decorators. If you enable this option, the migration will generate an
additional constructor signature to keep it backwards compatible, at the expense of more code.
**Before:**
```typescript
import { Component } from '@angular/core';
import { MyService } from './service';
@Component({})
export class MyComp {
constructor(private service: MyService) {}
}
```
**After:**
```typescript
import { Component } from '@angular/core';
import { MyService } from './service';
@Component({})
export class MyComp {
private service = inject(MyService);
/** Inserted by Angular inject() migration for backwards compatibility */
constructor(...args: unknown[]);
constructor() {}
}
```
#### `nonNullableOptional`
If injection fails for a parameter with the `@Optional` decorator, Angular returns `null` which
means that the real type of any `@Optional` parameter will be `| null`. However, because decorators
cannot influence their types, there is a lot of existing code whose type is incorrect. The type is
fixed in `inject()` which can cause new compilation errors to show up. If you enable this option,
the migration will produce a non-null assertion after the `inject()` call to match the old type,
at the expense of potentially hiding type errors.
**Note:** non-null assertions won't be added to parameters that are already typed to be nullable,
because the code that depends on them likely already accounts for their nullability.
**Before:**
```typescript
import { Component, Inject, Optional } from '@angular/core';
import { TOKEN_ONE, TOKEN_TWO } from './token';
@Component({})
export class MyComp {
constructor(
@Inject(TOKEN_ONE) @Optional() private tokenOne: number,
@Inject(TOKEN_TWO) @Optional() private tokenTwo: string | null) {}
}
```
**After:**
```typescript
import { Component, inject } from '@angular/core';
import { TOKEN_ONE, TOKEN_TWO } from './token';
@Component({})
export class MyComp {
// Note the `!` at the end.
private tokenOne = inject(TOKEN_ONE, { optional: true })!;
// Does not have `!` at the end, because the type was already nullable.
private tokenTwo = inject(TOKEN_TWO, { optional: true });
}
```
| |
011029
|
# Standalone migration
`ng generate` schematic that helps users to convert an application to `standalone` components,
directives and pipes. The migration can be run with `ng generate @angular/core:standalone` and it
has the following options:
* `mode` - Configures the mode that migration should run in. The different modes are clarified
further down in this document.
* `path` - Relative path within the project that the migration should apply to. Can be used to
migrate specific sub-directories individually. Defaults to the project root.
## Migration flow
The standalone migration involves multiple distinct operations, and as such has to be run multiple
times. Authors should verify that the app still works between each of the steps. If the application
is large, it can be easier to use the `path` option to migrate specific sub-sections of the app
individually.
**Note:** The schematic often needs to generate new code or copy existing code to different places.
This means that likely the formatting won't match your app anymore and there may be some lint
failures. The application should compile, but it's expected that the author will fix up any
formatting and linting failures.
An example migration could look as follows:
1. `ng generate @angular/core:standalone`.
2. Select the "Convert all components, directives and pipes to standalone" option.
3. Verify that the app works and commit the changes.
4. `ng generate @angular/core:standalone`.
5. Select the "Remove unnecessary NgModule classes" option.
6. Verify that the app works and commit the changes.
7. `ng generate @angular/core:standalone`.
8. Select the "Bootstrap the application using standalone APIs" option.
9. Verify that the app works and commit the changes.
10. Run your linting and formatting checks, and fix any failures. Commit the result.
| |
011030
|
## Migration modes
The migration is made up the following modes that are intended to be run in the order they are
listed in:
1. Convert declarations to standalone.
2. Remove unnecessary NgModules.
3. Switch to standalone bootstrapping API.
### Convert declarations to standalone
In this mode, the migration will find all of the components, directives and pipes, and convert them
to standalone by removing `standalone: false` and adding any dependencies to the `imports` array.
**Note:** NgModules which bootstrap a component are explicitly ignored in this step, because they
are likely to be root modules and they would have to be bootstrapped using `bootstrapApplication`
instead of `bootstrapModule`. Their declarations will be converted automatically as a part of the
"Switch to standalone bootstrapping API" step.
**Before:**
```typescript
// app.module.ts
@NgModule({
imports: [CommonModule],
declarations: [MyComp, MyDir, MyPipe]
})
export class AppModule {}
```
```typescript
// my-comp.ts
@Component({
selector: 'my-comp',
template: '<div my-dir *ngIf="showGreeting">{{ "Hello" | myPipe }}</div>',
standalone: false,
})
export class MyComp {
public showGreeting = true;
}
```
```typescript
// my-dir.ts
@Directive({selector: '[my-dir]', standalone: false})
export class MyDir {}
```
```typescript
// my-pipe.ts
@Pipe({name: 'myPipe', pure: true, standalone: false})
export class MyPipe {}
```
**After:**
```typescript
// app.module.ts
@NgModule({
imports: [CommonModule, MyComp, MyDir, MyPipe]
})
export class AppModule {}
```
```typescript
// my-comp.ts
@Component({
selector: 'my-comp',
template: '<div my-dir *ngIf="showGreeting">{{ "Hello" | myPipe }}</div>',
imports: [NgIf, MyDir, MyPipe]
})
export class MyComp {
public showGreeting = true;
}
```
```typescript
// my-dir.ts
@Directive({selector: '[my-dir]'})
export class MyDir {}
```
```typescript
// my-pipe.ts
@Pipe({name: 'myPipe', pure: true})
export class MyPipe {}
```
### Remove unnecessary NgModules
After converting all declarations to standalone, a lot of NgModules won't be necessary anymore!
This step identifies such modules and deletes them, including as many references to them, as
possible. If a module reference can't be deleted automatically, the migration will leave a TODO
comment saying `TODO(standalone-migration): clean up removed NgModule reference manually` so that
the author can delete it themselves.
A module is considered "safe to remove" if it:
* Has no `declarations`.
* Has no `providers`.
* Has no `bootstrap` components.
* Has no `imports` that reference a `ModuleWithProviders` symbol or a module that can't be removed.
* Has no class members. Empty constructors are ignored.
**Before:**
```typescript
// importer.module.ts
@NgModule({
imports: [FooComp, BarPipe],
exports: [FooComp, BarPipe]
})
export class ImporterModule {}
```
```typescript
// configurer.module.ts
import {ImporterModule} from './importer.module';
console.log(ImporterModule);
@NgModule({
imports: [ImporterModule],
exports: [ImporterModule],
providers: [{provide: FOO, useValue: 123}]
})
export class ConfigurerModule {}
```
```typescript
// index.ts
export {ImporterModule, ConfigurerModule} from './modules/index';
```
**After:**
```typescript
// importer.module.ts
// Deleted!
```
```typescript
// configurer.module.ts
console.log(/* TODO(standalone-migration): clean up removed NgModule reference manually */ ImporterModule);
@NgModule({
imports: [],
exports: [],
providers: [{provide: FOO, useValue: 123}]
})
export class ConfigurerModule {}
```
```typescript
// index.ts
export {ConfigurerModule} from './modules/index';
```
### Switch to standalone bootstrapping API
Converts any usages of the old `bootstrapModule` API to the new `bootstrapApplication`. To do this
in a safe way, the migration has to make the following changes to the application's code:
1. Generate the `bootstrapApplication` call to replace the `bootstrapModule` one.
2. Convert the `declarations` of the module that is being bootstrapped to `standalone`. These
modules were skipped explicitly in the first step of the migration.
3. Copy any `providers` from the bootstrapped module into the `providers` option of
`bootstrapApplication`.
4. Copy any classes from the `imports` array of the rootModule to the `providers` option of
`bootstrapApplication` and wrap them in an `importsProvidersFrom` function call.
5. Adjust any dynamic import paths so that they're correct when they're copied over.
6. If an API with a standalone equivalent is detected, it may be converted automatically as well.
E.g. `RouterModule.forRoot` will become `provideRouter`.
7. Remove the root module.
If the migration detects that the `providers` or `imports` of the root module are referencing code
outside of the class declaration, it will attempt to carry over as much of it as it can to the new
location. If some of that code is exported, it will be imported in the new location, otherwise it
will be copied over.
**Before:**
```typescript
// ./app/app.module.ts
import {NgModule, InjectionToken} from '@angular/core';
import {RouterModule} from '@angular/router';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AppComponent} from './app.component.ts';
import {SharedModule} from './shared.module';
import {ImportedInterface} from './some-interface';
import {CONFIG} from './config';
interface NonImportedInterface {
foo: any;
baz: ImportedInterface;
}
const token = new InjectionToken<NonImportedInterface>('token');
export class ExportedConfigClass {}
@NgModule({
imports: [
SharedModule,
BrowserAnimationsModule,
RouterModule.forRoot([{
path: 'shop',
loadComponent: () => import('./shop/shop.component').then(m => m.ShopComponent)
}], {
initialNavigation: 'enabledBlocking'
})
],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [
{provide: token, useValue: {foo: true, bar: {baz: false}}},
{provide: CONFIG, useClass: ExportedConfigClass}
]
})
export class AppModule {}
```
```typescript
// ./app/app.component.ts
@Component({selector: 'app', template: 'hello', standalone: false})
export class AppComponent {}
```
```typescript
// ./main.ts
import {platformBrowser} from '@angular/platform-browser';
import {AppModule} from './app/app.module';
platformBrowser().bootstrapModule(AppModule).catch(e => console.error(e));
```
**After:**
```typescript
// ./app/app.module.ts
import {NgModule, InjectionToken} from '@angular/core';
import {RouterModule} from '@angular/router';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {AppComponent} from './app.component.ts';
import {SharedModule} from '../shared/shared.module';
import {ImportedInterface} from './some-interface';
import {CONFIG} from './config';
interface NonImportedInterface {
foo: any;
bar: ImportedInterface;
}
const token = new InjectionToken<NonImportedInterface>('token');
export class ExportedConfigClass {}
```
```typescript
// ./app/app.component.ts
@Component({selector: 'app', template: 'hello'})
export class AppComponent {}
```
```typescript
// ./main.ts
import {platformBrowser, bootstrapApplication} from '@angular/platform-browser';
import {InjectionToken, importProvidersFrom} from '@angular/core';
import {withEnabledBlockingInitialNavigation, provideRouter} from '@angular/router';
import {provideAnimations} from '@angular/platform-browser/animations';
import {AppModule, ExportedConfigClass} from './app/app.module';
import {AppComponent} from './app/app.component';
import {CONFIG} from './app/config';
import {SharedModule} from './shared/shared.module';
import {ImportedInterface} from './app/some-interface';
interface NonImportedInterface {
foo: any;
bar: ImportedInterface;
}
const token = new InjectionToken<NonImportedInterface>('token');
bootstrapApplication(AppComponent, {
providers: [
importProvidersFrom(SharedModule),
{provide: token, useValue: {foo: true, bar: {baz: false}}},
{provide: CONFIG, useClass: ExportedConfigClass},
provideAnimations(),
provideRouter([{
path: 'shop',
loadComponent: () => import('./app/shop/shop.component').then(m => m.ShopComponent)
}], withEnabledBlockingInitialNavigation())
]
}).catch(e => console.error(e));
```
| |
011039
|
## Control Flow Syntax migration
Angular v17 introduces a new control flow syntax. This migration replaces the
existing usages of `*ngIf`, `*ngFor`, and `*ngSwitch` to their equivalent block
syntax. Existing ng-templates are preserved in case they are used elsewhere in
the template. It has the following option:
* `path` - Relative path within the project that the migration should apply to. Can be used to
migrate specific sub-directories individually. Defaults to the project root.
#### Before
```ts
import {Component} from '@angular/core';
@Component({
template: `<div><span *ngIf="show">Content here</span></div>`
})
export class MyComp {
show = false;
}
```
#### After
```ts
import {Component} from '@angular/core';
@Component({
template: `<div>@if (show) {<span>Content here</span>}</div>`
})
export class MyComp {
show = false
}
```
| |
011052
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Rule, SchematicContext, SchematicsException, Tree} from '@angular-devkit/schematics';
import {join, relative} from 'path';
import {normalizePath} from '../../utils/change_tracker';
import {canMigrateFile, createMigrationProgram} from '../../utils/typescript/compiler_host';
import {migrateTemplate} from './migration';
import {AnalyzedFile, MigrateError} from './types';
import {analyze} from './util';
interface Options {
path: string;
format: boolean;
}
export function migrate(options: Options): Rule {
return async (tree: Tree, context: SchematicContext) => {
const basePath = process.cwd();
const pathToMigrate = normalizePath(join(basePath, options.path));
let allPaths = [];
if (pathToMigrate.trim() !== '') {
allPaths.push(pathToMigrate);
}
if (!allPaths.length) {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot run the control flow migration.',
);
}
let errors: string[] = [];
for (const tsconfigPath of allPaths) {
const migrateErrors = runControlFlowMigration(
tree,
tsconfigPath,
basePath,
pathToMigrate,
options,
);
errors = [...errors, ...migrateErrors];
}
if (errors.length > 0) {
context.logger.warn(`WARNING: ${errors.length} errors occurred during your migration:\n`);
errors.forEach((err: string) => {
context.logger.warn(err);
});
}
};
}
function runControlFlowMigration(
tree: Tree,
tsconfigPath: string,
basePath: string,
pathToMigrate: string,
schematicOptions: Options,
): string[] {
if (schematicOptions.path.startsWith('..')) {
throw new SchematicsException(
'Cannot run control flow migration outside of the current project.',
);
}
const program = createMigrationProgram(tree, tsconfigPath, basePath);
const sourceFiles = program
.getSourceFiles()
.filter(
(sourceFile) =>
sourceFile.fileName.startsWith(pathToMigrate) &&
canMigrateFile(basePath, sourceFile, program),
);
if (sourceFiles.length === 0) {
throw new SchematicsException(
`Could not find any files to migrate under the path ${pathToMigrate}. Cannot run the control flow migration.`,
);
}
const analysis = new Map<string, AnalyzedFile>();
const migrateErrors = new Map<string, MigrateError[]>();
for (const sourceFile of sourceFiles) {
analyze(sourceFile, analysis);
}
// sort files with .html files first
// this ensures class files know if it's safe to remove CommonModule
const paths = sortFilePaths([...analysis.keys()]);
for (const path of paths) {
const file = analysis.get(path)!;
const ranges = file.getSortedRanges();
const relativePath = relative(basePath, path);
const content = tree.readText(relativePath);
const update = tree.beginUpdate(relativePath);
for (const {start, end, node, type} of ranges) {
const template = content.slice(start, end);
const length = (end ?? content.length) - start;
const {migrated, errors} = migrateTemplate(
template,
type,
node,
file,
schematicOptions.format,
analysis,
);
if (migrated !== null) {
update.remove(start, length);
update.insertLeft(start, migrated);
}
if (errors.length > 0) {
migrateErrors.set(path, errors);
}
}
tree.commitUpdate(update);
}
const errorList: string[] = [];
for (let [template, errors] of migrateErrors) {
errorList.push(generateErrorMessage(template, errors));
}
return errorList;
}
function sortFilePaths(names: string[]): string[] {
names.sort((a, _) => (a.endsWith('.html') ? -1 : 0));
return names;
}
function generateErrorMessage(path: string, errors: MigrateError[]): string {
let errorMessage = `Template "${path}" encountered ${errors.length} errors during migration:\n`;
errorMessage += errors.map((e) => ` - ${e.type}: ${e.error}\n`);
return errorMessage;
}
| |
011065
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {SIGNAL as ɵSIGNAL} from '@angular/core/primitives/signals';
export {isSignal, Signal, ValueEqualityFn} from './render3/reactivity/api';
export {computed, CreateComputedOptions} from './render3/reactivity/computed';
export {
CreateSignalOptions,
signal,
WritableSignal,
ɵunwrapWritableSignal,
} from './render3/reactivity/signal';
export {linkedSignal} from './render3/reactivity/linked_signal';
export {untracked} from './render3/reactivity/untracked';
export {
CreateEffectOptions,
effect,
EffectRef,
EffectCleanupFn,
EffectCleanupRegisterFn,
} from './render3/reactivity/effect';
export {
MicrotaskEffectScheduler as ɵMicrotaskEffectScheduler,
microtaskEffect as ɵmicrotaskEffect,
} from './render3/reactivity/microtask_effect';
export {EffectScheduler as ɵEffectScheduler} from './render3/reactivity/root_effect_scheduler';
export {afterRenderEffect, ɵFirstAvailableSignal} from './render3/reactivity/after_render_effect';
export {assertNotInReactiveContext} from './render3/reactivity/asserts';
| |
011076
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {APP_ID, PLATFORM_ID} from './application/application_tokens';
import {inject} from './di/injector_compatibility';
import {ɵɵdefineInjectable} from './di/interface/defs';
import {getDocument} from './render3/interfaces/document';
/**
* A type-safe key to use with `TransferState`.
*
* Example:
*
* ```
* const COUNTER_KEY = makeStateKey<number>('counter');
* let value = 10;
*
* transferState.set(COUNTER_KEY, value);
* ```
*
* @publicApi
*/
export type StateKey<T> = string & {
__not_a_string: never;
__value_type?: T;
};
/**
* Create a `StateKey<T>` that can be used to store value of type T with `TransferState`.
*
* Example:
*
* ```
* const COUNTER_KEY = makeStateKey<number>('counter');
* let value = 10;
*
* transferState.set(COUNTER_KEY, value);
* ```
*
* @publicApi
*/
export function makeStateKey<T = void>(key: string): StateKey<T> {
return key as StateKey<T>;
}
function initTransferState(): TransferState {
const transferState = new TransferState();
if (inject(PLATFORM_ID) === 'browser') {
transferState.store = retrieveTransferredState(getDocument(), inject(APP_ID));
}
return transferState;
}
/**
* A key value store that is transferred from the application on the server side to the application
* on the client side.
*
* The `TransferState` is available as an injectable token.
* On the client, just inject this token using DI and use it, it will be lazily initialized.
* On the server it's already included if `renderApplication` function is used. Otherwise, import
* the `ServerTransferStateModule` module to make the `TransferState` available.
*
* The values in the store are serialized/deserialized using JSON.stringify/JSON.parse. So only
* boolean, number, string, null and non-class objects will be serialized and deserialized in a
* non-lossy manner.
*
* @publicApi
*/
export class TransferState {
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
token: TransferState,
providedIn: 'root',
factory: initTransferState,
});
/** @internal */
store: Record<string, unknown | undefined> = {};
private onSerializeCallbacks: {[k: string]: () => unknown | undefined} = {};
/**
* Get the value corresponding to a key. Return `defaultValue` if key is not found.
*/
get<T>(key: StateKey<T>, defaultValue: T): T {
return this.store[key] !== undefined ? (this.store[key] as T) : defaultValue;
}
/**
* Set the value corresponding to a key.
*/
set<T>(key: StateKey<T>, value: T): void {
this.store[key] = value;
}
/**
* Remove a key from the store.
*/
remove<T>(key: StateKey<T>): void {
delete this.store[key];
}
/**
* Test whether a key exists in the store.
*/
hasKey<T>(key: StateKey<T>): boolean {
return this.store.hasOwnProperty(key);
}
/**
* Indicates whether the state is empty.
*/
get isEmpty(): boolean {
return Object.keys(this.store).length === 0;
}
/**
* Register a callback to provide the value for a key when `toJson` is called.
*/
onSerialize<T>(key: StateKey<T>, callback: () => T): void {
this.onSerializeCallbacks[key] = callback;
}
/**
* Serialize the current state of the store to JSON.
*/
toJson(): string {
// Call the onSerialize callbacks and put those values into the store.
for (const key in this.onSerializeCallbacks) {
if (this.onSerializeCallbacks.hasOwnProperty(key)) {
try {
this.store[key] = this.onSerializeCallbacks[key]();
} catch (e) {
console.warn('Exception in onSerialize callback: ', e);
}
}
}
// Escape script tag to avoid break out of <script> tag in serialized output.
// Encoding of `<` is the same behaviour as G3 script_builders.
return JSON.stringify(this.store).replace(/</g, '\\u003C');
}
}
function retrieveTransferredState(
doc: Document,
appId: string,
): Record<string, unknown | undefined> {
// Locate the script tag with the JSON data transferred from the server.
// The id of the script tag is set to the Angular appId + 'state'.
const script = doc.getElementById(appId + '-state');
if (script?.textContent) {
try {
// Avoid using any here as it triggers lint errors in google3 (any is not allowed).
// Decoding of `<` is done of the box by browsers and node.js, same behaviour as G3
// script_builders.
return JSON.parse(script.textContent) as {};
} catch (e) {
console.warn('Exception while restoring TransferState for app ' + appId, e);
}
}
return {};
}
| |
011086
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {SimpleChanges} from './simple_change';
/**
* @description
* A lifecycle hook that is called when any data-bound property of a directive changes.
* Define an `ngOnChanges()` method to handle the changes.
*
* @see {@link DoCheck}
* @see {@link OnInit}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define an on-changes handler for an input property.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='OnChanges'}
*
* @publicApi
*/
export interface OnChanges {
/**
* A callback method that is invoked immediately after the
* default change detector has checked data-bound properties
* if at least one has changed, and before the view and content
* children are checked.
* @param changes The changed properties.
*/
ngOnChanges(changes: SimpleChanges): void;
}
/**
* @description
* A lifecycle hook that is called after Angular has initialized
* all data-bound properties of a directive.
* Define an `ngOnInit()` method to handle any additional initialization tasks.
*
* @see {@link AfterContentInit}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define its own initialization method.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='OnInit'}
*
* @publicApi
*/
export interface OnInit {
/**
* A callback method that is invoked immediately after the
* default change detector has checked the directive's
* data-bound properties for the first time,
* and before any of the view or content children have been checked.
* It is invoked only once when the directive is instantiated.
*/
ngOnInit(): void;
}
/**
* A lifecycle hook that invokes a custom change-detection function for a directive,
* in addition to the check performed by the default change-detector.
*
* The default change-detection algorithm looks for differences by comparing
* bound-property values by reference across change detection runs. You can use this
* hook to check for and respond to changes by some other means.
*
* When the default change detector detects changes, it invokes `ngOnChanges()` if supplied,
* regardless of whether you perform additional change detection.
* Typically, you should not use both `DoCheck` and `OnChanges` to respond to
* changes on the same input.
*
* @see {@link OnChanges}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface
* to invoke it own change-detection cycle.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='DoCheck'}
*
* For a more complete example and discussion, see
* [Defining custom change detection](guide/components/lifecycle#defining-custom-change-detection).
*
* @publicApi
*/
export interface DoCheck {
/**
* A callback method that performs change-detection, invoked
* after the default change-detector runs.
* See `KeyValueDiffers` and `IterableDiffers` for implementing
* custom change checking for collections.
*
*/
ngDoCheck(): void;
}
/**
* A lifecycle hook that is called when a directive, pipe, or service is destroyed.
* Use for any custom cleanup that needs to occur when the
* instance is destroyed.
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface
* to define its own custom clean-up method.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='OnDestroy'}
*
* @publicApi
*/
export interface OnDestroy {
/**
* A callback method that performs custom clean-up, invoked immediately
* before a directive, pipe, or service instance is destroyed.
*/
ngOnDestroy(): void;
}
/**
* @description
* A lifecycle hook that is called after Angular has fully initialized
* all content of a directive. It will run only once when the projected content is initialized.
* Define an `ngAfterContentInit()` method to handle any additional initialization tasks.
*
* @see {@link OnInit}
* @see {@link AfterViewInit}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define its own content initialization method.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterContentInit'}
*
* @publicApi
*/
export interface AfterContentInit {
/**
* A callback method that is invoked immediately after
* Angular has completed initialization of all of the directive's
* content.
* It is invoked only once when the directive is instantiated.
*/
ngAfterContentInit(): void;
}
/**
* @description
* A lifecycle hook that is called after the default change detector has
* completed checking all content of a directive. It will run after the content
* has been checked and most of the time it's during a change detection cycle.
*
* @see {@link AfterViewChecked}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define its own after-check functionality.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterContentChecked'}
*
* @publicApi
*/
export interface AfterContentChecked {
/**
* A callback method that is invoked immediately after the
* default change detector has completed checking all of the directive's
* content.
*/
ngAfterContentChecked(): void;
}
/**
* @description
* A lifecycle hook that is called after Angular has fully initialized
* a component's view.
* Define an `ngAfterViewInit()` method to handle any additional initialization tasks.
*
* @see {@link OnInit}
* @see {@link AfterContentInit}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define its own view initialization method.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterViewInit'}
*
* @publicApi
*/
export interface AfterViewInit {
/**
* A callback method that is invoked immediately after
* Angular has completed initialization of a component's view.
* It is invoked only once when the view is instantiated.
*
*/
ngAfterViewInit(): void;
}
/**
* @description
* A lifecycle hook that is called after the default change detector has
* completed checking a component's view for changes.
*
* @see {@link AfterContentChecked}
* @see [Lifecycle hooks guide](guide/components/lifecycle)
*
* @usageNotes
* The following snippet shows how a component can implement this interface to
* define its own after-check functionality.
*
* {@example core/ts/metadata/lifecycle_hooks_spec.ts region='AfterViewChecked'}
*
* @publicApi
*/
export interface AfterViewChecked {
/**
* A callback method that is invoked immediately after the
* default change detector has completed one change-check cycle
* for a component's view.
*/
ngAfterViewChecked(): void;
}
| |
011096
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Type} from '../interface/type';
import {getClosureSafeProperty} from '../util/property';
import {stringify} from '../util/stringify';
/**
* An interface that a function passed into `forwardRef` has to implement.
*
* @usageNotes
* ### Example
*
* {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref_fn'}
* @publicApi
*/
export interface ForwardRefFn {
(): any;
}
const __forward_ref__ = getClosureSafeProperty({__forward_ref__: getClosureSafeProperty});
/**
* Allows to refer to references which are not yet defined.
*
* For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
* DI is declared, but not yet defined. It is also used when the `token` which we use when creating
* a query is not yet defined.
*
* `forwardRef` is also used to break circularities in standalone components imports.
*
* @usageNotes
* ### Circular dependency example
* {@example core/di/ts/forward_ref/forward_ref_spec.ts region='forward_ref'}
*
* ### Circular standalone reference import example
* ```ts
* @Component({
* standalone: true,
* imports: [ChildComponent],
* selector: 'app-parent',
* template: `<app-child [hideParent]="hideParent"></app-child>`,
* })
* export class ParentComponent {
* @Input() hideParent: boolean;
* }
*
*
* @Component({
* standalone: true,
* imports: [CommonModule, forwardRef(() => ParentComponent)],
* selector: 'app-child',
* template: `<app-parent *ngIf="!hideParent"></app-parent>`,
* })
* export class ChildComponent {
* @Input() hideParent: boolean;
* }
* ```
*
* @publicApi
*/
export function forwardRef(forwardRefFn: ForwardRefFn): Type<any> {
(<any>forwardRefFn).__forward_ref__ = forwardRef;
(<any>forwardRefFn).toString = function () {
return stringify(this());
};
return <Type<any>>(<any>forwardRefFn);
}
/**
* Lazily retrieves the reference value from a forwardRef.
*
* Acts as the identity function when given a non-forward-ref value.
*
* @usageNotes
* ### Example
*
* {@example core/di/ts/forward_ref/forward_ref_spec.ts region='resolve_forward_ref'}
*
* @see {@link forwardRef}
* @publicApi
*/
export function resolveForwardRef<T>(type: T): T {
return isForwardRef(type) ? type() : type;
}
/** Checks whether a function is wrapped by a `forwardRef`. */
export function isForwardRef(fn: any): fn is () => any {
return (
typeof fn === 'function' &&
fn.hasOwnProperty(__forward_ref__) &&
fn.__forward_ref__ === forwardRef
);
}
| |
011104
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {
InjectorProfilerContext,
setInjectorProfilerContext,
} from '../render3/debug/injector_profiler';
import {getInjectImplementation, setInjectImplementation} from './inject_switch';
import type {Injector} from './injector';
import {getCurrentInjector, setCurrentInjector} from './injector_compatibility';
import {assertNotDestroyed, R3Injector} from './r3_injector';
/**
* Runs the given function in the [context](guide/di/dependency-injection-context) of the given
* `Injector`.
*
* Within the function's stack frame, [`inject`](api/core/inject) can be used to inject dependencies
* from the given `Injector`. Note that `inject` is only usable synchronously, and cannot be used in
* any asynchronous callbacks or after any `await` points.
*
* @param injector the injector which will satisfy calls to [`inject`](api/core/inject) while `fn`
* is executing
* @param fn the closure to be run in the context of `injector`
* @returns the return value of the function, if any
* @publicApi
*/
export function runInInjectionContext<ReturnT>(injector: Injector, fn: () => ReturnT): ReturnT {
if (injector instanceof R3Injector) {
assertNotDestroyed(injector);
}
let prevInjectorProfilerContext: InjectorProfilerContext;
if (ngDevMode) {
prevInjectorProfilerContext = setInjectorProfilerContext({injector, token: null});
}
const prevInjector = setCurrentInjector(injector);
const previousInjectImplementation = setInjectImplementation(undefined);
try {
return fn();
} finally {
setCurrentInjector(prevInjector);
ngDevMode && setInjectorProfilerContext(prevInjectorProfilerContext!);
setInjectImplementation(previousInjectImplementation);
}
}
/**
* Whether the current stack frame is inside an injection context.
*/
export function isInInjectionContext(): boolean {
return getInjectImplementation() !== undefined || getCurrentInjector() != null;
}
/**
* Asserts that the current stack frame is within an [injection
* context](guide/di/dependency-injection-context) and has access to `inject`.
*
* @param debugFn a reference to the function making the assertion (used for the error message).
*
* @publicApi
*/
export function assertInInjectionContext(debugFn: Function): void {
// Taking a `Function` instead of a string name here prevents the unminified name of the function
// from being retained in the bundle regardless of minification.
if (!isInInjectionContext()) {
throw new RuntimeError(
RuntimeErrorCode.MISSING_INJECTION_CONTEXT,
ngDevMode &&
debugFn.name +
'() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`',
);
}
}
| |
011128
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Subscription} from 'rxjs';
import {ApplicationRef} from '../../application/application_ref';
import {
ENVIRONMENT_INITIALIZER,
EnvironmentProviders,
inject,
Injectable,
InjectionToken,
makeEnvironmentProviders,
StaticProvider,
} from '../../di';
import {RuntimeError, RuntimeErrorCode} from '../../errors';
import {PendingTasksInternal} from '../../pending_tasks';
import {performanceMarkFeature} from '../../util/performance';
import {NgZone} from '../../zone';
import {InternalNgZoneOptions} from '../../zone/ng_zone';
import {
ChangeDetectionScheduler,
ZONELESS_SCHEDULER_DISABLED,
ZONELESS_ENABLED,
SCHEDULE_IN_ROOT_ZONE,
} from './zoneless_scheduling';
import {SCHEDULE_IN_ROOT_ZONE_DEFAULT} from './flags';
@Injectable({providedIn: 'root'})
export class NgZoneChangeDetectionScheduler {
private readonly zone = inject(NgZone);
private readonly changeDetectionScheduler = inject(ChangeDetectionScheduler);
private readonly applicationRef = inject(ApplicationRef);
private _onMicrotaskEmptySubscription?: Subscription;
initialize(): void {
if (this._onMicrotaskEmptySubscription) {
return;
}
this._onMicrotaskEmptySubscription = this.zone.onMicrotaskEmpty.subscribe({
next: () => {
// `onMicroTaskEmpty` can happen _during_ the zoneless scheduler change detection because
// zone.run(() => {}) will result in `checkStable` at the end of the `zone.run` closure
// and emit `onMicrotaskEmpty` synchronously if run coalsecing is false.
if (this.changeDetectionScheduler.runningTick) {
return;
}
this.zone.run(() => {
this.applicationRef.tick();
});
},
});
}
ngOnDestroy() {
this._onMicrotaskEmptySubscription?.unsubscribe();
}
}
/**
* Internal token used to verify that `provideZoneChangeDetection` is not used
* with the bootstrapModule API.
*/
export const PROVIDED_NG_ZONE = new InjectionToken<boolean>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'provideZoneChangeDetection token' : '',
{factory: () => false},
);
export function internalProvideZoneChangeDetection({
ngZoneFactory,
ignoreChangesOutsideZone,
scheduleInRootZone,
}: {
ngZoneFactory?: () => NgZone;
ignoreChangesOutsideZone?: boolean;
scheduleInRootZone?: boolean;
}): StaticProvider[] {
ngZoneFactory ??= () =>
new NgZone({...getNgZoneOptions(), scheduleInRootZone} as InternalNgZoneOptions);
return [
{provide: NgZone, useFactory: ngZoneFactory},
{
provide: ENVIRONMENT_INITIALIZER,
multi: true,
useFactory: () => {
const ngZoneChangeDetectionScheduler = inject(NgZoneChangeDetectionScheduler, {
optional: true,
});
if (
(typeof ngDevMode === 'undefined' || ngDevMode) &&
ngZoneChangeDetectionScheduler === null
) {
throw new RuntimeError(
RuntimeErrorCode.MISSING_REQUIRED_INJECTABLE_IN_BOOTSTRAP,
`A required Injectable was not found in the dependency injection tree. ` +
'If you are bootstrapping an NgModule, make sure that the `BrowserModule` is imported.',
);
}
return () => ngZoneChangeDetectionScheduler!.initialize();
},
},
{
provide: ENVIRONMENT_INITIALIZER,
multi: true,
useFactory: () => {
const service = inject(ZoneStablePendingTask);
return () => {
service.initialize();
};
},
},
// Always disable scheduler whenever explicitly disabled, even if another place called
// `provideZoneChangeDetection` without the 'ignore' option.
ignoreChangesOutsideZone === true ? {provide: ZONELESS_SCHEDULER_DISABLED, useValue: true} : [],
{
provide: SCHEDULE_IN_ROOT_ZONE,
useValue: scheduleInRootZone ?? SCHEDULE_IN_ROOT_ZONE_DEFAULT,
},
];
}
/**
* Provides `NgZone`-based change detection for the application bootstrapped using
* `bootstrapApplication`.
*
* `NgZone` is already provided in applications by default. This provider allows you to configure
* options like `eventCoalescing` in the `NgZone`.
* This provider is not available for `platformBrowser().bootstrapModule`, which uses
* `BootstrapOptions` instead.
*
* @usageNotes
* ```typescript
* bootstrapApplication(MyApp, {providers: [
* provideZoneChangeDetection({eventCoalescing: true}),
* ]});
* ```
*
* @publicApi
* @see {@link bootstrapApplication}
* @see {@link NgZoneOptions}
*/
export function provideZoneChangeDetection(options?: NgZoneOptions): EnvironmentProviders {
const ignoreChangesOutsideZone = options?.ignoreChangesOutsideZone;
const scheduleInRootZone = (options as any)?.scheduleInRootZone;
const zoneProviders = internalProvideZoneChangeDetection({
ngZoneFactory: () => {
const ngZoneOptions = getNgZoneOptions(options);
ngZoneOptions.scheduleInRootZone = scheduleInRootZone;
if (ngZoneOptions.shouldCoalesceEventChangeDetection) {
performanceMarkFeature('NgZone_CoalesceEvent');
}
return new NgZone(ngZoneOptions);
},
ignoreChangesOutsideZone,
scheduleInRootZone,
});
return makeEnvironmentProviders([
{provide: PROVIDED_NG_ZONE, useValue: true},
{provide: ZONELESS_ENABLED, useValue: false},
zoneProviders,
]);
}
/**
* Used to configure event and run coalescing with `provideZoneChangeDetection`.
*
* @publicApi
*
* @see {@link provideZoneChangeDetection}
*/
export interface NgZoneOptions {
/**
* Optionally specify coalescing event change detections or not.
* Consider the following case.
*
* ```
* <div (click)="doSomething()">
* <button (click)="doSomethingElse()"></button>
* </div>
* ```
*
* When button is clicked, because of the event bubbling, both
* event handlers will be called and 2 change detections will be
* triggered. We can coalesce such kind of events to only trigger
* change detection only once.
*
* By default, this option will be false. So the events will not be
* coalesced and the change detection will be triggered multiple times.
* And if this option be set to true, the change detection will be
* triggered async by scheduling a animation frame. So in the case above,
* the change detection will only be triggered once.
*/
eventCoalescing?: boolean;
/**
* Optionally specify if `NgZone#run()` method invocations should be coalesced
* into a single change detection.
*
* Consider the following case.
* ```
* for (let i = 0; i < 10; i ++) {
* ngZone.run(() => {
* // do something
* });
* }
* ```
*
* This case triggers the change detection multiple times.
* With ngZoneRunCoalescing options, all change detections in an event loop trigger only once.
* In addition, the change detection executes in requestAnimation.
*
*/
runCoalescing?: boolean;
/**
* When false, change detection is scheduled when Angular receives
* a clear indication that templates need to be refreshed. This includes:
*
* - calling `ChangeDetectorRef.markForCheck`
* - calling `ComponentRef.setInput`
* - updating a signal that is read in a template
* - attaching a view that is marked dirty
* - removing a view
* - registering a render hook (templates are only refreshed if render hooks do one of the above)
*
* @deprecated This option was introduced out of caution as a way for developers to opt out of the
* new behavior in v18 which schedule change detection for the above events when they occur
* outside the Zone. After monitoring the results post-release, we have determined that this
* feature is working as desired and do not believe it should ever be disabled by setting
* this option to `true`.
*/
ignoreChangesOutsideZone?: boolean;
}
// Transforms a set of `BootstrapOptions` (supported by the NgModule-based bootstrap APIs) ->
// `NgZoneOptions` that are recognized by the NgZone constructor. Passing no options will result in
// a set of default options returned.
export function getNgZoneOptions(options?: NgZoneOptions): InternalNgZoneOptions {
return {
enableLongStackTrace: typeof ngDevMode === 'undefined' ? false : !!ngDevMode,
shouldCoalesceEventChangeDetection: options?.eventCoalescing ?? false,
shouldCoalesceRunChangeDetection: options?.runCoalescing ?? false,
};
}
| |
011131
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {InjectionToken} from '../../di/injection_token';
export const enum NotificationSource {
// Change detection needs to run in order to synchronize application state
// with the DOM when the following notifications are received:
// This operation indicates that a subtree needs to be traversed during change detection.
MarkAncestorsForTraversal,
// A component/directive gets a new input.
SetInput,
// Defer block state updates need change detection to fully render the state.
DeferBlockStateUpdate,
// Debugging tools updated state and have requested change detection.
DebugApplyChanges,
// ChangeDetectorRef.markForCheck indicates the component is dirty/needs to refresh.
MarkForCheck,
// Bound listener callbacks execute and can update state without causing other notifications from
// above.
Listener,
// Custom elements do sometimes require checking directly.
CustomElement,
// The following notifications do not require views to be refreshed
// but we should execute render hooks:
// Render hooks are guaranteed to execute with the schedulers timing.
RenderHook,
DeferredRenderHook,
// Views might be created outside and manipulated in ways that
// we cannot be aware of. When a view is attached, Angular now "knows"
// about it and we now know that DOM might have changed (and we should
// run render hooks). If the attached view is dirty, the `MarkAncestorsForTraversal`
// notification should also be received.
ViewAttached,
// When DOM removal happens, render hooks may be interested in the new
// DOM state but we do not need to refresh any views unless. If change
// detection is required after DOM removal, another notification should
// be received (i.e. `markForCheck`).
ViewDetachedFromDOM,
// Applying animations might result in new DOM state and should rerun render hooks
AsyncAnimationsLoaded,
// The scheduler is notified when a pending task is removed via the public API.
// This allows us to make stability async, delayed until the next application tick.
PendingTaskRemoved,
// An `effect()` outside of the view tree became dirty and might need to run.
RootEffect,
// An `effect()` within the view tree became dirty.
ViewEffect,
}
/**
* Injectable that is notified when an `LView` is made aware of changes to application state.
*/
export abstract class ChangeDetectionScheduler {
abstract notify(source: NotificationSource): void;
abstract runningTick: boolean;
}
/** Token used to indicate if zoneless was enabled via provideZonelessChangeDetection(). */
export const ZONELESS_ENABLED = new InjectionToken<boolean>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless enabled' : '',
{providedIn: 'root', factory: () => false},
);
/** Token used to indicate `provideExperimentalZonelessChangeDetection` was used. */
export const PROVIDED_ZONELESS = new InjectionToken<boolean>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless provided' : '',
{providedIn: 'root', factory: () => false},
);
export const ZONELESS_SCHEDULER_DISABLED = new InjectionToken<boolean>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'scheduler disabled' : '',
);
// TODO(atscott): Remove in v19. Scheduler should be done with runOutsideAngular.
export const SCHEDULE_IN_ROOT_ZONE = new InjectionToken<boolean>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'run changes outside zone in root' : '',
);
| |
011134
|
@Injectable({providedIn: 'root'})
export class ChangeDetectionSchedulerImpl implements ChangeDetectionScheduler {
private readonly appRef = inject(ApplicationRef);
private readonly taskService = inject(PendingTasksInternal);
private readonly ngZone = inject(NgZone);
private readonly zonelessEnabled = inject(ZONELESS_ENABLED);
private readonly disableScheduling =
inject(ZONELESS_SCHEDULER_DISABLED, {optional: true}) ?? false;
private readonly zoneIsDefined = typeof Zone !== 'undefined' && !!Zone.root.run;
private readonly schedulerTickApplyArgs = [{data: {'__scheduler_tick__': true}}];
private readonly subscriptions = new Subscription();
private readonly angularZoneId = this.zoneIsDefined
? (this.ngZone as NgZonePrivate)._inner?.get(angularZoneInstanceIdProperty)
: null;
private readonly scheduleInRootZone =
!this.zonelessEnabled &&
this.zoneIsDefined &&
(inject(SCHEDULE_IN_ROOT_ZONE, {optional: true}) ?? false);
private cancelScheduledCallback: null | (() => void) = null;
private useMicrotaskScheduler = false;
runningTick = false;
pendingRenderTaskId: number | null = null;
constructor() {
this.subscriptions.add(
this.appRef.afterTick.subscribe(() => {
// If the scheduler isn't running a tick but the application ticked, that means
// someone called ApplicationRef.tick manually. In this case, we should cancel
// any change detections that had been scheduled so we don't run an extra one.
if (!this.runningTick) {
this.cleanup();
}
}),
);
this.subscriptions.add(
this.ngZone.onUnstable.subscribe(() => {
// If the zone becomes unstable when we're not running tick (this happens from the zone.run),
// we should cancel any scheduled change detection here because at this point we
// know that the zone will stabilize at some point and run change detection itself.
if (!this.runningTick) {
this.cleanup();
}
}),
);
// TODO(atscott): These conditions will need to change when zoneless is the default
// Instead, they should flip to checking if ZoneJS scheduling is provided
this.disableScheduling ||=
!this.zonelessEnabled &&
// NoopNgZone without enabling zoneless means no scheduling whatsoever
(this.ngZone instanceof NoopNgZone ||
// The same goes for the lack of Zone without enabling zoneless scheduling
!this.zoneIsDefined);
}
notify(source: NotificationSource): void {
if (!this.zonelessEnabled && source === NotificationSource.Listener) {
// When the notification comes from a listener, we skip the notification unless the
// application has enabled zoneless. Ideally, listeners wouldn't notify the scheduler at all
// automatically. We do not know that a developer made a change in the listener callback that
// requires an `ApplicationRef.tick` (synchronize templates / run render hooks). We do this
// only for an easier migration from OnPush components to zoneless. Because listeners are
// usually executed inside the Angular zone and listeners automatically call `markViewDirty`,
// developers never needed to manually use `ChangeDetectorRef.markForCheck` or some other API
// to make listener callbacks work correctly with `OnPush` components.
return;
}
let force = false;
switch (source) {
case NotificationSource.MarkAncestorsForTraversal: {
this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeTraversal;
break;
}
case NotificationSource.DebugApplyChanges:
case NotificationSource.DeferBlockStateUpdate:
case NotificationSource.MarkForCheck:
case NotificationSource.Listener:
case NotificationSource.SetInput: {
this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeCheck;
break;
}
case NotificationSource.DeferredRenderHook: {
// Render hooks are "deferred" when they're triggered from other render hooks. Using the
// deferred dirty flags ensures that adding new hooks doesn't automatically trigger a loop
// inside tick().
this.appRef.deferredDirtyFlags |= ApplicationRefDirtyFlags.AfterRender;
break;
}
case NotificationSource.CustomElement: {
// We use `ViewTreeTraversal` to ensure we refresh the element even if this is triggered
// during CD. In practice this is a no-op since the elements code also calls via a
// `markForRefresh()` API which sends `NotificationSource.MarkAncestorsForTraversal` anyway.
this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeTraversal;
force = true;
break;
}
case NotificationSource.RootEffect: {
this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.RootEffects;
// Root effects still force a CD, even if the scheduler is disabled. This ensures that
// effects always run, even when triggered from outside the zone when the scheduler is
// otherwise disabled.
force = true;
break;
}
case NotificationSource.ViewEffect: {
// This is technically a no-op, since view effects will also send a
// `MarkAncestorsForTraversal` notification. Still, we set this for logical consistency.
this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeTraversal;
// View effects still force a CD, even if the scheduler is disabled. This ensures that
// effects always run, even when triggered from outside the zone when the scheduler is
// otherwise disabled.
force = true;
break;
}
case NotificationSource.PendingTaskRemoved: {
// Removing a pending task via the public API forces a scheduled tick, ensuring that
// stability is async and delayed until there was at least an opportunity to run
// application synchronization. This prevents some footguns when working with the
// public API for pending tasks where developers attempt to update application state
// immediately after removing the last task.
force = true;
break;
}
case NotificationSource.ViewDetachedFromDOM:
case NotificationSource.ViewAttached:
case NotificationSource.RenderHook:
case NotificationSource.AsyncAnimationsLoaded:
default: {
// These notifications only schedule a tick but do not change whether we should refresh
// views. Instead, we only need to run render hooks unless another notification from the
// other set is also received before `tick` happens.
this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.AfterRender;
}
}
if (!this.shouldScheduleTick(force)) {
return;
}
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (this.useMicrotaskScheduler) {
trackMicrotaskNotificationForDebugging();
} else {
consecutiveMicrotaskNotifications = 0;
stackFromLastFewNotifications.length = 0;
}
}
const scheduleCallback = this.useMicrotaskScheduler
? scheduleCallbackWithMicrotask
: scheduleCallbackWithRafRace;
this.pendingRenderTaskId = this.taskService.add();
if (this.scheduleInRootZone) {
this.cancelScheduledCallback = Zone.root.run(() => scheduleCallback(() => this.tick()));
} else {
this.cancelScheduledCallback = this.ngZone.runOutsideAngular(() =>
scheduleCallback(() => this.tick()),
);
}
}
private shouldScheduleTick(force: boolean): boolean {
if ((this.disableScheduling && !force) || this.appRef.destroyed) {
return false;
}
// already scheduled or running
if (this.pendingRenderTaskId !== null || this.runningTick || this.appRef._runningTick) {
return false;
}
// If we're inside the zone don't bother with scheduler. Zone will stabilize
// eventually and run change detection.
if (
!this.zonelessEnabled &&
this.zoneIsDefined &&
Zone.current.get(angularZoneInstanceIdProperty + this.angularZoneId)
) {
return false;
}
return true;
}
/**
* Calls ApplicationRef._tick inside the `NgZone`.
*
* Calling `tick` directly runs change detection and cancels any change detection that had been
* scheduled previously.
*
* @param shouldRefreshViews Passed directly to `ApplicationRef._tick` and skips straight to
* render hooks when `false`.
*/
| |
011135
|
private tick(): void {
// When ngZone.run below exits, onMicrotaskEmpty may emit if the zone is
// stable. We want to prevent double ticking so we track whether the tick is
// already running and skip it if so.
if (this.runningTick || this.appRef.destroyed) {
return;
}
// If we reach the tick and there is no work to be done in ApplicationRef.tick,
// skip it altogether and clean up. There may be no work if, for example, the only
// event that notified the scheduler was the removal of a pending task.
if (this.appRef.dirtyFlags === ApplicationRefDirtyFlags.None) {
this.cleanup();
return;
}
// The scheduler used to pass "whether to check views" as a boolean flag instead of setting
// fine-grained dirtiness flags, and global checking was always used on the first pass. This
// created an interesting edge case: if a notification made a view dirty and then ticked via the
// scheduler (and not the zone) a global check was still performed.
//
// Ideally, this would not be the case, and only zone-based ticks would do global passes.
// However this is a breaking change and requires fixes in g3. Until this cleanup can be done,
// we add the `ViewTreeGlobal` flag to request a global check if any views are dirty in a
// scheduled tick (unless zoneless is enabled, in which case global checks aren't really a
// thing).
//
// TODO(alxhub): clean up and remove this workaround as a breaking change.
if (!this.zonelessEnabled && this.appRef.dirtyFlags & ApplicationRefDirtyFlags.ViewTreeAny) {
this.appRef.dirtyFlags |= ApplicationRefDirtyFlags.ViewTreeGlobal;
}
const task = this.taskService.add();
try {
this.ngZone.run(
() => {
this.runningTick = true;
this.appRef._tick();
},
undefined,
this.schedulerTickApplyArgs,
);
} catch (e: unknown) {
this.taskService.remove(task);
throw e;
} finally {
this.cleanup();
}
// If we're notified of a change within 1 microtask of running change
// detection, run another round in the same event loop. This allows code
// which uses Promise.resolve (see NgModel) to avoid
// ExpressionChanged...Error to still be reflected in a single browser
// paint, even if that spans multiple rounds of change detection.
this.useMicrotaskScheduler = true;
scheduleCallbackWithMicrotask(() => {
this.useMicrotaskScheduler = false;
this.taskService.remove(task);
});
}
ngOnDestroy() {
this.subscriptions.unsubscribe();
this.cleanup();
}
private cleanup() {
this.runningTick = false;
this.cancelScheduledCallback?.();
this.cancelScheduledCallback = null;
// If this is the last task, the service will synchronously emit a stable
// notification. If there is a subscriber that then acts in a way that
// tries to notify the scheduler again, we need to be able to respond to
// schedule a new change detection. Therefore, we should clear the task ID
// before removing it from the pending tasks (or the tasks service should
// not synchronously emit stable, similar to how Zone stableness only
// happens if it's still stable after a microtask).
if (this.pendingRenderTaskId !== null) {
const taskId = this.pendingRenderTaskId;
this.pendingRenderTaskId = null;
this.taskService.remove(taskId);
}
}
}
/**
* Provides change detection without ZoneJS for the application bootstrapped using
* `bootstrapApplication`.
*
* This function allows you to configure the application to not use the state/state changes of
* ZoneJS to schedule change detection in the application. This will work when ZoneJS is not present
* on the page at all or if it exists because something else is using it (either another Angular
* application which uses ZoneJS for scheduling or some other library that relies on ZoneJS).
*
* This can also be added to the `TestBed` providers to configure the test environment to more
* closely match production behavior. This will help give higher confidence that components are
* compatible with zoneless change detection.
*
* ZoneJS uses browser events to trigger change detection. When using this provider, Angular will
* instead use Angular APIs to schedule change detection. These APIs include:
*
* - `ChangeDetectorRef.markForCheck`
* - `ComponentRef.setInput`
* - updating a signal that is read in a template
* - when bound host or template listeners are triggered
* - attaching a view that was marked dirty by one of the above
* - removing a view
* - registering a render hook (templates are only refreshed if render hooks do one of the above)
*
* @usageNotes
* ```typescript
* bootstrapApplication(MyApp, {providers: [
* provideExperimentalZonelessChangeDetection(),
* ]});
* ```
*
* This API is experimental. Neither the shape, nor the underlying behavior is stable and can change
* in patch versions. There are known feature gaps and API ergonomic considerations. We will iterate
* on the exact API based on the feedback and our understanding of the problem and solution space.
*
* @publicApi
* @experimental
* @see [bootstrapApplication](/api/platform-browser/bootstrapApplication)
*/
export function provideExperimentalZonelessChangeDetection(): EnvironmentProviders {
performanceMarkFeature('NgZoneless');
if ((typeof ngDevMode === 'undefined' || ngDevMode) && typeof Zone !== 'undefined' && Zone) {
const message = formatRuntimeError(
RuntimeErrorCode.UNEXPECTED_ZONEJS_PRESENT_IN_ZONELESS_MODE,
`The application is using zoneless change detection, but is still loading Zone.js. ` +
`Consider removing Zone.js to get the full benefits of zoneless. ` +
`In applications using the Angular CLI, Zone.js is typically included in the "polyfills" section of the angular.json file.`,
);
console.warn(message);
}
return makeEnvironmentProviders([
{provide: ChangeDetectionScheduler, useExisting: ChangeDetectionSchedulerImpl},
{provide: NgZone, useClass: NoopNgZone},
{provide: ZONELESS_ENABLED, useValue: true},
{provide: SCHEDULE_IN_ROOT_ZONE, useValue: false},
typeof ngDevMode === 'undefined' || ngDevMode
? [{provide: PROVIDED_ZONELESS, useValue: true}]
: [],
]);
}
| |
011225
|
export abstract class ViewContainerRef {
/**
* Anchor element that specifies the location of this container in the containing view.
* Each view container can have only one anchor element, and each anchor element
* can have only a single view container.
*
* Root elements of views attached to this container become siblings of the anchor element in
* the rendered view.
*
* Access the `ViewContainerRef` of an element by placing a `Directive` injected
* with `ViewContainerRef` on the element, or use a `ViewChild` query.
*
* <!-- TODO: rename to anchorElement -->
*/
abstract get element(): ElementRef;
/**
* The dependency injector for this view container.
*/
abstract get injector(): Injector;
/** @deprecated No replacement */
abstract get parentInjector(): Injector;
/**
* Destroys all views in this container.
*/
abstract clear(): void;
/**
* Retrieves a view from this container.
* @param index The 0-based index of the view to retrieve.
* @returns The `ViewRef` instance, or null if the index is out of range.
*/
abstract get(index: number): ViewRef | null;
/**
* Reports how many views are currently attached to this container.
* @returns The number of views.
*/
abstract get length(): number;
/**
* Instantiates an embedded view and inserts it
* into this container.
* @param templateRef The HTML template that defines the view.
* @param context The data-binding context of the embedded view, as declared
* in the `<ng-template>` usage.
* @param options Extra configuration for the created view. Includes:
* * index: The 0-based index at which to insert the new view into this container.
* If not specified, appends the new view as the last entry.
* * injector: Injector to be used within the embedded view.
*
* @returns The `ViewRef` instance for the newly created view.
*/
abstract createEmbeddedView<C>(
templateRef: TemplateRef<C>,
context?: C,
options?: {
index?: number;
injector?: Injector;
},
): EmbeddedViewRef<C>;
/**
* Instantiates an embedded view and inserts it
* into this container.
* @param templateRef The HTML template that defines the view.
* @param context The data-binding context of the embedded view, as declared
* in the `<ng-template>` usage.
* @param index The 0-based index at which to insert the new view into this container.
* If not specified, appends the new view as the last entry.
*
* @returns The `ViewRef` instance for the newly created view.
*/
abstract createEmbeddedView<C>(
templateRef: TemplateRef<C>,
context?: C,
index?: number,
): EmbeddedViewRef<C>;
/**
* Instantiates a single component and inserts its host view into this container.
*
* @param componentType Component Type to use.
* @param options An object that contains extra parameters:
* * index: the index at which to insert the new component's host view into this container.
* If not specified, appends the new view as the last entry.
* * injector: the injector to use as the parent for the new component.
* * ngModuleRef: an NgModuleRef of the component's NgModule, you should almost always provide
* this to ensure that all expected providers are available for the component
* instantiation.
* * environmentInjector: an EnvironmentInjector which will provide the component's environment.
* you should almost always provide this to ensure that all expected providers
* are available for the component instantiation. This option is intended to
* replace the `ngModuleRef` parameter.
* * projectableNodes: list of DOM nodes that should be projected through
* [`<ng-content>`](api/core/ng-content) of the new component instance.
*
* @returns The new `ComponentRef` which contains the component instance and the host view.
*/
abstract createComponent<C>(
componentType: Type<C>,
options?: {
index?: number;
injector?: Injector;
ngModuleRef?: NgModuleRef<unknown>;
environmentInjector?: EnvironmentInjector | NgModuleRef<unknown>;
projectableNodes?: Node[][];
},
): ComponentRef<C>;
/**
* Instantiates a single component and inserts its host view into this container.
*
* @param componentFactory Component factory to use.
* @param index The index at which to insert the new component's host view into this container.
* If not specified, appends the new view as the last entry.
* @param injector The injector to use as the parent for the new component.
* @param projectableNodes List of DOM nodes that should be projected through
* [`<ng-content>`](api/core/ng-content) of the new component instance.
* @param ngModuleRef An instance of the NgModuleRef that represent an NgModule.
* This information is used to retrieve corresponding NgModule injector.
*
* @returns The new `ComponentRef` which contains the component instance and the host view.
*
* @deprecated Angular no longer requires component factories to dynamically create components.
* Use different signature of the `createComponent` method, which allows passing
* Component class directly.
*/
abstract createComponent<C>(
componentFactory: ComponentFactory<C>,
index?: number,
injector?: Injector,
projectableNodes?: any[][],
environmentInjector?: EnvironmentInjector | NgModuleRef<any>,
): ComponentRef<C>;
/**
* Inserts a view into this container.
* @param viewRef The view to insert.
* @param index The 0-based index at which to insert the view.
* If not specified, appends the new view as the last entry.
* @returns The inserted `ViewRef` instance.
*
*/
abstract insert(viewRef: ViewRef, index?: number): ViewRef;
/**
* Moves a view to a new location in this container.
* @param viewRef The view to move.
* @param index The 0-based index of the new location.
* @returns The moved `ViewRef` instance.
*/
abstract move(viewRef: ViewRef, currentIndex: number): ViewRef;
/**
* Returns the index of a view within the current container.
* @param viewRef The view to query.
* @returns The 0-based index of the view's position in this container,
* or `-1` if this container doesn't contain the view.
*/
abstract indexOf(viewRef: ViewRef): number;
/**
* Destroys a view attached to this container
* @param index The 0-based index of the view to destroy.
* If not specified, the last view in the container is removed.
*/
abstract remove(index?: number): void;
/**
* Detaches a view from this container without destroying it.
* Use along with `insert()` to move a view within the current container.
* @param index The 0-based index of the view to detach.
* If not specified, the last view in the container is detached.
*/
abstract detach(index?: number): ViewRef | null;
/**
* @internal
* @nocollapse
*/
static __NG_ELEMENT_ID__: () => ViewContainerRef = injectViewContainerRef;
}
/**
* Creates a ViewContainerRef and stores it on the injector. Or, if the ViewContainerRef
* already exists, retrieves the existing ViewContainerRef.
*
* @returns The ViewContainerRef instance to use
*/
export function injectViewContainerRef(): ViewContainerRef {
const previousTNode = getCurrentTNode() as TElementNode | TElementContainerNode | TContainerNode;
return createContainerRef(previousTNode, getLView());
}
const VE_ViewContainerRef = ViewContainerRef;
// TODO(alxhub): cleaning up this indirection triggers a subtle bug in Closure in g3. Once the fix
// for that lands, this can be cleaned up.
| |
011276
|
export class ViewRef<T> implements EmbeddedViewRef<T>, ChangeDetectorRefInterface {
private _appRef: ApplicationRef | null = null;
private _attachedToViewContainer = false;
get rootNodes(): any[] {
const lView = this._lView;
const tView = lView[TVIEW];
return collectNativeNodes(tView, lView, tView.firstChild, []);
}
constructor(
/**
* This represents `LView` associated with the component when ViewRef is a ChangeDetectorRef.
*
* When ViewRef is created for a dynamic component, this also represents the `LView` for the
* component.
*
* For a "regular" ViewRef created for an embedded view, this is the `LView` for the embedded
* view.
*
* @internal
*/
public _lView: LView,
/**
* This represents the `LView` associated with the point where `ChangeDetectorRef` was
* requested.
*
* This may be different from `_lView` if the `_cdRefInjectingView` is an embedded view.
*/
private _cdRefInjectingView?: LView,
readonly notifyErrorHandler = true,
) {}
get context(): T {
return this._lView[CONTEXT] as unknown as T;
}
/**
* Reports whether the given view is considered dirty according to the different marking mechanisms.
*/
get dirty(): boolean {
return (
!!(
this._lView[FLAGS] &
(LViewFlags.Dirty | LViewFlags.RefreshView | LViewFlags.HasChildViewsToRefresh)
) || !!this._lView[REACTIVE_TEMPLATE_CONSUMER]?.dirty
);
}
/**
* @deprecated Replacing the full context object is not supported. Modify the context
* directly, or consider using a `Proxy` if you need to replace the full object.
* // TODO(devversion): Remove this.
*/
set context(value: T) {
if (ngDevMode) {
// Note: We have a warning message here because the `@deprecated` JSDoc will not be picked
// up for assignments on the setter. We want to let users know about the deprecated usage.
console.warn(
'Angular: Replacing the `context` object of an `EmbeddedViewRef` is deprecated.',
);
}
this._lView[CONTEXT] = value as unknown as {};
}
get destroyed(): boolean {
return (this._lView[FLAGS] & LViewFlags.Destroyed) === LViewFlags.Destroyed;
}
destroy(): void {
if (this._appRef) {
this._appRef.detachView(this);
} else if (this._attachedToViewContainer) {
const parent = this._lView[PARENT];
if (isLContainer(parent)) {
const viewRefs = parent[VIEW_REFS] as ViewRef<unknown>[] | null;
const index = viewRefs ? viewRefs.indexOf(this) : -1;
if (index > -1) {
ngDevMode &&
assertEqual(
index,
parent.indexOf(this._lView) - CONTAINER_HEADER_OFFSET,
'An attached view should be in the same position within its container as its ViewRef in the VIEW_REFS array.',
);
detachView(parent, index);
removeFromArray(viewRefs!, index);
}
}
this._attachedToViewContainer = false;
}
destroyLView(this._lView[TVIEW], this._lView);
}
onDestroy(callback: Function) {
storeLViewOnDestroy(this._lView, callback as () => void);
}
/**
* Marks a view and all of its ancestors dirty.
*
* This can be used to ensure an {@link ChangeDetectionStrategy#OnPush} component is
* checked when it needs to be re-rendered but the two normal triggers haven't marked it
* dirty (i.e. inputs haven't changed and events haven't fired in the view).
*
* <!-- TODO: Add a link to a chapter on OnPush components -->
*
* @usageNotes
* ### Example
*
* ```typescript
* @Component({
* selector: 'app-root',
* template: `Number of ticks: {{numberOfTicks}}`
* changeDetection: ChangeDetectionStrategy.OnPush,
* })
* class AppComponent {
* numberOfTicks = 0;
*
* constructor(private ref: ChangeDetectorRef) {
* setInterval(() => {
* this.numberOfTicks++;
* // the following is required, otherwise the view will not be updated
* this.ref.markForCheck();
* }, 1000);
* }
* }
* ```
*/
markForCheck(): void {
markViewDirty(this._cdRefInjectingView || this._lView, NotificationSource.MarkForCheck);
}
markForRefresh(): void {
markViewForRefresh(this._cdRefInjectingView || this._lView);
}
/**
* Detaches the view from the change detection tree.
*
* Detached views will not be checked during change detection runs until they are
* re-attached, even if they are dirty. `detach` can be used in combination with
* {@link ChangeDetectorRef#detectChanges} to implement local change
* detection checks.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
* <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
*
* @usageNotes
* ### Example
*
* The following example defines a component with a large list of readonly data.
* Imagine the data changes constantly, many times per second. For performance reasons,
* we want to check and update the list every five seconds. We can do that by detaching
* the component's change detector and doing a local check every five seconds.
*
* ```typescript
* class DataProvider {
* // in a real application the returned data will be different every time
* get data() {
* return [1,2,3,4,5];
* }
* }
*
* @Component({
* selector: 'giant-list',
* template: `
* <li *ngFor="let d of dataProvider.data">Data {{d}}</li>
* `,
* })
* class GiantList {
* constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {
* ref.detach();
* setInterval(() => {
* this.ref.detectChanges();
* }, 5000);
* }
* }
*
* @Component({
* selector: 'app',
* providers: [DataProvider],
* template: `
* <giant-list><giant-list>
* `,
* })
* class App {
* }
* ```
*/
detach(): void {
this._lView[FLAGS] &= ~LViewFlags.Attached;
}
/**
* Re-attaches a view to the change detection tree.
*
* This can be used to re-attach views that were previously detached from the tree
* using {@link ChangeDetectorRef#detach}. Views are attached to the tree by default.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
*
* @usageNotes
* ### Example
*
* The following example creates a component displaying `live` data. The component will detach
* its change detector from the main change detector tree when the component's live property
* is set to false.
*
* ```typescript
* class DataProvider {
* data = 1;
*
* constructor() {
* setInterval(() => {
* this.data = this.data * 2;
* }, 500);
* }
* }
*
* @Component({
* selector: 'live-data',
* inputs: ['live'],
* template: 'Data: {{dataProvider.data}}'
* })
* class LiveData {
* constructor(private ref: ChangeDetectorRef, private dataProvider: DataProvider) {}
*
* set live(value) {
* if (value) {
* this.ref.reattach();
* } else {
* this.ref.detach();
* }
* }
* }
*
* @Component({
* selector: 'app-root',
* providers: [DataProvider],
* template: `
* Live Update: <input type="checkbox" [(ngModel)]="live">
* <live-data [live]="live"><live-data>
* `,
* })
* class AppComponent {
* live = true;
* }
* ```
*/
| |
011418
|
rt function handleUnknownPropertyError(
propName: string,
tagName: string | null,
nodeType: TNodeType,
lView: LView,
): void {
// Special-case a situation when a structural directive is applied to
// an `<ng-template>` element, for example: `<ng-template *ngIf="true">`.
// In this case the compiler generates the `ɵɵtemplate` instruction with
// the `null` as the tagName. The directive matching logic at runtime relies
// on this effect (see `isInlineTemplate`), thus using the 'ng-template' as
// a default value of the `tNode.value` is not feasible at this moment.
if (!tagName && nodeType === TNodeType.Container) {
tagName = 'ng-template';
}
const isHostStandalone = isHostComponentStandalone(lView);
const templateLocation = getTemplateLocationDetails(lView);
let message = `Can't bind to '${propName}' since it isn't a known property of '${tagName}'${templateLocation}.`;
const schemas = `'${isHostStandalone ? '@Component' : '@NgModule'}.schemas'`;
const importLocation = isHostStandalone
? "included in the '@Component.imports' of this component"
: 'a part of an @NgModule where this component is declared';
if (KNOWN_CONTROL_FLOW_DIRECTIVES.has(propName)) {
// Most likely this is a control flow directive (such as `*ngIf`) used in
// a template, but the directive or the `CommonModule` is not imported.
const correspondingImport = KNOWN_CONTROL_FLOW_DIRECTIVES.get(propName);
message +=
`\nIf the '${propName}' is an Angular control flow directive, ` +
`please make sure that either the '${correspondingImport}' directive or the 'CommonModule' is ${importLocation}.`;
} else {
// May be an Angular component, which is not imported/declared?
message +=
`\n1. If '${tagName}' is an Angular component and it has the ` +
`'${propName}' input, then verify that it is ${importLocation}.`;
// May be a Web Component?
if (tagName && tagName.indexOf('-') > -1) {
message +=
`\n2. If '${tagName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' ` +
`to the ${schemas} of this component to suppress this message.`;
message +=
`\n3. To allow any property add 'NO_ERRORS_SCHEMA' to ` +
`the ${schemas} of this component.`;
} else {
// If it's expected, the error can be suppressed by the `NO_ERRORS_SCHEMA` schema.
message +=
`\n2. To allow any property add 'NO_ERRORS_SCHEMA' to ` +
`the ${schemas} of this component.`;
}
}
reportUnknownPropertyError(message);
}
export function reportUnknownPropertyError(message: string) {
if (shouldThrowErrorOnUnknownProperty) {
throw new RuntimeError(RuntimeErrorCode.UNKNOWN_BINDING, message);
} else {
console.error(formatRuntimeError(RuntimeErrorCode.UNKNOWN_BINDING, message));
}
}
/**
* WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
* and must **not** be used in production bundles. The function makes megamorphic reads, which might
* be too slow for production mode and also it relies on the constructor function being available.
*
* Gets a reference to the host component def (where a current component is declared).
*
* @param lView An `LView` that represents a current component that is being rendered.
*/
export function getDeclarationComponentDef(lView: LView): ComponentDef<unknown> | null {
!ngDevMode && throwError('Must never be called in production mode');
const declarationLView = lView[DECLARATION_COMPONENT_VIEW] as LView<Type<unknown>>;
const context = declarationLView[CONTEXT];
// Unable to obtain a context.
if (!context) return null;
return context.constructor ? getComponentDef(context.constructor) : null;
}
/**
* WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
* and must **not** be used in production bundles. The function makes megamorphic reads, which might
* be too slow for production mode.
*
* Checks if the current component is declared inside of a standalone component template.
*
* @param lView An `LView` that represents a current component that is being rendered.
*/
export function isHostComponentStandalone(lView: LView): boolean {
!ngDevMode && throwError('Must never be called in production mode');
const componentDef = getDeclarationComponentDef(lView);
// Treat host component as non-standalone if we can't obtain the def.
return !!componentDef?.standalone;
}
/**
* WARNING: this is a **dev-mode only** function (thus should always be guarded by the `ngDevMode`)
* and must **not** be used in production bundles. The function makes megamorphic reads, which might
* be too slow for production mode.
*
* Constructs a string describing the location of the host component template. The function is used
* in dev mode to produce error messages.
*
* @param lView An `LView` that represents a current component that is being rendered.
*/
export function getTemplateLocationDetails(lView: LView): string {
!ngDevMode && throwError('Must never be called in production mode');
const hostComponentDef = getDeclarationComponentDef(lView);
const componentClassName = hostComponentDef?.type?.name;
return componentClassName ? ` (used in the '${componentClassName}' component template)` : '';
}
/**
* The set of known control flow directives and their corresponding imports.
* We use this set to produce a more precises error message with a note
* that the `CommonModule` should also be included.
*/
export const KNOWN_CONTROL_FLOW_DIRECTIVES = new Map([
['ngIf', 'NgIf'],
['ngFor', 'NgFor'],
['ngSwitchCase', 'NgSwitchCase'],
['ngSwitchDefault', 'NgSwitchDefault'],
]);
/**
* Returns true if the tag name is allowed by specified schemas.
* @param schemas Array of schemas
* @param tagName Name of the tag
*/
export function matchingSchemas(schemas: SchemaMetadata[] | null, tagName: string | null): boolean {
if (schemas !== null) {
for (let i = 0; i < schemas.length; i++) {
const schema = schemas[i];
if (
schema === NO_ERRORS_SCHEMA ||
(schema === CUSTOM_ELEMENTS_SCHEMA && tagName && tagName.indexOf('-') > -1)
) {
return true;
}
}
}
return false;
}
| |
011481
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {signalAsReadonlyFn, WritableSignal} from './signal';
import {Signal, ValueEqualityFn} from './api';
import {
producerMarkClean,
ReactiveNode,
SIGNAL,
signalSetFn,
signalUpdateFn,
producerUpdateValueVersion,
REACTIVE_NODE,
defaultEquals,
consumerBeforeComputation,
consumerAfterComputation,
producerAccessed,
} from '@angular/core/primitives/signals';
import {performanceMarkFeature} from '../../util/performance';
type ComputationFn<S, D> = (source: S, previous?: {source: S; value: D}) => D;
interface LinkedSignalNode<S, D> extends ReactiveNode {
/**
* Value of the source signal that was used to derive the computed value.
*/
sourceValue: S;
/**
* Current state value, or one of the sentinel values (`UNSET`, `COMPUTING`,
* `ERROR`).
*/
value: D;
/**
* If `value` is `ERRORED`, the error caught from the last computation attempt which will
* be re-thrown.
*/
error: unknown;
/**
* The source function represents reactive dependency based on which the linked state is reset.
*/
source: () => S;
/**
* The computation function which will produce a new value based on the source and, optionally - previous values.
*/
computation: ComputationFn<S, D>;
equal: ValueEqualityFn<D>;
}
export type LinkedSignalGetter<S, D> = (() => D) & {
[SIGNAL]: LinkedSignalNode<S, D>;
};
const identityFn = <T>(v: T) => v;
/**
* Create a linked signal which represents state that is (re)set from a linked reactive expression.
*/
function createLinkedSignal<S, D>(node: LinkedSignalNode<S, D>): WritableSignal<D> {
const linkedSignalGetter = () => {
// Check if the value needs updating before returning it.
producerUpdateValueVersion(node);
// Record that someone looked at this signal.
producerAccessed(node);
if (node.value === ERRORED) {
throw node.error;
}
return node.value;
};
const getter = linkedSignalGetter as LinkedSignalGetter<S, D> & WritableSignal<D>;
getter[SIGNAL] = node;
if (ngDevMode) {
getter.toString = () => `[LinkedSignal: ${getter()}]`;
}
getter.set = (newValue: D) => {
producerUpdateValueVersion(node);
signalSetFn(node, newValue);
producerMarkClean(node);
};
getter.update = (updateFn: (value: D) => D) => {
producerUpdateValueVersion(node);
signalUpdateFn(node, updateFn);
producerMarkClean(node);
};
getter.asReadonly = signalAsReadonlyFn.bind(getter as any) as () => Signal<D>;
return getter;
}
/**
* @experimental
*/
export function linkedSignal<D>(
computation: () => D,
options?: {equal?: ValueEqualityFn<NoInfer<D>>},
): WritableSignal<D>;
export function linkedSignal<S, D>(options: {
source: () => S;
computation: (source: NoInfer<S>, previous?: {source: NoInfer<S>; value: NoInfer<D>}) => D;
equal?: ValueEqualityFn<NoInfer<D>>;
}): WritableSignal<D>;
export function linkedSignal<S, D>(
optionsOrComputation:
| {
source: () => S;
computation: ComputationFn<S, D>;
equal?: ValueEqualityFn<D>;
}
| (() => D),
options?: {equal?: ValueEqualityFn<D>},
): WritableSignal<D> {
performanceMarkFeature('NgSignals');
const isShorthand = typeof optionsOrComputation === 'function';
const node: LinkedSignalNode<unknown, unknown> = Object.create(LINKED_SIGNAL_NODE);
node.source = isShorthand ? optionsOrComputation : optionsOrComputation.source;
if (!isShorthand) {
node.computation = optionsOrComputation.computation as ComputationFn<unknown, unknown>;
}
const equal = isShorthand ? options?.equal : optionsOrComputation.equal;
if (equal) {
node.equal = equal as ValueEqualityFn<unknown>;
}
return createLinkedSignal(node as LinkedSignalNode<S, D>);
}
/**
* A dedicated symbol used before a state value has been set / calculated for the first time.
* Explicitly typed as `any` so we can use it as signal's value.
*/
const UNSET: any = /* @__PURE__ */ Symbol('UNSET');
/**
* A dedicated symbol used in place of a linked signal value to indicate that a given computation
* is in progress. Used to detect cycles in computation chains.
* Explicitly typed as `any` so we can use it as signal's value.
*/
const COMPUTING: any = /* @__PURE__ */ Symbol('COMPUTING');
/**
* A dedicated symbol used in place of a linked signal value to indicate that a given computation
* failed. The thrown error is cached until the computation gets dirty again or the state is set.
* Explicitly typed as `any` so we can use it as signal's value.
*/
const ERRORED: any = /* @__PURE__ */ Symbol('ERRORED');
// Note: Using an IIFE here to ensure that the spread assignment is not considered
// a side-effect, ending up preserving `LINKED_SIGNAL_NODE` and `REACTIVE_NODE`.
// TODO: remove when https://github.com/evanw/esbuild/issues/3392 is resolved.
const LINKED_SIGNAL_NODE = /* @__PURE__ */ (() => {
return {
...REACTIVE_NODE,
value: UNSET,
dirty: true,
error: null,
equal: defaultEquals,
computation: identityFn,
producerMustRecompute(node: LinkedSignalNode<unknown, unknown>): boolean {
// Force a recomputation if there's no current value, or if the current value is in the
// process of being calculated (which should throw an error).
return node.value === UNSET || node.value === COMPUTING;
},
producerRecomputeValue(node: LinkedSignalNode<unknown, unknown>): void {
if (node.value === COMPUTING) {
// Our computation somehow led to a cyclic read of itself.
throw new Error('Detected cycle in computations.');
}
const oldValue = node.value;
node.value = COMPUTING;
const prevConsumer = consumerBeforeComputation(node);
let newValue: unknown;
try {
const newSourceValue = node.source();
const prev =
oldValue === UNSET || oldValue === ERRORED
? undefined
: {
source: node.sourceValue,
value: oldValue,
};
newValue = node.computation(newSourceValue, prev);
node.sourceValue = newSourceValue;
} catch (err) {
newValue = ERRORED;
node.error = err;
} finally {
consumerAfterComputation(node, prevConsumer);
}
if (oldValue !== UNSET && newValue !== ERRORED && node.equal(oldValue, newValue)) {
// No change to `valueVersion` - old and new values are
// semantically equivalent.
node.value = oldValue;
return;
}
node.value = newValue;
node.version++;
},
};
})();
| |
011483
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {createWatch, Watch, WatchCleanupRegisterFn} from '@angular/core/primitives/signals';
import {ChangeDetectorRef} from '../../change_detection/change_detector_ref';
import {Injector} from '../../di/injector';
import {inject} from '../../di/injector_compatibility';
import {ɵɵdefineInjectable} from '../../di/interface/defs';
import {ErrorHandler} from '../../error_handler';
import type {ViewRef} from '../view_ref';
import {DestroyRef} from '../../linker/destroy_ref';
import {FLAGS, LViewFlags, EFFECTS_TO_SCHEDULE} from '../interfaces/view';
import type {CreateEffectOptions, EffectCleanupRegisterFn, EffectRef} from './effect';
import {type SchedulableEffect, ZoneAwareEffectScheduler} from './root_effect_scheduler';
import {performanceMarkFeature} from '../../util/performance';
import {assertNotInReactiveContext} from './asserts';
import {assertInInjectionContext} from '../../di';
import {PendingTasksInternal} from '../../pending_tasks';
export class MicrotaskEffectScheduler extends ZoneAwareEffectScheduler {
private readonly pendingTasks = inject(PendingTasksInternal);
private taskId: number | null = null;
override schedule(effect: SchedulableEffect): void {
// Check whether there are any pending effects _before_ queueing in the base class.
super.schedule(effect);
if (this.taskId === null) {
this.taskId = this.pendingTasks.add();
queueMicrotask(() => this.flush());
}
}
override flush(): void {
try {
super.flush();
} finally {
if (this.taskId !== null) {
this.pendingTasks.remove(this.taskId);
this.taskId = null;
}
}
}
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
token: MicrotaskEffectScheduler,
providedIn: 'root',
factory: () => new MicrotaskEffectScheduler(),
});
}
/**
* Core reactive node for an Angular effect.
*
* `EffectHandle` combines the reactive graph's `Watch` base node for effects with the framework's
* scheduling abstraction (`MicrotaskEffectScheduler`) as well as automatic cleanup via `DestroyRef`
* if available/requested.
*/
class EffectHandle implements EffectRef, SchedulableEffect {
unregisterOnDestroy: (() => void) | undefined;
readonly watcher: Watch;
constructor(
private scheduler: MicrotaskEffectScheduler,
private effectFn: (onCleanup: EffectCleanupRegisterFn) => void,
public zone: Zone | null,
destroyRef: DestroyRef | null,
private injector: Injector,
allowSignalWrites: boolean,
) {
this.watcher = createWatch(
(onCleanup) => this.runEffect(onCleanup),
() => this.schedule(),
allowSignalWrites,
);
this.unregisterOnDestroy = destroyRef?.onDestroy(() => this.destroy());
}
private runEffect(onCleanup: WatchCleanupRegisterFn): void {
try {
this.effectFn(onCleanup);
} catch (err) {
// Inject the `ErrorHandler` here in order to avoid circular DI error
// if the effect is used inside of a custom `ErrorHandler`.
const errorHandler = this.injector.get(ErrorHandler, null, {optional: true});
errorHandler?.handleError(err);
}
}
run(): void {
this.watcher.run();
}
private schedule(): void {
this.scheduler.schedule(this);
}
destroy(): void {
this.watcher.destroy();
this.unregisterOnDestroy?.();
// Note: if the effect is currently scheduled, it's not un-scheduled, and so the scheduler will
// retain a reference to it. Attempting to execute it will be a no-op.
}
}
// Just used for the name for the debug error below.
function effect() {}
/**
* Create a global `Effect` for the given reactive function.
*/
export function microtaskEffect(
effectFn: (onCleanup: EffectCleanupRegisterFn) => void,
options?: CreateEffectOptions,
): EffectRef {
performanceMarkFeature('NgSignals');
ngDevMode &&
assertNotInReactiveContext(
effect,
'Call `effect` outside of a reactive context. For example, schedule the ' +
'effect inside the component constructor.',
);
!options?.injector && assertInInjectionContext(effect);
const injector = options?.injector ?? inject(Injector);
const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
const handle = new EffectHandle(
injector.get(MicrotaskEffectScheduler),
effectFn,
typeof Zone === 'undefined' ? null : Zone.current,
destroyRef,
injector,
options?.allowSignalWrites ?? false,
);
// Effects need to be marked dirty manually to trigger their initial run. The timing of this
// marking matters, because the effects may read signals that track component inputs, which are
// only available after those components have had their first update pass.
//
// We inject `ChangeDetectorRef` optionally, to determine whether this effect is being created in
// the context of a component or not. If it is, then we check whether the component has already
// run its update pass, and defer the effect's initial scheduling until the update pass if it
// hasn't already run.
const cdr = injector.get(ChangeDetectorRef, null, {optional: true}) as ViewRef<unknown> | null;
if (!cdr || !(cdr._lView[FLAGS] & LViewFlags.FirstLViewPass)) {
// This effect is either not running in a view injector, or the view has already
// undergone its first change detection pass, which is necessary for any required inputs to be
// set.
handle.watcher.notify();
} else {
// Delay the initialization of the effect until the view is fully initialized.
(cdr._lView[EFFECTS_TO_SCHEDULE] ??= []).push(handle.watcher.notify);
}
return handle;
}
| |
011484
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {SIGNAL} from '@angular/core/primitives/signals';
/**
* A reactive value which notifies consumers of any changes.
*
* Signals are functions which returns their current value. To access the current value of a signal,
* call it.
*
* Ordinary values can be turned into `Signal`s with the `signal` function.
*/
export type Signal<T> = (() => T) & {
[SIGNAL]: unknown;
};
/**
* Checks if the given `value` is a reactive `Signal`.
*/
export function isSignal(value: unknown): value is Signal<unknown> {
return typeof value === 'function' && (value as Signal<unknown>)[SIGNAL] !== undefined;
}
/**
* A comparison function which can determine if two values are equal.
*/
export type ValueEqualityFn<T> = (a: T, b: T) => boolean;
| |
011486
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
createSignal,
SIGNAL,
SignalGetter,
SignalNode,
signalSetFn,
signalUpdateFn,
} from '@angular/core/primitives/signals';
import {performanceMarkFeature} from '../../util/performance';
import {isSignal, Signal, ValueEqualityFn} from './api';
/** Symbol used distinguish `WritableSignal` from other non-writable signals and functions. */
export const ɵWRITABLE_SIGNAL = /* @__PURE__ */ Symbol('WRITABLE_SIGNAL');
/**
* A `Signal` with a value that can be mutated via a setter interface.
*/
export interface WritableSignal<T> extends Signal<T> {
[ɵWRITABLE_SIGNAL]: T;
/**
* Directly set the signal to a new value, and notify any dependents.
*/
set(value: T): void;
/**
* Update the value of the signal based on its current value, and
* notify any dependents.
*/
update(updateFn: (value: T) => T): void;
/**
* Returns a readonly version of this signal. Readonly signals can be accessed to read their value
* but can't be changed using set or update methods. The readonly signals do _not_ have
* any built-in mechanism that would prevent deep-mutation of their value.
*/
asReadonly(): Signal<T>;
}
/**
* Utility function used during template type checking to extract the value from a `WritableSignal`.
* @codeGenApi
*/
export function ɵunwrapWritableSignal<T>(value: T | {[ɵWRITABLE_SIGNAL]: T}): T {
// Note: the function uses `WRITABLE_SIGNAL` as a brand instead of `WritableSignal<T>`,
// because the latter incorrectly unwraps non-signal getter functions.
return null!;
}
/**
* Options passed to the `signal` creation function.
*/
export interface CreateSignalOptions<T> {
/**
* A comparison function which defines equality for signal values.
*/
equal?: ValueEqualityFn<T>;
/**
* A debug name for the signal. Used in Angular DevTools to identify the signal.
*/
debugName?: string;
}
/**
* Create a `Signal` that can be set or updated directly.
*/
export function signal<T>(initialValue: T, options?: CreateSignalOptions<T>): WritableSignal<T> {
performanceMarkFeature('NgSignals');
const signalFn = createSignal(initialValue) as SignalGetter<T> & WritableSignal<T>;
const node = signalFn[SIGNAL];
if (options?.equal) {
node.equal = options.equal;
}
signalFn.set = (newValue: T) => signalSetFn(node, newValue);
signalFn.update = (updateFn: (value: T) => T) => signalUpdateFn(node, updateFn);
signalFn.asReadonly = signalAsReadonlyFn.bind(signalFn as any) as () => Signal<T>;
if (ngDevMode) {
signalFn.toString = () => `[Signal: ${signalFn()}]`;
node.debugName = options?.debugName;
}
return signalFn as WritableSignal<T>;
}
export function signalAsReadonlyFn<T>(this: SignalGetter<T>): Signal<T> {
const node = this[SIGNAL] as SignalNode<T> & {readonlyFn?: Signal<T>};
if (node.readonlyFn === undefined) {
const readonlyFn = () => this();
(readonlyFn as any)[SIGNAL] = node;
node.readonlyFn = readonlyFn as Signal<T>;
}
return node.readonlyFn;
}
/**
* Checks if the given `value` is a writeable signal.
*/
export function isWritableSignal(value: unknown): value is WritableSignal<unknown> {
return isSignal(value) && typeof (value as any).set === 'function';
}
| |
011487
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {createComputed, SIGNAL} from '@angular/core/primitives/signals';
import {performanceMarkFeature} from '../../util/performance';
import {Signal, ValueEqualityFn} from './api';
/**
* Options passed to the `computed` creation function.
*/
export interface CreateComputedOptions<T> {
/**
* A comparison function which defines equality for computed values.
*/
equal?: ValueEqualityFn<T>;
/**
* A debug name for the computed signal. Used in Angular DevTools to identify the signal.
*/
debugName?: string;
}
/**
* Create a computed `Signal` which derives a reactive value from an expression.
*/
export function computed<T>(computation: () => T, options?: CreateComputedOptions<T>): Signal<T> {
performanceMarkFeature('NgSignals');
const getter = createComputed(computation);
if (options?.equal) {
getter[SIGNAL].equal = options.equal;
}
if (ngDevMode) {
getter.toString = () => `[Computed: ${getter()}]`;
getter[SIGNAL].debugName = options?.debugName;
}
return getter;
}
| |
011528
|
* Register callbacks to be invoked the next time the application finishes rendering, during the
* specified phases. The available phases are:
* - `earlyRead`
* Use this phase to **read** from the DOM before a subsequent `write` callback, for example to
* perform custom layout that the browser doesn't natively support. Prefer the `read` phase if
* reading can wait until after the write phase. **Never** write to the DOM in this phase.
* - `write`
* Use this phase to **write** to the DOM. **Never** read from the DOM in this phase.
* - `mixedReadWrite`
* Use this phase to read from and write to the DOM simultaneously. **Never** use this phase if
* it is possible to divide the work among the other phases instead.
* - `read`
* Use this phase to **read** from the DOM. **Never** write to the DOM in this phase.
*
* <div class="alert is-critical">
*
* You should prefer using the `read` and `write` phases over the `earlyRead` and `mixedReadWrite`
* phases when possible, to avoid performance degradation.
*
* </div>
*
* Note that:
* - Callbacks run in the following phase order *once, after the next render*:
* 1. `earlyRead`
* 2. `write`
* 3. `mixedReadWrite`
* 4. `read`
* - Callbacks in the same phase run in the order they are registered.
* - Callbacks run on browser platforms only, they will not run on the server.
*
* The first phase callback to run as part of this spec will receive no parameters. Each
* subsequent phase callback in this spec will receive the return value of the previously run
* phase callback as a parameter. This can be used to coordinate work across multiple phases.
*
* Angular is unable to verify or enforce that phases are used correctly, and instead
* relies on each developer to follow the guidelines documented for each value and
* carefully choose the appropriate one, refactoring their code if necessary. By doing
* so, Angular is better able to minimize the performance degradation associated with
* manual DOM access, ensuring the best experience for the end users of your application
* or library.
*
* <div class="alert is-important">
*
* Components are not guaranteed to be [hydrated](guide/hydration) before the callback runs.
* You must use caution when directly reading or writing the DOM and layout.
*
* </div>
*
* @param spec The callback functions to register
* @param options Options to control the behavior of the callback
*
* @usageNotes
*
* Use `afterNextRender` to read or write the DOM once,
* for example to initialize a non-Angular library.
*
* ### Example
* ```ts
* @Component({
* selector: 'my-chart-cmp',
* template: `<div #chart>{{ ... }}</div>`,
* })
* export class MyChartCmp {
* @ViewChild('chart') chartRef: ElementRef;
* chart: MyChart|null;
*
* constructor() {
* afterNextRender({
* write: () => {
* this.chart = new MyChart(this.chartRef.nativeElement);
* }
* });
* }
* }
* ```
*
* @developerPreview
*/
export function afterNextRender<E = never, W = never, M = never>(
spec: {
earlyRead?: () => E;
write?: (...args: ɵFirstAvailable<[E]>) => W;
mixedReadWrite?: (...args: ɵFirstAvailable<[W, E]>) => M;
read?: (...args: ɵFirstAvailable<[M, W, E]>) => void;
},
options?: Omit<AfterRenderOptions, 'phase'>,
): AfterRenderRef;
/**
* Register a callback to be invoked the next time the application finishes rendering, during the
* `mixedReadWrite` phase.
*
* <div class="alert is-critical">
*
* You should prefer specifying an explicit phase for the callback instead, or you risk significant
* performance degradation.
*
* </div>
*
* Note that the callback will run
* - in the order it was registered
* - on browser platforms only
* - during the `mixedReadWrite` phase
*
* <div class="alert is-important">
*
* Components are not guaranteed to be [hydrated](guide/hydration) before the callback runs.
* You must use caution when directly reading or writing the DOM and layout.
*
* </div>
*
* @param callback A callback function to register
* @param options Options to control the behavior of the callback
*
* @usageNotes
*
* Use `afterNextRender` to read or write the DOM once,
* for example to initialize a non-Angular library.
*
* ### Example
* ```ts
* @Component({
* selector: 'my-chart-cmp',
* template: `<div #chart>{{ ... }}</div>`,
* })
* export class MyChartCmp {
* @ViewChild('chart') chartRef: ElementRef;
* chart: MyChart|null;
*
* constructor() {
* afterNextRender({
* write: () => {
* this.chart = new MyChart(this.chartRef.nativeElement);
* }
* });
* }
* }
* ```
*
* @developerPreview
*/
export function afterNextRender(
callback: VoidFunction,
options?: AfterRenderOptions,
): AfterRenderRef;
export function afterNextRender(
callbackOrSpec:
| VoidFunction
| {
earlyRead?: () => unknown;
write?: (r?: unknown) => unknown;
mixedReadWrite?: (r?: unknown) => unknown;
read?: (r?: unknown) => void;
},
options?: AfterRenderOptions,
): AfterRenderRef {
!options?.injector && assertInInjectionContext(afterNextRender);
const injector = options?.injector ?? inject(Injector);
if (!isPlatformBrowser(injector)) {
return NOOP_AFTER_RENDER_REF;
}
performanceMarkFeature('NgAfterNextRender');
return afterRenderImpl(callbackOrSpec, injector, options, /* once */ true);
}
function getHooks(
callbackOrSpec:
| VoidFunction
| {
earlyRead?: () => unknown;
write?: (r?: unknown) => unknown;
mixedReadWrite?: (r?: unknown) => unknown;
read?: (r?: unknown) => void;
},
phase: AfterRenderPhase,
): AfterRenderHooks {
if (callbackOrSpec instanceof Function) {
const hooks: AfterRenderHooks = [undefined, undefined, undefined, undefined];
hooks[phase] = callbackOrSpec;
return hooks;
} else {
return [
callbackOrSpec.earlyRead,
callbackOrSpec.write,
callbackOrSpec.mixedReadWrite,
callbackOrSpec.read,
];
}
}
/**
* Shared implementation for `afterRender` and `afterNextRender`.
*/
function afterRenderImpl(
callbackOrSpec:
| VoidFunction
| {
earlyRead?: () => unknown;
write?: (r?: unknown) => unknown;
mixedReadWrite?: (r?: unknown) => unknown;
read?: (r?: unknown) => void;
},
injector: Injector,
options: AfterRenderOptions | undefined,
once: boolean,
): AfterRenderRef {
const manager = injector.get(AfterRenderManager);
// Lazily initialize the handler implementation, if necessary. This is so that it can be
// tree-shaken if `afterRender` and `afterNextRender` aren't used.
manager.impl ??= injector.get(AfterRenderImpl);
const hooks = options?.phase ?? AfterRenderPhase.MixedReadWrite;
const destroyRef = options?.manualCleanup !== true ? injector.get(DestroyRef) : null;
const sequence = new AfterRenderSequence(
manager.impl,
getHooks(callbackOrSpec, hooks),
once,
destroyRef,
);
manager.impl.register(sequence);
return sequence;
}
/** `AfterRenderRef` that does nothing. */
export const NOOP_AFTER_RENDER_REF: AfterRenderRef = {
destroy() {},
};
| |
011563
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This file contains types that will be published to npm in library typings files.
// Formatting does horrible things to these declarations.
/**
* @publicApi
*/
export type ɵɵDirectiveDeclaration<
T,
Selector extends string,
ExportAs extends string[],
// `string` keys are for backwards compatibility with pre-16 versions.
InputMap extends {
[key: string]: string | {alias: string | null; required: boolean; isSignal?: boolean};
},
OutputMap extends {[key: string]: string},
QueryFields extends string[],
// Optional as this was added to align the `IsStandalone` parameters
// between directive and component declarations.
NgContentSelectors extends never = never,
// Optional as this was added in Angular v14. All pre-existing directives
// are not standalone.
IsStandalone extends boolean = false,
HostDirectives = never,
IsSignal extends boolean = false,
> = unknown;
/**
* @publicApi
*/
export type ɵɵComponentDeclaration<
T,
Selector extends String,
ExportAs extends string[],
// `string` keys are for backwards compatibility with pre-16 versions.
InputMap extends {[key: string]: string | {alias: string | null; required: boolean}},
OutputMap extends {[key: string]: string},
QueryFields extends string[],
NgContentSelectors extends string[],
// Optional as this was added in Angular v14. All pre-existing components
// are not standalone.
IsStandalone extends boolean = false,
HostDirectives = never,
IsSignal extends boolean = false,
> = unknown;
/**
* @publicApi
*/
export type ɵɵNgModuleDeclaration<T, Declarations, Imports, Exports> = unknown;
/**
* @publicApi
*/
export type ɵɵPipeDeclaration<
T,
Name extends string,
// Optional as this was added in Angular v14. All pre-existing directives
// are not standalone.
IsStandalone extends boolean = false,
> = unknown;
/**
* @publicApi
*/
export type ɵɵInjectorDeclaration<T> = unknown;
/**
* @publicApi
*/
export type ɵɵFactoryDeclaration<T, CtorDependencies extends CtorDependency[]> = unknown;
/**
* An object literal of this type is used to represent the metadata of a constructor dependency.
* The type itself is never referred to from generated code.
*
* @publicApi
*/
export type CtorDependency = {
/**
* If an `@Attribute` decorator is used, this represents the injected attribute's name. If the
* attribute name is a dynamic expression instead of a string literal, this will be the unknown
* type.
*/
attribute?: string | unknown;
/**
* If `@Optional()` is used, this key is set to true.
*/
optional?: true;
/**
* If `@Host` is used, this key is set to true.
*/
host?: true;
/**
* If `@Self` is used, this key is set to true.
*/
self?: true;
/**
* If `@SkipSelf` is used, this key is set to true.
*/
skipSelf?: true;
} | null;
| |
011571
|
/**
* A reference to an Angular application running on a page.
*
* @usageNotes
* {@a is-stable-examples}
* ### isStable examples and caveats
*
* Note two important points about `isStable`, demonstrated in the examples below:
* - the application will never be stable if you start any kind
* of recurrent asynchronous task when the application starts
* (for example for a polling process, started with a `setInterval`, a `setTimeout`
* or using RxJS operators like `interval`);
* - the `isStable` Observable runs outside of the Angular zone.
*
* Let's imagine that you start a recurrent task
* (here incrementing a counter, using RxJS `interval`),
* and at the same time subscribe to `isStable`.
*
* ```
* constructor(appRef: ApplicationRef) {
* appRef.isStable.pipe(
* filter(stable => stable)
* ).subscribe(() => console.log('App is stable now');
* interval(1000).subscribe(counter => console.log(counter));
* }
* ```
* In this example, `isStable` will never emit `true`,
* and the trace "App is stable now" will never get logged.
*
* If you want to execute something when the app is stable,
* you have to wait for the application to be stable
* before starting your polling process.
*
* ```
* constructor(appRef: ApplicationRef) {
* appRef.isStable.pipe(
* first(stable => stable),
* tap(stable => console.log('App is stable now')),
* switchMap(() => interval(1000))
* ).subscribe(counter => console.log(counter));
* }
* ```
* In this example, the trace "App is stable now" will be logged
* and then the counter starts incrementing every second.
*
* Note also that this Observable runs outside of the Angular zone,
* which means that the code in the subscription
* to this Observable will not trigger the change detection.
*
* Let's imagine that instead of logging the counter value,
* you update a field of your component
* and display it in its template.
*
* ```
* constructor(appRef: ApplicationRef) {
* appRef.isStable.pipe(
* first(stable => stable),
* switchMap(() => interval(1000))
* ).subscribe(counter => this.value = counter);
* }
* ```
* As the `isStable` Observable runs outside the zone,
* the `value` field will be updated properly,
* but the template will not be refreshed!
*
* You'll have to manually trigger the change detection to update the template.
*
* ```
* constructor(appRef: ApplicationRef, cd: ChangeDetectorRef) {
* appRef.isStable.pipe(
* first(stable => stable),
* switchMap(() => interval(1000))
* ).subscribe(counter => {
* this.value = counter;
* cd.detectChanges();
* });
* }
* ```
*
* Or make the subscription callback run inside the zone.
*
* ```
* constructor(appRef: ApplicationRef, zone: NgZone) {
* appRef.isStable.pipe(
* first(stable => stable),
* switchMap(() => interval(1000))
* ).subscribe(counter => zone.run(() => this.value = counter));
* }
* ```
*
* @publicApi
*/
| |
011575
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {InjectionToken} from '../di/injection_token';
import {getDocument} from '../render3/interfaces/document';
/**
* A DI token representing a string ID, used
* primarily for prefixing application attributes and CSS styles when
* {@link ViewEncapsulation#Emulated} is being used.
*
* The token is needed in cases when multiple applications are bootstrapped on a page
* (for example, using `bootstrapApplication` calls). In this case, ensure that those applications
* have different `APP_ID` value setup. For example:
*
* ```
* bootstrapApplication(ComponentA, {
* providers: [
* { provide: APP_ID, useValue: 'app-a' },
* // ... other providers ...
* ]
* });
*
* bootstrapApplication(ComponentB, {
* providers: [
* { provide: APP_ID, useValue: 'app-b' },
* // ... other providers ...
* ]
* });
* ```
*
* By default, when there is only one application bootstrapped, you don't need to provide the
* `APP_ID` token (the `ng` will be used as an app ID).
*
* @publicApi
*/
export const APP_ID = new InjectionToken<string>(ngDevMode ? 'AppId' : '', {
providedIn: 'root',
factory: () => DEFAULT_APP_ID,
});
/** Default value of the `APP_ID` token. */
const DEFAULT_APP_ID = 'ng';
/**
* A function that is executed when a platform is initialized.
*
* @deprecated from v19.0.0, use providePlatformInitializer instead
*
* @see {@link providePlatformInitializer}
*
* @publicApi
*/
export const PLATFORM_INITIALIZER = new InjectionToken<ReadonlyArray<() => void>>(
ngDevMode ? 'Platform Initializer' : '',
);
/**
* A token that indicates an opaque platform ID.
* @publicApi
*/
export const PLATFORM_ID = new InjectionToken<Object>(ngDevMode ? 'Platform ID' : '', {
providedIn: 'platform',
factory: () => 'unknown', // set a default platform name, when none set explicitly
});
/**
* A DI token that indicates the root directory of
* the application
* @publicApi
* @deprecated
*/
export const PACKAGE_ROOT_URL = new InjectionToken<string>(
ngDevMode ? 'Application Packages Root URL' : '',
);
// We keep this token here, rather than the animations package, so that modules that only care
// about which animations module is loaded (e.g. the CDK) can retrieve it without having to
// include extra dependencies. See #44970 for more context.
/**
* A [DI token](api/core/InjectionToken) that indicates which animations
* module has been loaded.
* @publicApi
*/
export const ANIMATION_MODULE_TYPE = new InjectionToken<'NoopAnimations' | 'BrowserAnimations'>(
ngDevMode ? 'AnimationModuleType' : '',
);
// TODO(crisbeto): link to CSP guide here.
/**
* Token used to configure the [Content Security Policy](https://web.dev/strict-csp/) nonce that
* Angular will apply when inserting inline styles. If not provided, Angular will look up its value
* from the `ngCspNonce` attribute of the application root node.
*
* @publicApi
*/
export const CSP_NONCE = new InjectionToken<string | null>(ngDevMode ? 'CSP nonce' : '', {
providedIn: 'root',
factory: () => {
// Ideally we wouldn't have to use `querySelector` here since we know that the nonce will be on
// the root node, but because the token value is used in renderers, it has to be available
// *very* early in the bootstrapping process. This should be a fairly shallow search, because
// the app won't have been added to the DOM yet. Some approaches that were considered:
// 1. Find the root node through `ApplicationRef.components[i].location` - normally this would
// be enough for our purposes, but the token is injected very early so the `components` array
// isn't populated yet.
// 2. Find the root `LView` through the current `LView` - renderers are a prerequisite to
// creating the `LView`. This means that no `LView` will have been entered when this factory is
// invoked for the root component.
// 3. Have the token factory return `() => string` which is invoked when a nonce is requested -
// the slightly later execution does allow us to get an `LView` reference, but the fact that
// it is a function means that it could be executed at *any* time (including immediately) which
// may lead to weird bugs.
// 4. Have the `ComponentFactory` read the attribute and provide it to the injector under the
// hood - has the same problem as #1 and #2 in that the renderer is used to query for the root
// node and the nonce value needs to be available when the renderer is created.
return getDocument().body?.querySelector('[ngCspNonce]')?.getAttribute('ngCspNonce') || null;
},
});
/**
* A configuration object for the image-related options. Contains:
* - breakpoints: An array of integer breakpoints used to generate
* srcsets for responsive images.
* - disableImageSizeWarning: A boolean value. Setting this to true will
* disable console warnings about oversized images.
* - disableImageLazyLoadWarning: A boolean value. Setting this to true will
* disable console warnings about LCP images configured with `loading="lazy"`.
* Learn more about the responsive image configuration in [the NgOptimizedImage
* guide](guide/image-optimization).
* Learn more about image warning options in [the related error page](errors/NG0913).
* @publicApi
*/
export type ImageConfig = {
breakpoints?: number[];
placeholderResolution?: number;
disableImageSizeWarning?: boolean;
disableImageLazyLoadWarning?: boolean;
};
export const IMAGE_CONFIG_DEFAULTS: ImageConfig = {
breakpoints: [16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840],
placeholderResolution: 30,
disableImageSizeWarning: false,
disableImageLazyLoadWarning: false,
};
/**
* Injection token that configures the image optimized image functionality.
* See {@link ImageConfig} for additional information about parameters that
* can be used.
*
* @see {@link NgOptimizedImage}
* @see {@link ImageConfig}
* @publicApi
*/
export const IMAGE_CONFIG = new InjectionToken<ImageConfig>(ngDevMode ? 'ImageConfig' : '', {
providedIn: 'root',
factory: () => IMAGE_CONFIG_DEFAULTS,
});
| |
011576
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Observable} from 'rxjs';
import {
EnvironmentProviders,
inject,
Injectable,
InjectionToken,
Injector,
makeEnvironmentProviders,
runInInjectionContext,
} from '../di';
import {RuntimeError, RuntimeErrorCode} from '../errors';
import {isPromise, isSubscribable} from '../util/lang';
/**
* A DI token that you can use to provide
* one or more initialization functions.
*
* The provided functions are injected at application startup and executed during
* app initialization. If any of these functions returns a Promise or an Observable, initialization
* does not complete until the Promise is resolved or the Observable is completed.
*
* You can, for example, create a factory function that loads language data
* or an external configuration, and provide that function to the `APP_INITIALIZER` token.
* The function is executed during the application bootstrap process,
* and the needed data is available on startup.
*
* Note that the provided initializer is run in the injection context.
*
* @deprecated from v19.0.0, use provideAppInitializer instead
*
* @see {@link ApplicationInitStatus}
* @see {@link provideAppInitializer}
*
* @usageNotes
*
* The following example illustrates how to configure a multi-provider using `APP_INITIALIZER` token
* and a function returning a promise.
* ### Example with NgModule-based application
* ```
* function initializeApp(): Promise<any> {
* const http = inject(HttpClient);
* return firstValueFrom(
* http
* .get("https://someUrl.com/api/user")
* .pipe(tap(user => { ... }))
* );
* }
*
* @NgModule({
* imports: [BrowserModule],
* declarations: [AppComponent],
* bootstrap: [AppComponent],
* providers: [{
* provide: APP_INITIALIZER,
* useValue: initializeApp,
* multi: true,
* }]
* })
* export class AppModule {}
* ```
*
* ### Example with standalone application
* ```
* function initializeApp() {
* const http = inject(HttpClient);
* return firstValueFrom(
* http
* .get("https://someUrl.com/api/user")
* .pipe(tap(user => { ... }))
* );
* }
*
* bootstrapApplication(App, {
* providers: [
* provideHttpClient(),
* {
* provide: APP_INITIALIZER,
* useValue: initializeApp,
* multi: true,
* },
* ],
* });
* ```
*
*
* It's also possible to configure a multi-provider using `APP_INITIALIZER` token and a function
* returning an observable, see an example below. Note: the `HttpClient` in this example is used for
* demo purposes to illustrate how the factory function can work with other providers available
* through DI.
*
* ### Example with NgModule-based application
* ```
* function initializeApp() {
* const http = inject(HttpClient);
* return firstValueFrom(
* http
* .get("https://someUrl.com/api/user")
* .pipe(tap(user => { ... }))
* );
* }
*
* @NgModule({
* imports: [BrowserModule, HttpClientModule],
* declarations: [AppComponent],
* bootstrap: [AppComponent],
* providers: [{
* provide: APP_INITIALIZER,
* useValue: initializeApp,
* multi: true,
* }]
* })
* export class AppModule {}
* ```
*
* ### Example with standalone application
* ```
* function initializeApp() {
* const http = inject(HttpClient);
* return firstValueFrom(
* http
* .get("https://someUrl.com/api/user")
* .pipe(tap(user => { ... }))
* );
* }
*
* bootstrapApplication(App, {
* providers: [
* provideHttpClient(),
* {
* provide: APP_INITIALIZER,
* useValue: initializeApp,
* multi: true,
* },
* ],
* });
* ```
*
* @publicApi
*/
export const APP_INITIALIZER = new InjectionToken<
ReadonlyArray<() => Observable<unknown> | Promise<unknown> | void>
>(ngDevMode ? 'Application Initializer' : '');
/**
* @description
* The provided function is injected at application startup and executed during
* app initialization. If the function returns a Promise or an Observable, initialization
* does not complete until the Promise is resolved or the Observable is completed.
*
* You can, for example, create a function that loads language data
* or an external configuration, and provide that function using `provideAppInitializer()`.
* The function is executed during the application bootstrap process,
* and the needed data is available on startup.
*
* Note that the provided initializer is run in the injection context.
*
* Previously, this was achieved using the `APP_INITIALIZER` token which is now deprecated.
*
* @see {@link APP_INITIALIZER}
*
* @usageNotes
* The following example illustrates how to configure an initialization function using
* `provideAppInitializer()`
* ```
* bootstrapApplication(App, {
* providers: [
* provideAppInitializer(() => {
* const http = inject(HttpClient);
* return firstValueFrom(
* http
* .get("https://someUrl.com/api/user")
* .pipe(tap(user => { ... }))
* );
* }),
* provideHttpClient(),
* ],
* });
* ```
*
* @publicApi
*/
export function provideAppInitializer(
initializerFn: () => Observable<unknown> | Promise<unknown> | void,
): EnvironmentProviders {
return makeEnvironmentProviders([
{
provide: APP_INITIALIZER,
multi: true,
useValue: initializerFn,
},
]);
}
/**
* A class that reflects the state of running {@link APP_INITIALIZER} functions.
*
* @publicApi
*/
@Injectable({providedIn: 'root'})
export class ApplicationInitStatus {
// Using non null assertion, these fields are defined below
// within the `new Promise` callback (synchronously).
private resolve!: (...args: any[]) => void;
private reject!: (...args: any[]) => void;
private initialized = false;
public readonly done = false;
public readonly donePromise: Promise<any> = new Promise((res, rej) => {
this.resolve = res;
this.reject = rej;
});
private readonly appInits = inject(APP_INITIALIZER, {optional: true}) ?? [];
private readonly injector = inject(Injector);
constructor() {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && !Array.isArray(this.appInits)) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_MULTI_PROVIDER,
'Unexpected type of the `APP_INITIALIZER` token value ' +
`(expected an array, but got ${typeof this.appInits}). ` +
'Please check that the `APP_INITIALIZER` token is configured as a ' +
'`multi: true` provider.',
);
}
}
/** @internal */
runInitializers() {
if (this.initialized) {
return;
}
const asyncInitPromises = [];
for (const appInits of this.appInits) {
const initResult = runInInjectionContext(this.injector, appInits);
if (isPromise(initResult)) {
asyncInitPromises.push(initResult);
} else if (isSubscribable(initResult)) {
const observableAsPromise = new Promise<void>((resolve, reject) => {
initResult.subscribe({complete: resolve, error: reject});
});
asyncInitPromises.push(observableAsPromise);
}
}
const complete = () => {
// @ts-expect-error overwriting a readonly
this.done = true;
this.resolve();
};
Promise.all(asyncInitPromises)
.then(() => {
complete();
})
.catch((e) => {
this.reject(e);
});
if (asyncInitPromises.length === 0) {
complete();
}
this.initialized = true;
}
}
| |
011603
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {EnvironmentProviders, ModuleWithProviders, Provider} from '../di/interface/provider';
import {Type} from '../interface/type';
import {SchemaMetadata} from '../metadata/schema';
import {compileNgModule} from '../render3/jit/module';
import {makeDecorator, TypeDecorator} from '../util/decorators';
/**
* Type of the NgModule decorator / constructor function.
*
* @publicApi
*/
export interface NgModuleDecorator {
/**
* Decorator that marks a class as an NgModule and supplies configuration metadata.
*/
(obj?: NgModule): TypeDecorator;
new (obj?: NgModule): NgModule;
}
/**
* Type of the NgModule metadata.
*
* @publicApi
*/
export interface NgModule {
/**
* The set of injectable objects that are available in the injector
* of this module.
*
* @see [Dependency Injection guide](guide/di/dependency-injection
* @see [NgModule guide](guide/ngmodules/providers)
*
* @usageNotes
*
* Dependencies whose providers are listed here become available for injection
* into any component, directive, pipe or service that is a child of this injector.
* The NgModule used for bootstrapping uses the root injector, and can provide dependencies
* to any part of the app.
*
* A lazy-loaded module has its own injector, typically a child of the app root injector.
* Lazy-loaded services are scoped to the lazy-loaded module's injector.
* If a lazy-loaded module also provides the `UserService`, any component created
* within that module's context (such as by router navigation) gets the local instance
* of the service, not the instance in the root injector.
* Components in external modules continue to receive the instance provided by their injectors.
*
* ### Example
*
* The following example defines a class that is injected in
* the HelloWorld NgModule:
*
* ```
* class Greeter {
* greet(name:string) {
* return 'Hello ' + name + '!';
* }
* }
*
* @NgModule({
* providers: [
* Greeter
* ]
* })
* class HelloWorld {
* greeter:Greeter;
*
* constructor(greeter:Greeter) {
* this.greeter = greeter;
* }
* }
* ```
*/
providers?: Array<Provider | EnvironmentProviders>;
/**
* The set of components, directives, and pipes (declarables
* that belong to this module.
*
* @usageNotes
*
* The set of selectors that are available to a template include those declared here, and
* those that are exported from imported NgModules.
*
* Declarables must belong to exactly one module.
* The compiler emits an error if you try to declare the same class in more than one module.
* Be careful not to declare a class that is imported from another module.
*
* ### Example
*
* The following example allows the CommonModule to use the `NgFor`
* directive.
*
* ```javascript
* @NgModule({
* declarations: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
declarations?: Array<Type<any> | any[]>;
/**
* The set of NgModules whose exported declarables
* are available to templates in this module.
*
* @usageNotes
*
* A template can use exported declarables from any
* imported module, including those from modules that are imported indirectly
* and re-exported.
* For example, `ModuleA` imports `ModuleB`, and also exports
* it, which makes the declarables from `ModuleB` available
* wherever `ModuleA` is imported.
*
* ### Example
*
* The following example allows MainModule to use anything exported by
* `CommonModule`:
*
* ```javascript
* @NgModule({
* imports: [CommonModule]
* })
* class MainModule {
* }
* ```
*
*/
imports?: Array<Type<any> | ModuleWithProviders<{}> | any[]>;
/**
* The set of components, directives, and pipes declared in this
* NgModule that can be used in the template of any component that is part of an
* NgModule that imports this NgModule. Exported declarations are the module's public API.
*
* A declarable belongs to one and only one NgModule.
* A module can list another module among its exports, in which case all of that module's
* public declaration are exported.
*
* @usageNotes
*
* Declarations are private by default.
* If this ModuleA does not export UserComponent, then only the components within this
* ModuleA can use UserComponent.
*
* ModuleA can import ModuleB and also export it, making exports from ModuleB
* available to an NgModule that imports ModuleA.
*
* ### Example
*
* The following example exports the `NgFor` directive from CommonModule.
*
* ```javascript
* @NgModule({
* exports: [NgFor]
* })
* class CommonModule {
* }
* ```
*/
exports?: Array<Type<any> | any[]>;
/**
* The set of components that are bootstrapped when this module is bootstrapped.
*/
bootstrap?: Array<Type<any> | any[]>;
/**
* The set of schemas that declare elements to be allowed in the NgModule.
* Elements and properties that are neither Angular components nor directives
* must be declared in a schema.
*
* Allowed value are `NO_ERRORS_SCHEMA` and `CUSTOM_ELEMENTS_SCHEMA`.
*
* @security When using one of `NO_ERRORS_SCHEMA` or `CUSTOM_ELEMENTS_SCHEMA`
* you must ensure that allowed elements and properties securely escape inputs.
*/
schemas?: Array<SchemaMetadata | any[]>;
/**
* A name or path that uniquely identifies this NgModule in `getNgModuleById`.
* If left `undefined`, the NgModule is not registered with `getNgModuleById`.
*/
id?: string;
/**
* When present, this module is ignored by the AOT compiler.
* It remains in distributed code, and the JIT compiler attempts to compile it
* at run time, in the browser.
* To ensure the correct behavior, the app must import `@angular/compiler`.
*/
jit?: true;
}
/**
* @Annotation
*/
export const NgModule: NgModuleDecorator = makeDecorator(
'NgModule',
(ngModule: NgModule) => ngModule,
undefined,
undefined,
/**
* Decorator that marks the following class as an NgModule, and supplies
* configuration metadata for it.
*
* * The `declarations` option configures the compiler
* with information about what belongs to the NgModule.
* * The `providers` options configures the NgModule's injector to provide
* dependencies the NgModule members.
* * The `imports` and `exports` options bring in members from other modules, and make
* this module's members available to others.
*/
(type: Type<any>, meta: NgModule) => compileNgModule(type, meta),
);
| |
011609
|
export interface Component extends Directive {
/**
* The change-detection strategy to use for this component.
*
* When a component is instantiated, Angular creates a change detector,
* which is responsible for propagating the component's bindings.
* The strategy is one of:
* - `ChangeDetectionStrategy#OnPush` sets the strategy to `CheckOnce` (on demand).
* - `ChangeDetectionStrategy#Default` sets the strategy to `CheckAlways`.
*/
changeDetection?: ChangeDetectionStrategy;
/**
* Defines the set of injectable objects that are visible to its view DOM children.
* See [example](#injecting-a-class-with-a-view-provider).
*
*/
viewProviders?: Provider[];
/**
* The module ID of the module that contains the component.
* The component must be able to resolve relative URLs for templates and styles.
* SystemJS exposes the `__moduleName` variable within each module.
* In CommonJS, this can be set to `module.id`.
*
* @deprecated This option does not have any effect. Will be removed in Angular v17.
*/
moduleId?: string;
/**
* The relative path or absolute URL of a template file for an Angular component.
* If provided, do not supply an inline template using `template`.
*
*/
templateUrl?: string;
/**
* An inline template for an Angular component. If provided,
* do not supply a template file using `templateUrl`.
*
*/
template?: string;
/**
* One relative paths or an absolute URL for files containing CSS stylesheet to use
* in this component.
*/
styleUrl?: string;
/**
* Relative paths or absolute URLs for files containing CSS stylesheets to use in this component.
*/
styleUrls?: string[];
/**
* One or more inline CSS stylesheets to use
* in this component.
*/
styles?: string | string[];
/**
* One or more animation `trigger()` calls, containing
* [`state()`](api/animations/state) and `transition()` definitions.
* See the [Animations guide](guide/animations) and animations API documentation.
*
*/
animations?: any[];
/**
* An encapsulation policy for the component's styling.
* Possible values:
* - `ViewEncapsulation.Emulated`: Apply modified component styles in order to emulate
* a native Shadow DOM CSS encapsulation behavior.
* - `ViewEncapsulation.None`: Apply component styles globally without any sort of encapsulation.
* - `ViewEncapsulation.ShadowDom`: Use the browser's native Shadow DOM API to encapsulate styles.
*
* If not supplied, the value is taken from the `CompilerOptions`
* which defaults to `ViewEncapsulation.Emulated`.
*
* If the policy is `ViewEncapsulation.Emulated` and the component has no
* {@link Component#styles styles} nor {@link Component#styleUrls styleUrls},
* the policy is automatically switched to `ViewEncapsulation.None`.
*/
encapsulation?: ViewEncapsulation;
/**
* Overrides the default interpolation start and end delimiters (`{{` and `}}`).
*
* @deprecated use Angular's default interpolation delimiters instead.
*/
interpolation?: [string, string];
/**
* True to preserve or false to remove potentially superfluous whitespace characters
* from the compiled template. Whitespace characters are those matching the `\s`
* character class in JavaScript regular expressions. Default is false, unless
* overridden in compiler options.
*/
preserveWhitespaces?: boolean;
/**
* Angular components marked as `standalone` do not need to be declared in an NgModule. Such
* components directly manage their own template dependencies (components, directives, and pipes
* used in a template) via the imports property.
*
* More information about standalone components, directives, and pipes can be found in [this
* guide](guide/components/importing).
*/
standalone?: boolean;
/**
* The imports property specifies the standalone component's template dependencies — those
* directives, components, and pipes that can be used within its template. Standalone components
* can import other standalone components, directives, and pipes as well as existing NgModules.
*
* This property is only available for standalone components - specifying it for components
* declared in an NgModule generates a compilation error.
*
* More information about standalone components, directives, and pipes can be found in [this
* guide](guide/components/importing).
*/
imports?: (Type<any> | ReadonlyArray<any>)[];
/**
* The `deferredImports` property specifies a standalone component's template dependencies,
* which should be defer-loaded as a part of the `@defer` block. Angular *always* generates
* dynamic imports for such symbols and removes the regular/eager import. Make sure that imports
* which bring symbols used in the `deferredImports` don't contain other symbols.
*
* Note: this is an internal-only field, use regular `@Component.imports` field instead.
* @internal
*/
deferredImports?: (Type<any> | ReadonlyArray<any>)[];
/**
* The set of schemas that declare elements to be allowed in a standalone component. Elements and
* properties that are neither Angular components nor directives must be declared in a schema.
*
* This property is only available for standalone components - specifying it for components
* declared in an NgModule generates a compilation error.
*
* More information about standalone components, directives, and pipes can be found in [this
* guide](guide/components/importing).
*/
schemas?: SchemaMetadata[];
}
/**
* Component decorator and metadata.
*
* @Annotation
* @publicApi
*/
export const Component: ComponentDecorator = makeDecorator(
'Component',
(c: Component = {}) => ({changeDetection: ChangeDetectionStrategy.Default, ...c}),
Directive,
undefined,
(type: Type<any>, meta: Component) => compileComponent(type, meta),
);
/**
* Type of the Pipe decorator / constructor function.
*
* @publicApi
*/
export interface PipeDecorator {
/**
*
* Decorator that marks a class as pipe and supplies configuration metadata.
*
* A pipe class must implement the `PipeTransform` interface.
* For example, if the name is "myPipe", use a template binding expression
* such as the following:
*
* ```
* {{ exp | myPipe }}
* ```
*
* The result of the expression is passed to the pipe's `transform()` method.
*
* A pipe must belong to an NgModule in order for it to be available
* to a template. To make it a member of an NgModule,
* list it in the `declarations` field of the `NgModule` metadata.
*
* @see [Style Guide: Pipe Names](style-guide#02-09)
*
*/
(obj: Pipe): TypeDecorator;
/**
* See the `Pipe` decorator.
*/
new (obj: Pipe): Pipe;
}
/**
* Type of the Pipe metadata.
*
* @publicApi
*/
export interface Pipe {
/**
* The pipe name to use in template bindings.
* Typically uses lowerCamelCase
* because the name cannot contain hyphens.
*/
name: string;
/**
* When true, the pipe is pure, meaning that the
* `transform()` method is invoked only when its input arguments
* change. Pipes are pure by default.
*
* If the pipe has internal state (that is, the result
* depends on state other than its arguments), set `pure` to false.
* In this case, the pipe is invoked on each change-detection cycle,
* even if the arguments have not changed.
*/
pure?: boolean;
/**
* Angular pipes marked as `standalone` do not need to be declared in an NgModule. Such
* pipes don't depend on any "intermediate context" of an NgModule (ex. configured providers).
*
* More information about standalone components, directives, and pipes can be found in [this
* guide](guide/components/importing).
*/
standalone?: boolean;
}
/**
* @Annotation
* @publicApi
*/
export const Pipe: PipeDecorator = makeDecorator(
'Pipe',
(p: Pipe) => ({pure: true, ...p}),
undefined,
undefined,
(type: Type<any>, meta: Pipe) => compilePipe(type, meta),
);
/**
* @publicApi
*/
e
| |
011629
|
Supports delivery of Angular apps on a server, for use with server-side rendering.
For more information, see [Server-side Rendering: An intro to Angular SSR](guide/ssr).
| |
011647
|
cribe('Router', () => {
it('should wait for lazy routes before serializing', async () => {
const ngZone = TestBed.inject(NgZone);
@Component({
standalone: true,
selector: 'lazy',
template: `LazyCmp content`,
})
class LazyCmp {}
const routes: Routes = [
{
path: '',
loadComponent: () => {
return ngZone.runOutsideAngular(() => {
return new Promise((resolve) => {
setTimeout(() => resolve(LazyCmp), 100);
});
});
},
},
];
@Component({
standalone: false,
selector: 'app',
template: `
Works!
<router-outlet />
`,
})
class MyServerApp {}
@NgModule({
declarations: [MyServerApp],
exports: [MyServerApp],
imports: [BrowserModule, ServerModule, RouterOutlet],
providers: [provideRouter(routes)],
bootstrap: [MyServerApp],
})
class MyServerAppModule {}
const options = {document: '<html><head></head><body><app></app></body></html>'};
const output = await renderModule(MyServerAppModule, options);
// Expect serialization to happen once a lazy-loaded route completes loading
// and a lazy component is rendered.
expect(output).toContain('<lazy>LazyCmp content</lazy>');
});
});
describe('HttpClient', () => {
it('can inject HttpClient', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
const ref = await platform.bootstrapModule(HttpClientExampleModule);
expect(ref.injector.get(HttpClient) instanceof HttpClient).toBeTruthy();
});
it('can make HttpClient requests', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
await platform.bootstrapModule(HttpClientExampleModule).then((ref) => {
const mock = ref.injector.get(HttpTestingController) as HttpTestingController;
const http = ref.injector.get(HttpClient);
ref.injector.get<NgZone>(NgZone).run(() => {
http.get<string>('http://localhost/testing').subscribe((body: string) => {
NgZone.assertInAngularZone();
expect(body).toEqual('success!');
});
mock.expectOne('http://localhost/testing').flush('success!');
});
});
});
it('can use HttpInterceptor that injects HttpClient', async () => {
const platform = platformServer([
{provide: INITIAL_CONFIG, useValue: {document: '<app></app>'}},
]);
await platform.bootstrapModule(HttpInterceptorExampleModule).then((ref) => {
const mock = ref.injector.get(HttpTestingController) as HttpTestingController;
const http = ref.injector.get(HttpClient);
ref.injector.get(NgZone).run(() => {
http.get<string>('http://localhost/testing').subscribe((body: string) => {
NgZone.assertInAngularZone();
expect(body).toEqual('success!');
});
mock.expectOne('http://localhost/testing').flush('success!');
});
});
});
describe(`given 'url' is provided in 'INITIAL_CONFIG'`, () => {
let mock: HttpTestingController;
let ref: NgModuleRef<HttpInterceptorExampleModule>;
let http: HttpClient;
beforeEach(async () => {
const platform = platformServer([
{
provide: INITIAL_CONFIG,
useValue: {document: '<app></app>', url: 'http://localhost:4000/foo'},
},
]);
ref = await platform.bootstrapModule(HttpInterceptorExampleModule);
mock = ref.injector.get(HttpTestingController);
http = ref.injector.get(HttpClient);
});
it('should resolve relative request URLs to absolute', async () => {
ref.injector.get(NgZone).run(() => {
http.get('/testing').subscribe((body) => {
NgZone.assertInAngularZone();
expect(body).toEqual('success!');
});
mock.expectOne('http://localhost:4000/testing').flush('success!');
});
});
it(`should not replace the baseUrl of a request when it's absolute`, async () => {
ref.injector.get(NgZone).run(() => {
http.get('http://localhost/testing').subscribe((body) => {
NgZone.assertInAngularZone();
expect(body).toEqual('success!');
});
mock.expectOne('http://localhost/testing').flush('success!');
});
});
});
});
});
})();
| |
011655
|
escribe('ViewContainerRef', () => {
it('should work with ViewContainerRef.createComponent', async () => {
@Component({
standalone: true,
selector: 'dynamic',
template: `
<span>This is a content of a dynamic component.</span>
`,
})
class DynamicComponent {}
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<div #target></div>
<main>Hi! This is the main content.</main>
`,
})
class SimpleComponent {
@ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
ngAfterViewInit() {
const compRef = this.vcr.createComponent(DynamicComponent);
compRef.changeDetectorRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, DynamicComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should work with ViewContainerRef.createEmbeddedView', async () => {
@Component({
standalone: true,
selector: 'app',
imports: [NgIf, NgFor],
template: `
<ng-template #tmpl>
<h1>This is a content of an ng-template.</h1>
</ng-template>
<ng-container #target></ng-container>
`,
})
class SimpleComponent {
@ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
@ViewChild('tmpl', {read: TemplateRef}) tmpl!: TemplateRef<unknown>;
ngAfterViewInit() {
const viewRef = this.vcr.createEmbeddedView(this.tmpl);
viewRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
const clientRootNode = compRef.location.nativeElement;
verifyAllNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should hydrate dynamically created components using root component as an anchor', async () => {
@Component({
standalone: true,
imports: [CommonModule],
selector: 'dynamic',
template: `
<span>This is a content of a dynamic component.</span>
`,
})
class DynamicComponent {}
@Component({
standalone: true,
selector: 'app',
template: `
<main>Hi! This is the main content.</main>
`,
})
class SimpleComponent {
vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const compRef = this.vcr.createComponent(DynamicComponent);
compRef.changeDetectorRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent, DynamicComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
// Compare output starting from the parent node above the component node,
// because component host node also acted as a ViewContainerRef anchor,
// thus there are elements after this node (as next siblings).
const clientRootNode = compRef.location.nativeElement.parentNode;
await whenStable(appRef);
verifyAllChildNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
it('should hydrate embedded views when using root component as an anchor', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<ng-template #tmpl>
<h1>Content of embedded view</h1>
</ng-template>
<main>Hi! This is the main content.</main>
`,
})
class SimpleComponent {
@ViewChild('tmpl', {read: TemplateRef}) tmpl!: TemplateRef<unknown>;
vcr = inject(ViewContainerRef);
ngAfterViewInit() {
const viewRef = this.vcr.createEmbeddedView(this.tmpl);
viewRef.detectChanges();
}
}
const html = await ssr(SimpleComponent);
const ssrContents = getAppContents(html);
expect(ssrContents).toContain('<app ngh');
resetTViewsFor(SimpleComponent);
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent);
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
// Compare output starting from the parent node above the component node,
// because component host node also acted as a ViewContainerRef anchor,
// thus there are elements after this node (as next siblings).
const clientRootNode = compRef.location.nativeElement.parentNode;
await whenStable(appRef);
verifyAllChildNodesClaimedForHydration(clientRootNode);
verifyClientAndSSRContentsMatch(ssrContents, clientRootNode);
});
| |
011692
|
t('should SSR and hydrate nested `@defer` blocks', async () => {
@Component({
standalone: true,
selector: 'app',
template: `
<main (click)="fnA()">
@defer (on viewport; hydrate on interaction) {
<div (click)="fnA()">
Main defer block rendered!
@if (visible) {
Defer events work!
}
<div id="outer-trigger" (mouseover)="showMessage()"></div>
@defer (on viewport; hydrate on interaction) {
<p (click)="showMessage()">Nested defer block</p>
} @placeholder {
<span>Inner block placeholder</span>
}
</div>
} @placeholder {
<span>Outer block placeholder</span>
}
</main>
`,
})
class SimpleComponent {
items = [1, 2, 3];
visible = false;
fnA() {}
showMessage() {
this.visible = true;
}
}
const appId = 'custom-app-id';
const providers = [{provide: APP_ID, useValue: appId}];
const hydrationFeatures = [withIncrementalHydration()];
const html = await ssr(SimpleComponent, {envProviders: providers, hydrationFeatures});
const ssrContents = getAppContents(html);
// Assert that we have `jsaction` annotations and
// defer blocks are triggered and rendered.
// <main> uses "eager" `custom-app-id` namespace.
expect(ssrContents).toContain('<main jsaction="click:;');
// <div>s inside a defer block have `d0` as a namespace.
expect(ssrContents).toContain('<div jsaction="click:;keydown:;" ngb="d0"');
expect(ssrContents).toContain('<div id="outer-trigger" jsaction="mouseover:;" ngb="d0"');
// <p> is inside a nested defer block -> different namespace.
expect(ssrContents).toContain('<p jsaction="click:;keydown:;" ngb="d1');
// There is an extra annotation in the TransferState data.
expect(ssrContents).toContain(
'"__nghDeferData__":{"d0":{"p":null,"r":1,"s":2,"t":[]},"d1":{"p":"d0","r":1,"s":2,"t":[]}}',
);
// Outer defer block is rendered.
expect(ssrContents).toContain('Main defer block rendered');
// Inner defer block is rendered as well.
expect(ssrContents).toContain('Nested defer block');
// Internal cleanup before we do server->client transition in this test.
resetTViewsFor(SimpleComponent);
////////////////////////////////
const doc = getDocument();
const appRef = await prepareEnvironmentAndHydrate(doc, html, SimpleComponent, {
envProviders: [...providers, {provide: PLATFORM_ID, useValue: 'browser'}],
hydrationFeatures,
});
const compRef = getComponentRef<SimpleComponent>(appRef);
appRef.tick();
await whenStable(appRef);
const appHostNode = compRef.location.nativeElement;
// At this point an eager part of an app is hydrated,
// but defer blocks are still in dehydrated state.
// <main> no longer has `jsaction` attribute.
expect(appHostNode.outerHTML).toContain('<main>');
// Elements from @defer blocks still have `jsaction` annotations,
// since they were not triggered yet.
expect(appHostNode.outerHTML).toContain('<div jsaction="click:;keydown:;" ngb="d0"');
expect(appHostNode.outerHTML).toContain(
'<div id="outer-trigger" jsaction="mouseover:;" ngb="d0',
);
expect(appHostNode.outerHTML).toContain('<p jsaction="click:;keydown:;" ngb="d1"');
// Emit an event inside of a defer block, which should result
// in triggering the defer block (start loading deps, etc) and
// subsequent hydration.
const inner = doc.body.querySelector('p')!;
const clickEvent = new CustomEvent('click', {bubbles: true});
inner.dispatchEvent(clickEvent);
await timeout(1000); // wait for defer blocks to resolve
appRef.tick();
// An event was replayed after hydration, which resulted in
// an `@if` block becoming active and its inner content got
// rendered/
expect(appHostNode.outerHTML).toContain('Defer events work');
// Since inner `@defer` block was triggered, all parent blocks
// were hydrated as well, so all `jsaction` attributes are removed.
expect(appHostNode.outerHTML).not.toContain('jsaction="');
}, 100_000);
| |
011731
|
tes diagnostic when the library does not export the host directive', () => {
const files = {
// export post module and component but not the host directive. This is not valid. We won't
// be able to import the host directive for template type checking.
'dist/post/index.d.ts': `
export { PostComponent, PostModule } from './lib/post.component';
`,
'dist/post/lib/post.component.d.ts': `
import * as i0 from "@angular/core";
export declare class HostBindDirective {
static ɵdir: i0.ɵɵDirectiveDeclaration<HostBindDirective, never, never, {}, {}, never, never, true, never>;
}
export declare class PostComponent {
static ɵcmp: i0.ɵɵComponentDeclaration<PostComponent, "lib-post", never, {}, {}, never, never, false, [{ directive: typeof HostBindDirective; inputs: {}; outputs: {}; }]>;
}
export declare class PostModule {
static ɵmod: i0.ɵɵNgModuleDeclaration<PostModule, [typeof PostComponent], never, [typeof PostComponent]>;
static ɵinj: i0.ɵɵInjectorDeclaration<PostModule>;
}
`,
'test.ts': `
import {Component} from '@angular/core';
import {PostModule} from 'post';
@Component({
templateUrl: './test.ng.html',
imports: [PostModule],
standalone: true,
})
export class Main { }
`,
'test.ng.html': '<lib-post />',
};
const tsCompilerOptions = {paths: {'post': ['dist/post']}};
const project = env.addProject('test', files, {}, tsCompilerOptions);
const diags = project.getDiagnosticsForFile('test.ng.html');
expect(diags.length).toBe(1);
expect(ts.flattenDiagnosticMessageText(diags[0].messageText, '')).toContain(
'HostBindDirective',
);
});
});
function getTextOfDiagnostic(diag: ts.Diagnostic): string {
expect(diag.file).not.toBeUndefined();
expect(diag.start).not.toBeUndefined();
expect(diag.length).not.toBeUndefined();
return diag.file!.text.substring(diag.start!, diag.start! + diag.length!);
}
| |
011736
|
friends', () => {
it('defer', () => {
expectQuickInfo({
templateOverride: `@de¦fer { } @placeholder { <input /> }`,
expectedSpanText: '@defer ',
expectedDisplayString: '(block) @defer',
});
});
it('defer with condition', () => {
expectQuickInfo({
templateOverride: `@de¦fer (on immediate) { } @placeholder { <input /> }`,
expectedSpanText: '@defer ',
expectedDisplayString: '(block) @defer',
});
});
it('placeholder', () => {
expectQuickInfo({
templateOverride: `@defer { } @pla¦ceholder { <input /> }`,
expectedSpanText: '@placeholder ',
expectedDisplayString: '(block) @placeholder',
});
});
it('loading', () => {
expectQuickInfo({
templateOverride: `@defer { } @loadin¦g { <input /> }`,
expectedSpanText: '@loading ',
expectedDisplayString: '(block) @loading',
});
});
it('error', () => {
expectQuickInfo({
templateOverride: `@defer { } @erro¦r { <input /> }`,
expectedSpanText: '@error ',
expectedDisplayString: '(block) @error',
});
});
describe('triggers', () => {
it('viewport', () => {
expectQuickInfo({
templateOverride: `@defer (on vie¦wport(x)) { } <div #x></div>`,
expectedSpanText: 'viewport',
expectedDisplayString: '(trigger) viewport',
});
});
it('immediate', () => {
expectQuickInfo({
templateOverride: `@defer (on imme¦diate) {}`,
expectedSpanText: 'immediate',
expectedDisplayString: '(trigger) immediate',
});
});
it('idle', () => {
expectQuickInfo({
templateOverride: `@defer (on i¦dle) { } `,
expectedSpanText: 'idle',
expectedDisplayString: '(trigger) idle',
});
});
it('hover', () => {
expectQuickInfo({
templateOverride: `@defer (on hov¦er(x)) { } <div #x></div> `,
expectedSpanText: 'hover',
expectedDisplayString: '(trigger) hover',
});
});
it('timer', () => {
expectQuickInfo({
templateOverride: `@defer (on tim¦er(100)) { } `,
expectedSpanText: 'timer',
expectedDisplayString: '(trigger) timer',
});
});
it('interaction', () => {
expectQuickInfo({
templateOverride: `@defer (on interactio¦n(x)) { } <div #x></div>`,
expectedSpanText: 'interaction',
expectedDisplayString: '(trigger) interaction',
});
});
it('when', () => {
expectQuickInfo({
templateOverride: `@defer (whe¦n title) { } <div #x></div>`,
expectedSpanText: 'when',
expectedDisplayString: '(keyword) when',
});
});
it('prefetch (when)', () => {
expectQuickInfo({
templateOverride: `@defer (prefet¦ch when title) { }`,
expectedSpanText: 'prefetch',
expectedDisplayString: '(keyword) prefetch',
});
});
it('hydrate (when)', () => {
expectQuickInfo({
templateOverride: `@defer (hydra¦te when title) { }`,
expectedSpanText: 'hydrate',
expectedDisplayString: '(keyword) hydrate',
});
});
it('on', () => {
expectQuickInfo({
templateOverride: `@defer (o¦n immediate) { } `,
expectedSpanText: 'on',
expectedDisplayString: '(keyword) on',
});
});
it('prefetch (on)', () => {
expectQuickInfo({
templateOverride: `@defer (prefet¦ch on immediate) { }`,
expectedSpanText: 'prefetch',
expectedDisplayString: '(keyword) prefetch',
});
});
it('hydrate (on)', () => {
expectQuickInfo({
templateOverride: `@defer (hydra¦te on immediate) { }`,
expectedSpanText: 'hydrate',
expectedDisplayString: '(keyword) hydrate',
});
});
});
});
it('empty', () => {
expectQuickInfo({
templateOverride: `@for (name of constNames; track $index) {} @em¦pty {}`,
expectedSpanText: '@empty ',
expectedDisplayString: '(block) @empty',
});
});
it('track keyword', () => {
expectQuickInfo({
templateOverride: `@for (name of constNames; tr¦ack $index) {}`,
expectedSpanText: 'track',
expectedDisplayString: '(keyword) track',
});
});
it('implicit variable assignment', () => {
expectQuickInfo({
templateOverride: `@for (name of constNames; track $index; let od¦d = $odd) {}`,
expectedSpanText: 'odd',
expectedDisplayString: '(variable) odd: boolean',
});
});
it('implicit variable assignment in comma separated list', () => {
expectQuickInfo({
templateOverride: `@for (name of constNames; track index; let odd = $odd, ind¦ex = $index) {}`,
expectedSpanText: 'index',
expectedDisplayString: '(variable) index: number',
});
});
it('if block alias variable', () => {
expectQuickInfo({
templateOverride: `@if (constNames; as al¦iasName) {}`,
expectedSpanText: 'aliasName',
expectedDisplayString: '(variable) aliasName: [{ readonly name: "name"; }]',
});
});
it('if block alias variable', () => {
expectQuickInfo({
templateOverride: `@if (someObject.some¦Signal(); as aliasName) {}`,
expectedSpanText: 'someSignal',
expectedDisplayString: '(property) someSignal: WritableSignal\n() => number',
});
});
});
describe('let declarations', () => {
it('should get quick info for a let declaration', () => {
expectQuickInfo({
templateOverride: `@let na¦me = 'Frodo'; {{name}}`,
expectedSpanText: `@let name = 'Frodo'`,
expectedDisplayString: `(let) name: "Frodo"`,
});
});
});
it('should work for object literal with shorthand property declarations', () => {
initMockFileSystem('Native');
env = LanguageServiceTestEnv.setup();
project = env.addProject(
'test',
{
'app.ts': `
import {Component, NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
@Component({
selector: 'some-cmp',
templateUrl: './app.html',
standalone: false,
})
export class SomeCmp {
val1 = 'one';
val2 = 2;
doSomething(obj: {val1: string, val2: number}) {}
}
@NgModule({
declarations: [SomeCmp],
imports: [CommonModule],
})
export class AppModule{
}
`,
'app.html': `{{doSomething({val1, val2})}}`,
},
{strictTemplates: true},
);
env.expectNoSourceDiagnostics();
project.expectNoSourceDiagnostics();
const template = project.openFile('app.html');
template.moveCursorToText('val¦1');
const quickInfo = template.getQuickInfoAtPosition();
expect(toText(quickInfo!.displayParts)).toEqual('(property) SomeCmp.val1: string');
template.moveCursorToText('val¦2');
const quickInfo2 = template.getQuickInfoAtPosition();
expect(toText(quickInfo2!.displayParts)).toEqual('(property) SomeCmp.val2: number');
});
});
describe('generics', () => {
beforeEach(() => {
initMockFileSys
| |
011904
|
### Disclaimer
The localize tools are consumed via the Angular CLI. The programmatic APIs are not considered officially
supported though and are not subject to the breaking change guarantees of SemVer.
| |
012044
|
# @angular/localize schematic for `ng add`
This schematic will be executed when an Angular CLI user runs `ng add @angular/localize`.
It will search their `angular.json` file, and add `types: ["@angular/localize"]` in the TypeScript
configuration files of the project.
If the user specifies that they want to use `$localize` at runtime then the dependency will be
added to the `dependencies` section of `package.json` rather than in the `devDependencies` which
is the default.
| |
012048
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {EmptyTree, Tree} from '@angular-devkit/schematics';
import {SchematicTestRunner} from '@angular-devkit/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import ts from 'typescript';
interface TsConfig {
compilerOptions?: ts.CompilerOptions;
}
describe('ng-add schematic', () => {
const localizeTripleSlashType = `/// <reference types="@angular/localize" />`;
const defaultOptions = {project: 'demo'};
const schematicRunner = new SchematicTestRunner(
'@angular/localize',
runfiles.resolvePackageRelative('../collection.json'),
);
let host: Tree;
beforeEach(() => {
host = new EmptyTree();
host.create(
'package.json',
JSON.stringify({
'devDependencies': {
// The default (according to `ng-add` in its package.json) is for `@angular/localize` to be
// saved to `devDependencies`.
'@angular/localize': '~0.0.0-PLACEHOLDER',
},
}),
);
host.create(
'main.ts',
`
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
`,
);
host.create(
'angular.json',
JSON.stringify({
version: 1,
projects: {
'demo': {
root: '',
architect: {
application: {
builder: '@angular-devkit/build-angular:application',
options: {
browser: './main.ts',
tsConfig: './tsconfig.application.json',
polyfills: ['zone.js'],
},
},
build: {
builder: '@angular-devkit/build-angular:browser',
options: {
main: './main.ts',
tsConfig: './tsconfig.app.json',
},
},
test: {
builder: '@angular-devkit/build-angular:karma',
options: {
tsConfig: './tsconfig.spec.json',
polyfills: 'zone.js',
},
},
server: {
builder: '@angular-devkit/build-angular:server',
options: {
tsConfig: './tsconfig.server.json',
},
},
unknown: {
builder: '@custom-builder/build-angular:unknown',
options: {
tsConfig: './tsconfig.unknown.json',
},
},
},
},
},
}),
);
});
it(`should add '@angular/localize' type reference in 'main.ts'`, async () => {
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
expect(host.readText('main.ts')).toContain(localizeTripleSlashType);
});
it(`should not add '@angular/localize' type reference in 'main.ts' if already present`, async () => {
const mainContentInput = `
${localizeTripleSlashType}
import { enableProdMode } from '@angular/core';
`;
host.overwrite('main.ts', mainContentInput);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
expect(host.readText('main.ts')).toBe(mainContentInput);
});
it(`should not add '@angular/localize' in 'types' tsconfigs referenced in non official builders`, async () => {
const tsConfig = JSON.stringify({
compilerOptions: {
types: ['node'],
},
});
host.create('tsconfig.unknown.json', tsConfig);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const {compilerOptions} = host.readJson('tsconfig.unknown.json') as TsConfig;
const types = compilerOptions?.types;
expect(types).not.toContain('@angular/localize');
expect(types).toHaveSize(1);
});
it(`should add '@angular/localize' in 'types' tsconfigs referenced in browser builder`, async () => {
const tsConfig = JSON.stringify({
compilerOptions: {
types: ['node'],
},
});
host.create('tsconfig.app.json', tsConfig);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const {compilerOptions} = host.readJson('tsconfig.app.json') as TsConfig;
const types = compilerOptions?.types;
expect(types).toContain('@angular/localize');
expect(types).toHaveSize(2);
});
it(`should add '@angular/localize' in 'types' tsconfigs referenced in application builder`, async () => {
const tsConfig = JSON.stringify({
compilerOptions: {
types: ['node'],
},
});
host.create('tsconfig.application.json', tsConfig);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const {compilerOptions} = host.readJson('tsconfig.application.json') as TsConfig;
const types = compilerOptions?.types;
expect(types).toContain('@angular/localize');
expect(types).toHaveSize(2);
});
it(`should add '@angular/localize/init' in 'polyfills' in application builder`, async () => {
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const workspace = host.readJson('angular.json') as any;
const polyfills = workspace.projects['demo'].architect.application.options.polyfills;
expect(polyfills).toEqual(['zone.js', '@angular/localize/init']);
});
it(`should add '@angular/localize/init' in 'polyfills' in karma builder`, async () => {
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const workspace = host.readJson('angular.json') as any;
const polyfills = workspace.projects['demo'].architect.test.options.polyfills;
expect(polyfills).toEqual(['zone.js', '@angular/localize/init']);
});
it(`should add '@angular/localize/init' in 'polyfills' in browser builder`, async () => {
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const workspace = host.readJson('angular.json') as any;
const polyfills = workspace.projects['demo'].architect.build.options.polyfills;
expect(polyfills).toEqual(['@angular/localize/init']);
});
it(`should add '@angular/localize' in 'types' tsconfigs referenced in karma builder`, async () => {
const tsConfig = JSON.stringify({
compilerOptions: {
types: ['node'],
},
});
host.create('tsconfig.spec.json', tsConfig);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const {compilerOptions} = host.readJson('tsconfig.spec.json') as TsConfig;
const types = compilerOptions?.types;
expect(types).toContain('@angular/localize');
expect(types).toHaveSize(2);
});
it(`should add '@angular/localize' in 'types' tsconfigs referenced in server builder`, async () => {
const tsConfig = JSON.stringify({
compilerOptions: {},
});
host.create('tsconfig.server.json', tsConfig);
host = await schematicRunner.runSchematic('ng-add', defaultOptions, host);
const {compilerOptions} = host.readJson('tsconfig.server.json') as TsConfig;
const types = compilerOptions?.types;
expect(types).toContain('@angular/localize');
expect(types).toHaveSize(1);
});
it('should add package to `dependencies` if `useAtRuntime` is `true`', async () => {
host = await schematicRunner.runSchematic(
'ng-add',
{...defaultOptions, useAtRuntime: true},
host,
);
const {devDependencies, dependencies} = host.readJson('/package.json') as {
devDependencies: {[key: string]: string};
dependencies: {[key: string]: string};
};
expect(dependencies?.['@angular/localize']).toBe('~0.0.0-PLACEHOLDER');
expect(devDependencies?.['@angular/localize']).toBeUndefined();
});
});
| |
012067
|
Implements fundamental Angular framework functionality, including directives and pipes, location services used in routing, HTTP services, localization support, and so on.
The `CommonModule` exports are re-exported by `BrowserModule`, which is included automatically in the root `AppModule` when you create a new app with the CLI `new` command.
| |
012211
|
escribe('ngIf directive', () => {
let fixture: ComponentFixture<any>;
function getComponent(): TestComponent {
return fixture.componentInstance;
}
afterEach(() => {
fixture = null!;
});
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
imports: [CommonModule],
});
});
it('should work in a template attribute', waitForAsync(() => {
const template = '<span *ngIf="booleanCondition">hello</span>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('hello');
}));
it('should work on a template element', waitForAsync(() => {
const template = '<ng-template [ngIf]="booleanCondition">hello2</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('hello2');
}));
it('should toggle node when condition changes', waitForAsync(() => {
const template = '<span *ngIf="booleanCondition">hello</span>';
fixture = createTestComponent(template);
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
getComponent().booleanCondition = true;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('hello');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
}));
it('should handle nested if correctly', waitForAsync(() => {
const template =
'<div *ngIf="booleanCondition"><span *ngIf="nestedBooleanCondition">hello</span></div>';
fixture = createTestComponent(template);
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
getComponent().booleanCondition = true;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('hello');
getComponent().nestedBooleanCondition = false;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
getComponent().nestedBooleanCondition = true;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('hello');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
}));
it('should update several nodes with if', waitForAsync(() => {
const template =
'<span *ngIf="numberCondition + 1 >= 2">helloNumber</span>' +
'<span *ngIf="stringCondition == \'foo\'">helloString</span>' +
'<span *ngIf="functionCondition(stringCondition, numberCondition)">helloFunction</span>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(3);
expect(fixture.nativeElement.textContent).toEqual('helloNumberhelloStringhelloFunction');
getComponent().numberCondition = 0;
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('helloString');
getComponent().numberCondition = 1;
getComponent().stringCondition = 'bar';
fixture.detectChanges();
expect(fixture.debugElement.queryAll(By.css('span')).length).toEqual(1);
expect(fixture.nativeElement).toHaveText('helloNumber');
}));
it('should not add the element twice if the condition goes from truthy to truthy', waitForAsync(() => {
const template = '<span *ngIf="numberCondition">hello</span>';
fixture = createTestComponent(template);
fixture.detectChanges();
let els = fixture.debugElement.queryAll(By.css('span'));
expect(els.length).toEqual(1);
els[0].nativeElement.classList.add('marker');
expect(fixture.nativeElement).toHaveText('hello');
getComponent().numberCondition = 2;
fixture.detectChanges();
els = fixture.debugElement.queryAll(By.css('span'));
expect(els.length).toEqual(1);
expect(els[0].nativeElement.classList.contains('marker')).toBe(true);
expect(fixture.nativeElement).toHaveText('hello');
}));
describe('then/else templates', () => {
it('should support else', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition; else elseBlock">TRUE</span>' +
'<ng-template #elseBlock>FALSE</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('TRUE');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('FALSE');
}));
it('should support then and else', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition; then thenBlock; else elseBlock">IGNORE</span>' +
'<ng-template #thenBlock>THEN</ng-template>' +
'<ng-template #elseBlock>ELSE</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('THEN');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('ELSE');
}));
it('should support removing the then/else templates', () => {
const template = `<span *ngIf="booleanCondition;
then nestedBooleanCondition ? tplRef : null;
else nestedBooleanCondition ? tplRef : null"></span>
<ng-template #tplRef>Template</ng-template>`;
fixture = createTestComponent(template);
const comp = fixture.componentInstance;
// then template
comp.booleanCondition = true;
comp.nestedBooleanCondition = true;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Template');
comp.nestedBooleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
// else template
comp.booleanCondition = true;
comp.nestedBooleanCondition = true;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('Template');
comp.nestedBooleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('');
});
it('should support dynamic else', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition; else nestedBooleanCondition ? b1 : b2">TRUE</span>' +
'<ng-template #b1>FALSE1</ng-template>' +
'<ng-template #b2>FALSE2</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('TRUE');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('FALSE1');
getComponent().nestedBooleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('FALSE2');
}));
it('should support binding to variable using let', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition; else elseBlock; let v">{{v}}</span>' +
'<ng-template #elseBlock let-v>{{v}}</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('true');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('false');
}));
it('should support binding to variable using as', waitForAsync(() => {
const template =
'<span *ngIf="booleanCondition as v; else elseBlock">{{v}}</span>' +
'<ng-template #elseBlock let-v>{{v}}</ng-template>';
fixture = createTestComponent(template);
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('true');
getComponent().booleanCondition = false;
fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('false');
}));
it('should be available as a standalone directive', () => {
@Component({
selector: 'test-component',
imports: [NgIf],
template: `
<div *ngIf="true">Hello</div>
<div *ngIf="false">World</div>
`,
standalone: true,
})
class TestComponent {}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('Hello');
expect(fixture.nativeElement.textContent).not.toBe('World');
});
});
| |
012218
|
it('should display last item correctly', waitForAsync(() => {
const template =
'<span *ngFor="let item of items; let isLast=last">{{isLast.toString()}}</span>';
fixture = createTestComponent(template);
getComponent().items = [0, 1, 2];
detectChangesAndExpectText('falsefalsetrue');
getComponent().items = [2, 1];
detectChangesAndExpectText('falsetrue');
}));
it('should display even items correctly', waitForAsync(() => {
const template =
'<span *ngFor="let item of items; let isEven=even">{{isEven.toString()}}</span>';
fixture = createTestComponent(template);
getComponent().items = [0, 1, 2];
detectChangesAndExpectText('truefalsetrue');
getComponent().items = [2, 1];
detectChangesAndExpectText('truefalse');
}));
it('should display odd items correctly', waitForAsync(() => {
const template = '<span *ngFor="let item of items; let isOdd=odd">{{isOdd.toString()}}</span>';
fixture = createTestComponent(template);
getComponent().items = [0, 1, 2, 3];
detectChangesAndExpectText('falsetruefalsetrue');
getComponent().items = [2, 1];
detectChangesAndExpectText('falsetrue');
}));
it('should allow to use a custom template', waitForAsync(() => {
const template =
'<ng-container *ngFor="let item of items; template: tpl"></ng-container>' +
'<ng-template let-item let-i="index" #tpl><p>{{i}}: {{item}};</p></ng-template>';
fixture = createTestComponent(template);
getComponent().items = ['a', 'b', 'c'];
fixture.detectChanges();
detectChangesAndExpectText('0: a;1: b;2: c;');
}));
it('should use a default template if a custom one is null', waitForAsync(() => {
const template = `<ul><ng-container *ngFor="let item of items; template: null; let i=index">{{i}}: {{item}};</ng-container></ul>`;
fixture = createTestComponent(template);
getComponent().items = ['a', 'b', 'c'];
fixture.detectChanges();
detectChangesAndExpectText('0: a;1: b;2: c;');
}));
it('should use a custom template when both default and a custom one are present', waitForAsync(() => {
const template =
'<ng-container *ngFor="let item of items; template: tpl">{{i}};</ng-container>' +
'<ng-template let-item let-i="index" #tpl>{{i}}: {{item}};</ng-template>';
fixture = createTestComponent(template);
getComponent().items = ['a', 'b', 'c'];
fixture.detectChanges();
detectChangesAndExpectText('0: a;1: b;2: c;');
}));
describe('track by', () => {
it('should console.warn if trackBy is not a function', waitForAsync(() => {
// TODO(vicb): expect a warning message when we have a proper log service
const template = `<p *ngFor="let item of items; trackBy: value"></p>`;
fixture = createTestComponent(template);
fixture.componentInstance.value = 0;
fixture.detectChanges();
}));
it('should track by identity when trackBy is to `null` or `undefined`', waitForAsync(() => {
// TODO(vicb): expect no warning message when we have a proper log service
const template = `<p *ngFor="let item of items; trackBy: value">{{ item }}</p>`;
fixture = createTestComponent(template);
fixture.componentInstance.items = ['a', 'b', 'c'];
fixture.componentInstance.value = null;
detectChangesAndExpectText('abc');
fixture.componentInstance.value = undefined;
detectChangesAndExpectText('abc');
}));
it('should set the context to the component instance', waitForAsync(() => {
const template = `<p *ngFor="let item of items; trackBy: trackByContext.bind(this)"></p>`;
fixture = createTestComponent(template);
thisArg = null;
fixture.detectChanges();
expect(thisArg).toBe(getComponent());
}));
it('should not replace tracked items', waitForAsync(() => {
const template = `<p *ngFor="let item of items; trackBy: trackById; let i=index">{{items[i]}}</p>`;
fixture = createTestComponent(template);
const buildItemList = () => {
getComponent().items = [{'id': 'a'}];
fixture.detectChanges();
return fixture.debugElement.queryAll(By.css('p'))[0];
};
const firstP = buildItemList();
const finalP = buildItemList();
expect(finalP.nativeElement).toBe(firstP.nativeElement);
}));
it('should update implicit local variable on view', waitForAsync(() => {
const template = `<div *ngFor="let item of items; trackBy: trackById">{{item['color']}}</div>`;
fixture = createTestComponent(template);
getComponent().items = [{'id': 'a', 'color': 'blue'}];
detectChangesAndExpectText('blue');
getComponent().items = [{'id': 'a', 'color': 'red'}];
detectChangesAndExpectText('red');
}));
it('should move items around and keep them updated ', waitForAsync(() => {
const template = `<div *ngFor="let item of items; trackBy: trackById">{{item['color']}}</div>`;
fixture = createTestComponent(template);
getComponent().items = [
{'id': 'a', 'color': 'blue'},
{'id': 'b', 'color': 'yellow'},
];
detectChangesAndExpectText('blueyellow');
getComponent().items = [
{'id': 'b', 'color': 'orange'},
{'id': 'a', 'color': 'red'},
];
detectChangesAndExpectText('orangered');
}));
it('should handle added and removed items properly when tracking by index', waitForAsync(() => {
const template = `<div *ngFor="let item of items; trackBy: trackByIndex">{{item}}</div>`;
fixture = createTestComponent(template);
getComponent().items = ['a', 'b', 'c', 'd'];
fixture.detectChanges();
getComponent().items = ['e', 'f', 'g', 'h'];
fixture.detectChanges();
getComponent().items = ['e', 'f', 'h'];
detectChangesAndExpectText('efh');
}));
});
it('should be available as a standalone directive', () => {
@Component({
selector: 'test-component',
imports: [NgForOf],
template: ` <ng-container *ngFor="let item of items">{{ item }}|</ng-container> `,
standalone: true,
})
class TestComponent {
items = [1, 2, 3];
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('1|2|3|');
});
it('should be available as a standalone directive using an `NgFor` alias', () => {
@Component({
selector: 'test-component',
imports: [NgFor],
template: ` <ng-container *ngFor="let item of items">{{ item }}|</ng-container> `,
standalone: true,
})
class TestComponent {
items = [1, 2, 3];
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('1|2|3|');
});
});
class Foo {
toString() {
return 'foo';
}
}
@Component({
selector: 'test-cmp',
template: '',
standalone: false,
})
class TestComponent {
value: any;
items: any[] = [1, 2];
trackById(index: number, item: any): string {
return item['id'];
}
trackByIndex(index: number, item: any): number {
return index;
}
trackByContext(): void {
thisArg = this;
}
}
const TEMPLATE = '<div><span *ngFor="let item of items">{{item.toString()}};</span></div>';
function createTestComponent(template: string = TEMPLATE): ComponentFixture<TestComponent> {
return TestBed.overrideComponent(TestComponent, {set: {template: template}}).createComponent(
TestComponent,
);
}
| |
012250
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AsyncPipe} from '@angular/common';
import {ChangeDetectorRef, Component, computed, EventEmitter, signal} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {Observable, of, Subscribable, Unsubscribable} from 'rxjs';
describe('AsyncPipe', () => {
let pipe: AsyncPipe;
let ref: ChangeDetectorRef & jasmine.SpyObj<ChangeDetectorRef>;
function getChangeDetectorRefSpy() {
return jasmine.createSpyObj('ChangeDetectorRef', ['markForCheck', 'detectChanges']);
}
beforeEach(() => {
ref = getChangeDetectorRefSpy();
pipe = new AsyncPipe(ref);
});
afterEach(() => {
pipe.ngOnDestroy(); // Close all subscriptions.
});
describe('Observable', () => {
// only expose methods from the Subscribable interface, to ensure that
// the implementation does not rely on other methods:
const wrapSubscribable = <T>(input: Subscribable<T>): Subscribable<T> => ({
subscribe(...args: any): Unsubscribable {
const subscription = input.subscribe.apply(input, args);
return {
unsubscribe() {
subscription.unsubscribe();
},
};
},
});
let emitter: EventEmitter<any>;
let subscribable: Subscribable<any>;
const message = {};
beforeEach(() => {
emitter = new EventEmitter();
subscribable = wrapSubscribable(emitter);
});
describe('transform', () => {
it('should return null when subscribing to an observable', () => {
expect(pipe.transform(subscribable)).toBe(null);
});
it('should return the latest available value', (done) => {
pipe.transform(subscribable);
emitter.emit(message);
setTimeout(() => {
expect(pipe.transform(subscribable)).toEqual(message);
done();
}, 0);
});
it('should return same value when nothing has changed since the last call', (done) => {
pipe.transform(subscribable);
emitter.emit(message);
setTimeout(() => {
pipe.transform(subscribable);
expect(pipe.transform(subscribable)).toBe(message);
done();
}, 0);
});
it('should dispose of the existing subscription when subscribing to a new observable', (done) => {
pipe.transform(subscribable);
const newEmitter = new EventEmitter();
const newSubscribable = wrapSubscribable(newEmitter);
expect(pipe.transform(newSubscribable)).toBe(null);
emitter.emit(message);
// this should not affect the pipe
setTimeout(() => {
expect(pipe.transform(newSubscribable)).toBe(null);
done();
}, 0);
});
it('should request a change detection check upon receiving a new value', (done) => {
pipe.transform(subscribable);
emitter.emit(message);
setTimeout(() => {
expect(ref.markForCheck).toHaveBeenCalled();
done();
}, 10);
});
it('should return value for unchanged NaN', () => {
emitter.emit(null);
pipe.transform(subscribable);
emitter.next(NaN);
const firstResult = pipe.transform(subscribable);
const secondResult = pipe.transform(subscribable);
expect(firstResult).toBeNaN();
expect(secondResult).toBeNaN();
});
it('should not track signal reads in subscriptions', () => {
const trigger = signal(false);
const obs = new Observable(() => {
// Whenever `obs` is subscribed, synchronously read `trigger`.
trigger();
});
let trackCount = 0;
const tracker = computed(() => {
// Subscribe to `obs` within this `computed`. If the subscription side effect runs
// within the computed, then changes to `trigger` will invalidate this computed.
pipe.transform(obs);
// The computed returns how many times it's run.
return ++trackCount;
});
expect(tracker()).toBe(1);
trigger.set(true);
expect(tracker()).toBe(1);
});
});
describe('ngOnDestroy', () => {
it('should do nothing when no subscription', () => {
expect(() => pipe.ngOnDestroy()).not.toThrow();
});
it('should dispose of the existing subscription', (done) => {
pipe.transform(subscribable);
pipe.ngOnDestroy();
emitter.emit(message);
setTimeout(() => {
expect(pipe.transform(subscribable)).toBe(null);
done();
}, 0);
});
});
});
describe('Subscribable', () => {
it('should infer the type from the subscribable', () => {
const emitter = new EventEmitter<{name: 'T'}>();
// The following line will fail to compile if the type cannot be inferred.
const name = pipe.transform(emitter)?.name;
});
});
describe('Promise', () => {
const message = {};
let resolve: (result: any) => void;
let reject: (error: any) => void;
let promise: Promise<any>;
// adds longer timers for passing tests in IE
const timer = 10;
beforeEach(() => {
promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
});
describe('transform', () => {
it('should return null when subscribing to a promise', () => {
expect(pipe.transform(promise)).toBe(null);
});
it('should return the latest available value', (done) => {
pipe.transform(promise);
resolve(message);
setTimeout(() => {
expect(pipe.transform(promise)).toEqual(message);
done();
}, timer);
});
it('should return value when nothing has changed since the last call', (done) => {
pipe.transform(promise);
resolve(message);
setTimeout(() => {
pipe.transform(promise);
expect(pipe.transform(promise)).toBe(message);
done();
}, timer);
});
it('should dispose of the existing subscription when subscribing to a new promise', (done) => {
pipe.transform(promise);
promise = new Promise<any>(() => {});
expect(pipe.transform(promise)).toBe(null);
resolve(message);
setTimeout(() => {
expect(pipe.transform(promise)).toBe(null);
done();
}, timer);
});
it('should request a change detection check upon receiving a new value', (done) => {
pipe.transform(promise);
resolve(message);
setTimeout(() => {
expect(ref.markForCheck).toHaveBeenCalled();
done();
}, timer);
});
describe('ngOnDestroy', () => {
it('should do nothing when no source', () => {
expect(() => pipe.ngOnDestroy()).not.toThrow();
});
it('should dispose of the existing source', (done) => {
pipe.transform(promise);
expect(pipe.transform(promise)).toBe(null);
resolve(message);
setTimeout(() => {
expect(pipe.transform(promise)).toEqual(message);
pipe.ngOnDestroy();
expect(pipe.transform(promise)).toBe(null);
done();
}, timer);
});
it('should ignore signals after the pipe has been destroyed', (done) => {
pipe.transform(promise);
expect(pipe.transform(promise)).toBe(null);
pipe.ngOnDestroy();
resolve(message);
setTimeout(() => {
expect(pipe.transform(promise)).toBe(null);
done();
}, timer);
});
});
});
});
describe('null', () => {
it('should return null when given null', () => {
expect(pipe.transform(null)).toEqual(null);
});
});
describe('undefined', () => {
it('should return null when given undefined', () => {
expect(pipe.transform(undefined)).toEqual(null);
});
});
describe('other types', () => {
it('should throw when given an invalid object', () => {
expect(() => pipe.transform('some bogus object' as any)).toThrowError();
});
});
it('should be available as a standalone pipe', () => {
@Component({
selector: 'test-component',
imports: [AsyncPipe],
template: '{{ value | async }}',
standalone: true,
})
class TestComponent {
value = of('foo');
}
const fixture = TestBed.createComponent(TestComponent);
fixture.detectChanges();
const content = fixture.nativeElement.textContent;
expect(content).toBe('foo');
});
});
| |
012277
|
Implements an HTTP client API for Angular apps that relies on the `XMLHttpRequest` interface exposed by browsers.
Includes testability features, typed request and response objects, request and response interception,
observable APIs, and streamlined error handling.
For usage information, see the [HTTP Client](guide/http) guide.
| |
012289
|
/**
* @license
* Copyright Google LLC All Rights Reserved.sonpCallbackContext
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {HttpHandler} from '@angular/common/http/src/backend';
import {HttpClient} from '@angular/common/http/src/client';
import {HttpContext, HttpContextToken} from '@angular/common/http/src/context';
import {HTTP_INTERCEPTORS, HttpInterceptor} from '@angular/common/http/src/interceptor';
import {HttpRequest} from '@angular/common/http/src/request';
import {HttpEvent, HttpResponse} from '@angular/common/http/src/response';
import {HttpTestingController} from '@angular/common/http/testing/src/api';
import {HttpClientTestingModule} from '@angular/common/http/testing/src/module';
import {TestRequest} from '@angular/common/http/testing/src/request';
import {Injectable, Injector} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
const IS_INTERCEPTOR_C_ENABLED = new HttpContextToken<boolean | undefined>(() => undefined);
class TestInterceptor implements HttpInterceptor {
constructor(private value: string) {}
intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<HttpEvent<any>> {
const existing = req.headers.get('Intercepted');
const next = !!existing ? existing + ',' + this.value : this.value;
req = req.clone({setHeaders: {'Intercepted': next}});
return delegate.handle(req).pipe(
map((event) => {
if (event instanceof HttpResponse) {
const existing = event.headers.get('Intercepted');
const next = !!existing ? existing + ',' + this.value : this.value;
return event.clone({headers: event.headers.set('Intercepted', next)});
}
return event;
}),
);
}
}
class InterceptorA extends TestInterceptor {
constructor() {
super('A');
}
}
class InterceptorB extends TestInterceptor {
constructor() {
super('B');
}
}
class InterceptorC extends TestInterceptor {
constructor() {
super('C');
}
override intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<HttpEvent<any>> {
if (req.context.get(IS_INTERCEPTOR_C_ENABLED) === true) {
return super.intercept(req, delegate);
}
return delegate.handle(req);
}
}
@Injectable()
class ReentrantInterceptor implements HttpInterceptor {
constructor(private client: HttpClient) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
describe('HttpClientModule', () => {
let injector: Injector;
beforeEach(() => {
injector = TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
{provide: HTTP_INTERCEPTORS, useClass: InterceptorA, multi: true},
{provide: HTTP_INTERCEPTORS, useClass: InterceptorB, multi: true},
{provide: HTTP_INTERCEPTORS, useClass: InterceptorC, multi: true},
],
});
});
it('initializes HttpClient properly', (done) => {
injector
.get(HttpClient)
.get('/test', {responseType: 'text'})
.subscribe((value: string) => {
expect(value).toBe('ok!');
done();
});
injector.get(HttpTestingController).expectOne('/test').flush('ok!');
});
it('intercepts outbound responses in the order in which interceptors were bound', (done) => {
injector
.get(HttpClient)
.get('/test', {observe: 'response', responseType: 'text'})
.subscribe(() => done());
const req = injector.get(HttpTestingController).expectOne('/test') as TestRequest;
expect(req.request.headers.get('Intercepted')).toEqual('A,B');
req.flush('ok!');
});
it('intercepts outbound responses in the order in which interceptors were bound and include specifically enabled interceptor', (done) => {
injector
.get(HttpClient)
.get('/test', {
observe: 'response',
responseType: 'text',
context: new HttpContext().set(IS_INTERCEPTOR_C_ENABLED, true),
})
.subscribe((value) => done());
const req = injector.get(HttpTestingController).expectOne('/test') as TestRequest;
expect(req.request.headers.get('Intercepted')).toEqual('A,B,C');
req.flush('ok!');
});
it('intercepts inbound responses in the right (reverse binding) order', (done) => {
injector
.get(HttpClient)
.get('/test', {observe: 'response', responseType: 'text'})
.subscribe((value: HttpResponse<string>) => {
expect(value.headers.get('Intercepted')).toEqual('B,A');
done();
});
injector.get(HttpTestingController).expectOne('/test').flush('ok!');
});
it('allows interceptors to inject HttpClient', (done) => {
TestBed.resetTestingModule();
injector = TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [{provide: HTTP_INTERCEPTORS, useClass: ReentrantInterceptor, multi: true}],
});
injector
.get(HttpClient)
.get('/test')
.subscribe(() => {
done();
});
injector.get(HttpTestingController).expectOne('/test').flush('ok!');
});
});
| |
012307
|
describe('provideHttpClient', () => {
beforeEach(() => {
setCookie('');
TestBed.resetTestingModule();
});
afterEach(() => {
let controller: HttpTestingController;
try {
controller = TestBed.inject(HttpTestingController);
} catch (err) {
// A failure here means that TestBed wasn't successfully configured. Some tests intentionally
// test configuration errors and therefore exit without setting up TestBed for HTTP, so just
// exit here without performing verification on the `HttpTestingController` in that case.
return;
}
controller.verify();
});
it('should configure HttpClient', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe();
TestBed.inject(HttpTestingController).expectOne('/test').flush('');
});
it('should not contribute to stability', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
let stable = false;
TestBed.inject(ApplicationRef).isStable.subscribe((v) => {
stable = v;
});
expect(stable).toBe(true);
TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe();
expect(stable).toBe(true);
TestBed.inject(HttpTestingController).expectOne('/test').flush('');
expect(stable).toBe(true);
});
it('should not use legacy interceptors by default', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideLegacyInterceptor('legacy'),
provideHttpClientTesting(),
],
});
TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.has('X-Tag')).toBeFalse();
req.flush('');
});
it('withInterceptorsFromDi() should enable legacy interceptors', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptorsFromDi()),
provideLegacyInterceptor('alpha'),
provideLegacyInterceptor('beta'),
provideHttpClientTesting(),
],
});
TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('alpha,beta');
req.flush('');
});
describe('interceptor functions', () => {
it('should allow configuring interceptors', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(
withInterceptors([
makeLiteralTagInterceptorFn('alpha'),
makeLiteralTagInterceptorFn('beta'),
]),
),
provideHttpClientTesting(),
],
});
TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('alpha,beta');
req.flush('');
});
it('should accept multiple separate interceptor configs', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(
withInterceptors([makeLiteralTagInterceptorFn('alpha')]),
withInterceptors([makeLiteralTagInterceptorFn('beta')]),
),
provideHttpClientTesting(),
],
});
TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('alpha,beta');
req.flush('');
});
it('should allow injection from an interceptor context', () => {
const ALPHA = new InjectionToken<string>('alpha', {
providedIn: 'root',
factory: () => 'alpha',
});
const BETA = new InjectionToken<string>('beta', {providedIn: 'root', factory: () => 'beta'});
TestBed.configureTestingModule({
providers: [
provideHttpClient(
withInterceptors([makeTokenTagInterceptorFn(ALPHA), makeTokenTagInterceptorFn(BETA)]),
),
provideHttpClientTesting(),
],
});
TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('alpha,beta');
req.flush('');
});
it('should allow combination with legacy interceptors, before the legacy stack', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(
withInterceptors([makeLiteralTagInterceptorFn('functional')]),
withInterceptorsFromDi(),
),
provideHttpClientTesting(),
provideLegacyInterceptor('legacy'),
],
});
TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('functional,legacy');
req.flush('');
});
it('should allow combination with legacy interceptors, after the legacy stack', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(
withInterceptorsFromDi(),
withInterceptors([makeLiteralTagInterceptorFn('functional')]),
),
provideHttpClientTesting(),
provideLegacyInterceptor('legacy'),
],
});
TestBed.inject(HttpClient).get('/test', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Tag')).toEqual('legacy,functional');
req.flush('');
});
});
describe('xsrf protection', () => {
it('should enable xsrf protection by default', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
{provide: PLATFORM_ID, useValue: 'test'},
],
});
setXsrfToken('abcdefg');
TestBed.inject(HttpClient).post('/test', '', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-XSRF-TOKEN')).toEqual('abcdefg');
req.flush('');
});
it('withXsrfConfiguration() should allow customization of xsrf config', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(
withXsrfConfiguration({
cookieName: 'XSRF-CUSTOM-COOKIE',
headerName: 'X-Custom-Xsrf-Header',
}),
),
provideHttpClientTesting(),
{provide: PLATFORM_ID, useValue: 'test'},
],
});
setCookie('XSRF-CUSTOM-COOKIE=abcdefg');
TestBed.inject(HttpClient).post('/test', '', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.get('X-Custom-Xsrf-Header')).toEqual('abcdefg');
req.flush('');
});
it('withNoXsrfProtection() should disable xsrf protection', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withNoXsrfProtection()),
provideHttpClientTesting(),
{provide: PLATFORM_ID, useValue: 'test'},
],
});
setXsrfToken('abcdefg');
TestBed.inject(HttpClient).post('/test', '', {responseType: 'text'}).subscribe();
const req = TestBed.inject(HttpTestingController).expectOne('/test');
expect(req.request.headers.has('X-Custom-Xsrf-Header')).toBeFalse();
req.flush('');
});
it('should error if withXsrfConfiguration() and withNoXsrfProtection() are combined', () => {
expect(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withNoXsrfProtection(), withXsrfConfiguration({})),
provideHttpClientTesting(),
{provide: PLATFORM_ID, useValue: 'test'},
],
});
}).toThrow();
});
});
describe('JSONP support', () => {
it('should not be enabled by default', () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
TestBed.inject(HttpClient).jsonp('/test', 'callback').subscribe();
// Because no JSONP interceptor should be registered, this request should go to the testing
// backend.
TestBed.inject(HttpTestingController).expectOne('/test?callback=JSONP_CALLBACK').flush('');
});
it('should be enabled when using withJsonpSupport()', () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withJsonpSupport()),
provideHttpClientTesting(),
FAKE_JSONP_BACKEND_PROVIDER,
],
});
TestBed.inject(HttpClient).jsonp('/test', 'callback').subscribe();
TestBed.inject(HttpTestingController).expectNone('/test?callback=JSONP_CALLBACK');
});
});
| |
012316
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {HttpClientModule} from '@angular/common/http';
import {NgModule} from '@angular/core';
import {provideHttpClientTesting} from './provider';
/**
* Configures `HttpClientTestingBackend` as the `HttpBackend` used by `HttpClient`.
*
* Inject `HttpTestingController` to expect and flush requests in your tests.
*
* @publicApi
*
* @deprecated Add `provideHttpClientTesting()` to your providers instead.
*/
@NgModule({
imports: [HttpClientModule],
providers: [provideHttpClientTesting()],
})
export class HttpClientTestingModule {}
| |
012324
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ModuleWithProviders, NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS} from './interceptor';
import {
provideHttpClient,
withInterceptorsFromDi,
withJsonpSupport,
withNoXsrfProtection,
withXsrfConfiguration,
} from './provider';
import {
HttpXsrfCookieExtractor,
HttpXsrfInterceptor,
HttpXsrfTokenExtractor,
XSRF_DEFAULT_COOKIE_NAME,
XSRF_DEFAULT_HEADER_NAME,
XSRF_ENABLED,
} from './xsrf';
/**
* Configures XSRF protection support for outgoing requests.
*
* For a server that supports a cookie-based XSRF protection system,
* use directly to configure XSRF protection with the correct
* cookie and header names.
*
* If no names are supplied, the default cookie name is `XSRF-TOKEN`
* and the default header name is `X-XSRF-TOKEN`.
*
* @publicApi
* @deprecated Use withXsrfConfiguration({cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN'}) as
* providers instead or `withNoXsrfProtection` if you want to disabled XSRF protection.
*/
@NgModule({
providers: [
HttpXsrfInterceptor,
{provide: HTTP_INTERCEPTORS, useExisting: HttpXsrfInterceptor, multi: true},
{provide: HttpXsrfTokenExtractor, useClass: HttpXsrfCookieExtractor},
withXsrfConfiguration({
cookieName: XSRF_DEFAULT_COOKIE_NAME,
headerName: XSRF_DEFAULT_HEADER_NAME,
}).ɵproviders,
{provide: XSRF_ENABLED, useValue: true},
],
})
export class HttpClientXsrfModule {
/**
* Disable the default XSRF protection.
*/
static disable(): ModuleWithProviders<HttpClientXsrfModule> {
return {
ngModule: HttpClientXsrfModule,
providers: [withNoXsrfProtection().ɵproviders],
};
}
/**
* Configure XSRF protection.
* @param options An object that can specify either or both
* cookie name or header name.
* - Cookie name default is `XSRF-TOKEN`.
* - Header name default is `X-XSRF-TOKEN`.
*
*/
static withOptions(
options: {
cookieName?: string;
headerName?: string;
} = {},
): ModuleWithProviders<HttpClientXsrfModule> {
return {
ngModule: HttpClientXsrfModule,
providers: withXsrfConfiguration(options).ɵproviders,
};
}
}
/**
* Configures the dependency injector for `HttpClient`
* with supporting services for XSRF. Automatically imported by `HttpClientModule`.
*
* You can add interceptors to the chain behind `HttpClient` by binding them to the
* multiprovider for built-in DI token `HTTP_INTERCEPTORS`.
*
* @publicApi
* @deprecated use `provideHttpClient(withInterceptorsFromDi())` as providers instead
*/
@NgModule({
/**
* Configures the dependency injector where it is imported
* with supporting services for HTTP communications.
*/
providers: [provideHttpClient(withInterceptorsFromDi())],
})
export class HttpClientModule {}
/**
* Configures the dependency injector for `HttpClient`
* with supporting services for JSONP.
* Without this module, Jsonp requests reach the backend
* with method JSONP, where they are rejected.
*
* @publicApi
* @deprecated `withJsonpSupport()` as providers instead
*/
@NgModule({
providers: [withJsonpSupport().ɵproviders],
})
export class HttpClientJsonpModule {}
| |
012328
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {XhrFactory} from '@angular/common';
import {Injectable, ɵRuntimeError as RuntimeError} from '@angular/core';
import {from, Observable, Observer, of} from 'rxjs';
import {switchMap} from 'rxjs/operators';
import {HttpBackend} from './backend';
import {RuntimeErrorCode} from './errors';
import {HttpHeaders} from './headers';
import {HttpRequest} from './request';
import {
HTTP_STATUS_CODE_NO_CONTENT,
HTTP_STATUS_CODE_OK,
HttpDownloadProgressEvent,
HttpErrorResponse,
HttpEvent,
HttpEventType,
HttpHeaderResponse,
HttpJsonParseError,
HttpResponse,
HttpUploadProgressEvent,
} from './response';
const XSSI_PREFIX = /^\)\]\}',?\n/;
/**
* Determine an appropriate URL for the response, by checking either
* XMLHttpRequest.responseURL or the X-Request-URL header.
*/
function getResponseUrl(xhr: any): string | null {
if ('responseURL' in xhr && xhr.responseURL) {
return xhr.responseURL;
}
if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
return xhr.getResponseHeader('X-Request-URL');
}
return null;
}
/**
* Uses `XMLHttpRequest` to send requests to a backend server.
* @see {@link HttpHandler}
* @see {@link JsonpClientBackend}
*
* @publicApi
*/
@Injectable()
export class HttpXhrBackend implements HttpBackend {
constructor(private xhrFactory: XhrFactory) {}
/**
* Processes a request and returns a stream of response events.
* @param req The request object.
* @returns An observable of the response events.
*/
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
// Quick check to give a better error message when a user attempts to use
// HttpClient.jsonp() without installing the HttpClientJsonpModule
if (req.method === 'JSONP') {
throw new RuntimeError(
RuntimeErrorCode.MISSING_JSONP_MODULE,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
`Cannot make a JSONP request without JSONP support. To fix the problem, either add the \`withJsonpSupport()\` call (if \`provideHttpClient()\` is used) or import the \`HttpClientJsonpModule\` in the root NgModule.`,
);
}
// Check whether this factory has a special function to load an XHR implementation
// for various non-browser environments. We currently limit it to only `ServerXhr`
// class, which needs to load an XHR implementation.
const xhrFactory: XhrFactory & {ɵloadImpl?: () => Promise<void>} = this.xhrFactory;
const source: Observable<void | null> = xhrFactory.ɵloadImpl
? from(xhrFactory.ɵloadImpl())
: of(null);
| |
012357
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
EnvironmentProviders,
inject,
InjectionToken,
makeEnvironmentProviders,
Provider,
} from '@angular/core';
import {HttpBackend, HttpHandler} from './backend';
import {HttpClient} from './client';
import {FetchBackend} from './fetch';
import {
HTTP_INTERCEPTOR_FNS,
HttpInterceptorFn,
HttpInterceptorHandler,
legacyInterceptorFnFactory,
} from './interceptor';
import {
jsonpCallbackContext,
JsonpCallbackContext,
JsonpClientBackend,
jsonpInterceptorFn,
} from './jsonp';
import {HttpXhrBackend} from './xhr';
import {
HttpXsrfCookieExtractor,
HttpXsrfTokenExtractor,
XSRF_COOKIE_NAME,
XSRF_ENABLED,
XSRF_HEADER_NAME,
xsrfInterceptorFn,
} from './xsrf';
/**
* Identifies a particular kind of `HttpFeature`.
*
* @publicApi
*/
export enum HttpFeatureKind {
Interceptors,
LegacyInterceptors,
CustomXsrfConfiguration,
NoXsrfProtection,
JsonpSupport,
RequestsMadeViaParent,
Fetch,
}
/**
* A feature for use when configuring `provideHttpClient`.
*
* @publicApi
*/
export interface HttpFeature<KindT extends HttpFeatureKind> {
ɵkind: KindT;
ɵproviders: Provider[];
}
function makeHttpFeature<KindT extends HttpFeatureKind>(
kind: KindT,
providers: Provider[],
): HttpFeature<KindT> {
return {
ɵkind: kind,
ɵproviders: providers,
};
}
/**
* Configures Angular's `HttpClient` service to be available for injection.
*
* By default, `HttpClient` will be configured for injection with its default options for XSRF
* protection of outgoing requests. Additional configuration options can be provided by passing
* feature functions to `provideHttpClient`. For example, HTTP interceptors can be added using the
* `withInterceptors(...)` feature.
*
* <div class="alert is-helpful">
*
* It's strongly recommended to enable
* [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for applications that use
* Server-Side Rendering for better performance and compatibility. To enable `fetch`, add
* `withFetch()` feature to the `provideHttpClient()` call at the root of the application:
*
* ```
* provideHttpClient(withFetch());
* ```
*
* </div>
*
* @see {@link withInterceptors}
* @see {@link withInterceptorsFromDi}
* @see {@link withXsrfConfiguration}
* @see {@link withNoXsrfProtection}
* @see {@link withJsonpSupport}
* @see {@link withRequestsMadeViaParent}
* @see {@link withFetch}
*/
export function provideHttpClient(
...features: HttpFeature<HttpFeatureKind>[]
): EnvironmentProviders {
if (ngDevMode) {
const featureKinds = new Set(features.map((f) => f.ɵkind));
if (
featureKinds.has(HttpFeatureKind.NoXsrfProtection) &&
featureKinds.has(HttpFeatureKind.CustomXsrfConfiguration)
) {
throw new Error(
ngDevMode
? `Configuration error: found both withXsrfConfiguration() and withNoXsrfProtection() in the same call to provideHttpClient(), which is a contradiction.`
: '',
);
}
}
const providers: Provider[] = [
HttpClient,
HttpXhrBackend,
HttpInterceptorHandler,
{provide: HttpHandler, useExisting: HttpInterceptorHandler},
{
provide: HttpBackend,
useFactory: () => {
return inject(FetchBackend, {optional: true}) ?? inject(HttpXhrBackend);
},
},
{
provide: HTTP_INTERCEPTOR_FNS,
useValue: xsrfInterceptorFn,
multi: true,
},
{provide: XSRF_ENABLED, useValue: true},
{provide: HttpXsrfTokenExtractor, useClass: HttpXsrfCookieExtractor},
];
for (const feature of features) {
providers.push(...feature.ɵproviders);
}
return makeEnvironmentProviders(providers);
}
/**
* Adds one or more functional-style HTTP interceptors to the configuration of the `HttpClient`
* instance.
*
* @see {@link HttpInterceptorFn}
* @see {@link provideHttpClient}
* @publicApi
*/
export function withInterceptors(
interceptorFns: HttpInterceptorFn[],
): HttpFeature<HttpFeatureKind.Interceptors> {
return makeHttpFeature(
HttpFeatureKind.Interceptors,
interceptorFns.map((interceptorFn) => {
return {
provide: HTTP_INTERCEPTOR_FNS,
useValue: interceptorFn,
multi: true,
};
}),
);
}
const LEGACY_INTERCEPTOR_FN = new InjectionToken<HttpInterceptorFn>(
ngDevMode ? 'LEGACY_INTERCEPTOR_FN' : '',
);
/**
* Includes class-based interceptors configured using a multi-provider in the current injector into
* the configured `HttpClient` instance.
*
* Prefer `withInterceptors` and functional interceptors instead, as support for DI-provided
* interceptors may be phased out in a later release.
*
* @see {@link HttpInterceptor}
* @see {@link HTTP_INTERCEPTORS}
* @see {@link provideHttpClient}
*/
export function withInterceptorsFromDi(): HttpFeature<HttpFeatureKind.LegacyInterceptors> {
// Note: the legacy interceptor function is provided here via an intermediate token
// (`LEGACY_INTERCEPTOR_FN`), using a pattern which guarantees that if these providers are
// included multiple times, all of the multi-provider entries will have the same instance of the
// interceptor function. That way, the `HttpINterceptorHandler` will dedup them and legacy
// interceptors will not run multiple times.
return makeHttpFeature(HttpFeatureKind.LegacyInterceptors, [
{
provide: LEGACY_INTERCEPTOR_FN,
useFactory: legacyInterceptorFnFactory,
},
{
provide: HTTP_INTERCEPTOR_FNS,
useExisting: LEGACY_INTERCEPTOR_FN,
multi: true,
},
]);
}
/**
* Customizes the XSRF protection for the configuration of the current `HttpClient` instance.
*
* This feature is incompatible with the `withNoXsrfProtection` feature.
*
* @see {@link provideHttpClient}
*/
export function withXsrfConfiguration({
cookieName,
headerName,
}: {
cookieName?: string;
headerName?: string;
}): HttpFeature<HttpFeatureKind.CustomXsrfConfiguration> {
const providers: Provider[] = [];
if (cookieName !== undefined) {
providers.push({provide: XSRF_COOKIE_NAME, useValue: cookieName});
}
if (headerName !== undefined) {
providers.push({provide: XSRF_HEADER_NAME, useValue: headerName});
}
return makeHttpFeature(HttpFeatureKind.CustomXsrfConfiguration, providers);
}
/**
* Disables XSRF protection in the configuration of the current `HttpClient` instance.
*
* This feature is incompatible with the `withXsrfConfiguration` feature.
*
* @see {@link provideHttpClient}
*/
export function withNoXsrfProtection(): HttpFeature<HttpFeatureKind.NoXsrfProtection> {
return makeHttpFeature(HttpFeatureKind.NoXsrfProtection, [
{
provide: XSRF_ENABLED,
useValue: false,
},
]);
}
/**
* Add JSONP support to the configuration of the current `HttpClient` instance.
*
* @see {@link provideHttpClient}
*/
export function withJsonpSupport(): HttpFeature<HttpFeatureKind.JsonpSupport> {
return makeHttpFeature(HttpFeatureKind.JsonpSupport, [
JsonpClientBackend,
{provide: JsonpCallbackContext, useFactory: jsonpCallbackContext},
{provide: HTTP_INTERCEPTOR_FNS, useValue: jsonpInterceptorFn, multi: true},
]);
}
/**
| |
012369
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export const PLATFORM_BROWSER_ID = 'browser';
export const PLATFORM_SERVER_ID = 'server';
/**
* Returns whether a platform id represents a browser platform.
* @publicApi
*/
export function isPlatformBrowser(platformId: Object): boolean {
return platformId === PLATFORM_BROWSER_ID;
}
/**
* Returns whether a platform id represents a server platform.
* @publicApi
*/
export function isPlatformServer(platformId: Object): boolean {
return platformId === PLATFORM_SERVER_ID;
}
| |
012371
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {inject, PLATFORM_ID, ɵɵdefineInjectable} from '@angular/core';
import {DOCUMENT} from './dom_tokens';
import {isPlatformBrowser} from './platform_id';
/**
* Defines a scroll position manager. Implemented by `BrowserViewportScroller`.
*
* @publicApi
*/
export abstract class ViewportScroller {
// De-sugared tree-shakable injection
// See #23917
/** @nocollapse */
static ɵprov = /** @pureOrBreakMyCode */ /* @__PURE__ */ ɵɵdefineInjectable({
token: ViewportScroller,
providedIn: 'root',
factory: () =>
isPlatformBrowser(inject(PLATFORM_ID))
? new BrowserViewportScroller(inject(DOCUMENT), window)
: new NullViewportScroller(),
});
/**
* Configures the top offset used when scrolling to an anchor.
* @param offset A position in screen coordinates (a tuple with x and y values)
* or a function that returns the top offset position.
*
*/
abstract setOffset(offset: [number, number] | (() => [number, number])): void;
/**
* Retrieves the current scroll position.
* @returns A position in screen coordinates (a tuple with x and y values).
*/
abstract getScrollPosition(): [number, number];
/**
* Scrolls to a specified position.
* @param position A position in screen coordinates (a tuple with x and y values).
*/
abstract scrollToPosition(position: [number, number]): void;
/**
* Scrolls to an anchor element.
* @param anchor The ID of the anchor element.
*/
abstract scrollToAnchor(anchor: string): void;
/**
* Disables automatic scroll restoration provided by the browser.
* See also [window.history.scrollRestoration
* info](https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration).
*/
abstract setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void;
}
/**
* Manages the scroll position for a browser window.
*/
export class BrowserViewportScroller implements ViewportScroller {
private offset: () => [number, number] = () => [0, 0];
constructor(
private document: Document,
private window: Window,
) {}
/**
* Configures the top offset used when scrolling to an anchor.
* @param offset A position in screen coordinates (a tuple with x and y values)
* or a function that returns the top offset position.
*
*/
setOffset(offset: [number, number] | (() => [number, number])): void {
if (Array.isArray(offset)) {
this.offset = () => offset;
} else {
this.offset = offset;
}
}
/**
* Retrieves the current scroll position.
* @returns The position in screen coordinates.
*/
getScrollPosition(): [number, number] {
return [this.window.scrollX, this.window.scrollY];
}
/**
* Sets the scroll position.
* @param position The new position in screen coordinates.
*/
scrollToPosition(position: [number, number]): void {
this.window.scrollTo(position[0], position[1]);
}
/**
* Scrolls to an element and attempts to focus the element.
*
* Note that the function name here is misleading in that the target string may be an ID for a
* non-anchor element.
*
* @param target The ID of an element or name of the anchor.
*
* @see https://html.spec.whatwg.org/#the-indicated-part-of-the-document
* @see https://html.spec.whatwg.org/#scroll-to-fragid
*/
scrollToAnchor(target: string): void {
const elSelected = findAnchorFromDocument(this.document, target);
if (elSelected) {
this.scrollToElement(elSelected);
// After scrolling to the element, the spec dictates that we follow the focus steps for the
// target. Rather than following the robust steps, simply attempt focus.
//
// @see https://html.spec.whatwg.org/#get-the-focusable-area
// @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/focus
// @see https://html.spec.whatwg.org/#focusable-area
elSelected.focus();
}
}
/**
* Disables automatic scroll restoration provided by the browser.
*/
setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void {
this.window.history.scrollRestoration = scrollRestoration;
}
/**
* Scrolls to an element using the native offset and the specified offset set on this scroller.
*
* The offset can be used when we know that there is a floating header and scrolling naively to an
* element (ex: `scrollIntoView`) leaves the element hidden behind the floating header.
*/
private scrollToElement(el: HTMLElement): void {
const rect = el.getBoundingClientRect();
const left = rect.left + this.window.pageXOffset;
const top = rect.top + this.window.pageYOffset;
const offset = this.offset();
this.window.scrollTo(left - offset[0], top - offset[1]);
}
}
function findAnchorFromDocument(document: Document, target: string): HTMLElement | null {
const documentResult = document.getElementById(target) || document.getElementsByName(target)[0];
if (documentResult) {
return documentResult;
}
// `getElementById` and `getElementsByName` won't pierce through the shadow DOM so we
// have to traverse the DOM manually and do the lookup through the shadow roots.
if (
typeof document.createTreeWalker === 'function' &&
document.body &&
typeof document.body.attachShadow === 'function'
) {
const treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
let currentNode = treeWalker.currentNode as HTMLElement | null;
while (currentNode) {
const shadowRoot = currentNode.shadowRoot;
if (shadowRoot) {
// Note that `ShadowRoot` doesn't support `getElementsByName`
// so we have to fall back to `querySelector`.
const result =
shadowRoot.getElementById(target) || shadowRoot.querySelector(`[name="${target}"]`);
if (result) {
return result;
}
}
currentNode = treeWalker.nextNode() as HTMLElement | null;
}
}
return null;
}
/**
* Provides an empty implementation of the viewport scroller.
*/
export class NullViewportScroller implements ViewportScroller {
/**
* Empty implementation
*/
setOffset(offset: [number, number] | (() => [number, number])): void {}
/**
* Empty implementation
*/
getScrollPosition(): [number, number] {
return [0, 0];
}
/**
* Empty implementation
*/
scrollToPosition(position: [number, number]): void {}
/**
* Empty implementation
*/
scrollToAnchor(anchor: string): void {}
/**
* Empty implementation
*/
setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void {}
}
| |
012374
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {COMMON_DIRECTIVES} from './directives/index';
import {COMMON_PIPES} from './pipes/index';
// Note: This does not contain the location providers,
// as they need some platform specific implementations to work.
/**
* Exports all the basic Angular directives and pipes,
* such as `NgIf`, `NgForOf`, `DecimalPipe`, and so on.
* Re-exported by `BrowserModule`, which is included automatically in the root
* `AppModule` when you create a new app with the CLI `new` command.
*
* @publicApi
*/
@NgModule({
imports: [COMMON_DIRECTIVES, COMMON_PIPES],
exports: [COMMON_DIRECTIVES, COMMON_PIPES],
})
export class CommonModule {}
| |
012377
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentRef,
createNgModule,
Directive,
DoCheck,
Injector,
Input,
NgModuleFactory,
NgModuleRef,
OnChanges,
OnDestroy,
SimpleChanges,
Type,
ViewContainerRef,
} from '@angular/core';
/**
* Instantiates a {@link Component} type and inserts its Host View into the current View.
* `NgComponentOutlet` provides a declarative approach for dynamic component creation.
*
* `NgComponentOutlet` requires a component type, if a falsy value is set the view will clear and
* any existing component will be destroyed.
*
* @usageNotes
*
* ### Fine tune control
*
* You can control the component creation process by using the following optional attributes:
*
* * `ngComponentOutletInputs`: Optional component inputs object, which will be bind to the
* component.
*
* * `ngComponentOutletInjector`: Optional custom {@link Injector} that will be used as parent for
* the Component. Defaults to the injector of the current view container.
*
* * `ngComponentOutletContent`: Optional list of projectable nodes to insert into the content
* section of the component, if it exists.
*
* * `ngComponentOutletNgModule`: Optional NgModule class reference to allow loading another
* module dynamically, then loading a component from that module.
*
* * `ngComponentOutletNgModuleFactory`: Deprecated config option that allows providing optional
* NgModule factory to allow loading another module dynamically, then loading a component from that
* module. Use `ngComponentOutletNgModule` instead.
*
* ### Syntax
*
* Simple
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression"></ng-container>
* ```
*
* With inputs
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression;
* inputs: inputsExpression;">
* </ng-container>
* ```
*
* Customized injector/content
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression;
* injector: injectorExpression;
* content: contentNodesExpression;">
* </ng-container>
* ```
*
* Customized NgModule reference
* ```
* <ng-container *ngComponentOutlet="componentTypeExpression;
* ngModule: ngModuleClass;">
* </ng-container>
* ```
*
* ### A simple example
*
* {@example common/ngComponentOutlet/ts/module.ts region='SimpleExample'}
*
* A more complete example with additional options:
*
* {@example common/ngComponentOutlet/ts/module.ts region='CompleteExample'}
*
* @publicApi
* @ngModule CommonModule
*/
@Directive({
selector: '[ngComponentOutlet]',
standalone: true,
})
export class NgComponentOutlet implements OnChanges, DoCheck, OnDestroy {
@Input() ngComponentOutlet: Type<any> | null = null;
@Input() ngComponentOutletInputs?: Record<string, unknown>;
@Input() ngComponentOutletInjector?: Injector;
@Input() ngComponentOutletContent?: any[][];
@Input() ngComponentOutletNgModule?: Type<any>;
/**
* @deprecated This input is deprecated, use `ngComponentOutletNgModule` instead.
*/
@Input() ngComponentOutletNgModuleFactory?: NgModuleFactory<any>;
private _componentRef: ComponentRef<any> | undefined;
private _moduleRef: NgModuleRef<any> | undefined;
/**
* A helper data structure that allows us to track inputs that were part of the
* ngComponentOutletInputs expression. Tracking inputs is necessary for proper removal of ones
* that are no longer referenced.
*/
private _inputsUsed = new Map<string, boolean>();
constructor(private _viewContainerRef: ViewContainerRef) {}
private _needToReCreateNgModuleInstance(changes: SimpleChanges): boolean {
// Note: square brackets property accessor is safe for Closure compiler optimizations (the
// `changes` argument of the `ngOnChanges` lifecycle hook retains the names of the fields that
// were changed).
return (
changes['ngComponentOutletNgModule'] !== undefined ||
changes['ngComponentOutletNgModuleFactory'] !== undefined
);
}
private _needToReCreateComponentInstance(changes: SimpleChanges): boolean {
// Note: square brackets property accessor is safe for Closure compiler optimizations (the
// `changes` argument of the `ngOnChanges` lifecycle hook retains the names of the fields that
// were changed).
return (
changes['ngComponentOutlet'] !== undefined ||
changes['ngComponentOutletContent'] !== undefined ||
changes['ngComponentOutletInjector'] !== undefined ||
this._needToReCreateNgModuleInstance(changes)
);
}
/** @nodoc */
ngOnChanges(changes: SimpleChanges) {
if (this._needToReCreateComponentInstance(changes)) {
this._viewContainerRef.clear();
this._inputsUsed.clear();
this._componentRef = undefined;
if (this.ngComponentOutlet) {
const injector = this.ngComponentOutletInjector || this._viewContainerRef.parentInjector;
if (this._needToReCreateNgModuleInstance(changes)) {
this._moduleRef?.destroy();
if (this.ngComponentOutletNgModule) {
this._moduleRef = createNgModule(
this.ngComponentOutletNgModule,
getParentInjector(injector),
);
} else if (this.ngComponentOutletNgModuleFactory) {
this._moduleRef = this.ngComponentOutletNgModuleFactory.create(
getParentInjector(injector),
);
} else {
this._moduleRef = undefined;
}
}
this._componentRef = this._viewContainerRef.createComponent(this.ngComponentOutlet, {
injector,
ngModuleRef: this._moduleRef,
projectableNodes: this.ngComponentOutletContent,
});
}
}
}
/** @nodoc */
ngDoCheck() {
if (this._componentRef) {
if (this.ngComponentOutletInputs) {
for (const inputName of Object.keys(this.ngComponentOutletInputs)) {
this._inputsUsed.set(inputName, true);
}
}
this._applyInputStateDiff(this._componentRef);
}
}
/** @nodoc */
ngOnDestroy() {
this._moduleRef?.destroy();
}
private _applyInputStateDiff(componentRef: ComponentRef<unknown>) {
for (const [inputName, touched] of this._inputsUsed) {
if (!touched) {
// The input that was previously active no longer exists and needs to be set to undefined.
componentRef.setInput(inputName, undefined);
this._inputsUsed.delete(inputName);
} else {
// Since touched is true, it can be asserted that the inputs object is not empty.
componentRef.setInput(inputName, this.ngComponentOutletInputs![inputName]);
this._inputsUsed.set(inputName, false);
}
}
}
}
// Helper function that returns an Injector instance of a parent NgModule.
function getParentInjector(injector: Injector): Injector {
const parentNgModule = injector.get(NgModuleRef);
return parentNgModule.injector;
}
| |
012381
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
DoCheck,
EmbeddedViewRef,
Input,
IterableChangeRecord,
IterableChanges,
IterableDiffer,
IterableDiffers,
NgIterable,
TemplateRef,
TrackByFunction,
ViewContainerRef,
ɵRuntimeError as RuntimeError,
} from '@angular/core';
import {RuntimeErrorCode} from '../errors';
/**
* @publicApi
*/
export class NgForOfContext<T, U extends NgIterable<T> = NgIterable<T>> {
constructor(
/** Reference to the current item from the collection. */
public $implicit: T,
/**
* The value of the iterable expression. Useful when the expression is
* more complex then a property access, for example when using the async pipe
* (`userStreams | async`).
*/
public ngForOf: U,
/** Returns an index of the current item in the collection. */
public index: number,
/** Returns total amount of items in the collection. */
public count: number,
) {}
// Indicates whether this is the first item in the collection.
get first(): boolean {
return this.index === 0;
}
// Indicates whether this is the last item in the collection.
get last(): boolean {
return this.index === this.count - 1;
}
// Indicates whether an index of this item in the collection is even.
get even(): boolean {
return this.index % 2 === 0;
}
// Indicates whether an index of this item in the collection is odd.
get odd(): boolean {
return !this.even;
}
}
/**
* A [structural directive](guide/directives/structural-directives) that renders
* a template for each item in a collection.
* The directive is placed on an element, which becomes the parent
* of the cloned templates.
*
* The `ngForOf` directive is generally used in the
* [shorthand form](guide/directives/structural-directives#asterisk) `*ngFor`.
* In this form, the template to be rendered for each iteration is the content
* of an anchor element containing the directive.
*
* The following example shows the shorthand syntax with some options,
* contained in an `<li>` element.
*
* ```
* <li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li>
* ```
*
* The shorthand form expands into a long form that uses the `ngForOf` selector
* on an `<ng-template>` element.
* The content of the `<ng-template>` element is the `<li>` element that held the
* short-form directive.
*
* Here is the expanded version of the short-form example.
*
* ```
* <ng-template ngFor let-item [ngForOf]="items" let-i="index" [ngForTrackBy]="trackByFn">
* <li>...</li>
* </ng-template>
* ```
*
* Angular automatically expands the shorthand syntax as it compiles the template.
* The context for each embedded view is logically merged to the current component
* context according to its lexical position.
*
* When using the shorthand syntax, Angular allows only [one structural directive
* on an element](guide/directives/structural-directives#one-per-element).
* If you want to iterate conditionally, for example,
* put the `*ngIf` on a container element that wraps the `*ngFor` element.
* For further discussion, see
* [Structural Directives](guide/directives/structural-directives#one-per-element).
*
* @usageNotes
*
* ### Local variables
*
* `NgForOf` provides exported values that can be aliased to local variables.
* For example:
*
* ```
* <li *ngFor="let user of users; index as i; first as isFirst">
* {{i}}/{{users.length}}. {{user}} <span *ngIf="isFirst">default</span>
* </li>
* ```
*
* The following exported values can be aliased to local variables:
*
* - `$implicit: T`: The value of the individual items in the iterable (`ngForOf`).
* - `ngForOf: NgIterable<T>`: The value of the iterable expression. Useful when the expression is
* more complex then a property access, for example when using the async pipe (`userStreams |
* async`).
* - `index: number`: The index of the current item in the iterable.
* - `count: number`: The length of the iterable.
* - `first: boolean`: True when the item is the first item in the iterable.
* - `last: boolean`: True when the item is the last item in the iterable.
* - `even: boolean`: True when the item has an even index in the iterable.
* - `odd: boolean`: True when the item has an odd index in the iterable.
*
* ### Change propagation
*
* When the contents of the iterator changes, `NgForOf` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
*
* Angular uses object identity to track insertions and deletions within the iterator and reproduce
* those changes in the DOM. This has important implications for animations and any stateful
* controls that are present, such as `<input>` elements that accept user input. Inserted rows can
* be animated in, deleted rows can be animated out, and unchanged rows retain any unsaved state
* such as user input.
* For more on animations, see [Transitions and Triggers](guide/animations/transition-and-triggers).
*
* The identities of elements in the iterator can change while the data does not.
* This can happen, for example, if the iterator is produced from an RPC to the server, and that
* RPC is re-run. Even if the data hasn't changed, the second response produces objects with
* different identities, and Angular must tear down the entire DOM and rebuild it (as if all old
* elements were deleted and all new elements inserted).
*
* To avoid this expensive operation, you can customize the default tracking algorithm.
* by supplying the `trackBy` option to `NgForOf`.
* `trackBy` takes a function that has two arguments: `index` and `item`.
* If `trackBy` is given, Angular tracks changes by the return value of the function.
*
* @see [Structural Directives](guide/directives/structural-directives)
* @ngModule CommonModule
* @publicApi
*/
| |
012382
|
Directive({
selector: '[ngFor][ngForOf]',
standalone: true,
})
export class NgForOf<T, U extends NgIterable<T> = NgIterable<T>> implements DoCheck {
/**
* The value of the iterable expression, which can be used as a
* [template input variable](guide/directives/structural-directives#shorthand).
*/
@Input()
set ngForOf(ngForOf: (U & NgIterable<T>) | undefined | null) {
this._ngForOf = ngForOf;
this._ngForOfDirty = true;
}
/**
* Specifies a custom `TrackByFunction` to compute the identity of items in an iterable.
*
* If a custom `TrackByFunction` is not provided, `NgForOf` will use the item's [object
* identity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)
* as the key.
*
* `NgForOf` uses the computed key to associate items in an iterable with DOM elements
* it produces for these items.
*
* A custom `TrackByFunction` is useful to provide good user experience in cases when items in an
* iterable rendered using `NgForOf` have a natural identifier (for example, custom ID or a
* primary key), and this iterable could be updated with new object instances that still
* represent the same underlying entity (for example, when data is re-fetched from the server,
* and the iterable is recreated and re-rendered, but most of the data is still the same).
*
* @see {@link TrackByFunction}
*/
@Input()
set ngForTrackBy(fn: TrackByFunction<T>) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') {
console.warn(
`trackBy must be a function, but received ${JSON.stringify(fn)}. ` +
`See https://angular.io/api/common/NgForOf#change-propagation for more information.`,
);
}
this._trackByFn = fn;
}
get ngForTrackBy(): TrackByFunction<T> {
return this._trackByFn;
}
private _ngForOf: U | undefined | null = null;
private _ngForOfDirty: boolean = true;
private _differ: IterableDiffer<T> | null = null;
// TODO(issue/24571): remove '!'
// waiting for microsoft/typescript#43662 to allow the return type `TrackByFunction|undefined` for
// the getter
private _trackByFn!: TrackByFunction<T>;
constructor(
private _viewContainer: ViewContainerRef,
private _template: TemplateRef<NgForOfContext<T, U>>,
private _differs: IterableDiffers,
) {}
/**
* A reference to the template that is stamped out for each item in the iterable.
* @see [template reference variable](guide/templates/variables#template-reference-variables)
*/
@Input()
set ngForTemplate(value: TemplateRef<NgForOfContext<T, U>>) {
// TODO(TS2.1): make TemplateRef<Partial<NgForRowOf<T>>> once we move to TS v2.1
// The current type is too restrictive; a template that just uses index, for example,
// should be acceptable.
if (value) {
this._template = value;
}
}
/**
* Applies the changes when needed.
* @nodoc
*/
ngDoCheck(): void {
if (this._ngForOfDirty) {
this._ngForOfDirty = false;
// React on ngForOf changes only once all inputs have been initialized
const value = this._ngForOf;
if (!this._differ && value) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
try {
// CAUTION: this logic is duplicated for production mode below, as the try-catch
// is only present in development builds.
this._differ = this._differs.find(value).create(this.ngForTrackBy);
} catch {
let errorMessage =
`Cannot find a differ supporting object '${value}' of type '` +
`${getTypeName(value)}'. NgFor only supports binding to Iterables, such as Arrays.`;
if (typeof value === 'object') {
errorMessage += ' Did you mean to use the keyvalue pipe?';
}
throw new RuntimeError(RuntimeErrorCode.NG_FOR_MISSING_DIFFER, errorMessage);
}
} else {
// CAUTION: this logic is duplicated for development mode above, as the try-catch
// is only present in development builds.
this._differ = this._differs.find(value).create(this.ngForTrackBy);
}
}
}
if (this._differ) {
const changes = this._differ.diff(this._ngForOf);
if (changes) this._applyChanges(changes);
}
}
private _applyChanges(changes: IterableChanges<T>) {
const viewContainer = this._viewContainer;
changes.forEachOperation(
(
item: IterableChangeRecord<T>,
adjustedPreviousIndex: number | null,
currentIndex: number | null,
) => {
if (item.previousIndex == null) {
// NgForOf is never "null" or "undefined" here because the differ detected
// that a new item needs to be inserted from the iterable. This implies that
// there is an iterable value for "_ngForOf".
viewContainer.createEmbeddedView(
this._template,
new NgForOfContext<T, U>(item.item, this._ngForOf!, -1, -1),
currentIndex === null ? undefined : currentIndex,
);
} else if (currentIndex == null) {
viewContainer.remove(adjustedPreviousIndex === null ? undefined : adjustedPreviousIndex);
} else if (adjustedPreviousIndex !== null) {
const view = viewContainer.get(adjustedPreviousIndex)!;
viewContainer.move(view, currentIndex);
applyViewChange(view as EmbeddedViewRef<NgForOfContext<T, U>>, item);
}
},
);
for (let i = 0, ilen = viewContainer.length; i < ilen; i++) {
const viewRef = <EmbeddedViewRef<NgForOfContext<T, U>>>viewContainer.get(i);
const context = viewRef.context;
context.index = i;
context.count = ilen;
context.ngForOf = this._ngForOf!;
}
changes.forEachIdentityChange((record: any) => {
const viewRef = <EmbeddedViewRef<NgForOfContext<T, U>>>viewContainer.get(record.currentIndex);
applyViewChange(viewRef, record);
});
}
/**
* Asserts the correct type of the context for the template that `NgForOf` will render.
*
* The presence of this method is a signal to the Ivy template type-check compiler that the
* `NgForOf` structural directive renders its template with a specific context type.
*/
static ngTemplateContextGuard<T, U extends NgIterable<T>>(
dir: NgForOf<T, U>,
ctx: any,
): ctx is NgForOfContext<T, U> {
return true;
}
}
// Also export the `NgForOf` class as `NgFor` to improve the DX for
// cases when the directive is used as standalone, so the class name
// matches the CSS selector (*ngFor).
export {NgForOf as NgFor};
function applyViewChange<T>(
view: EmbeddedViewRef<NgForOfContext<T>>,
record: IterableChangeRecord<T>,
) {
view.context.$implicit = record.item;
}
function getTypeName(type: any): string {
return type['name'] || typeof type;
}
| |
012383
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
DoCheck,
ElementRef,
Input,
IterableDiffers,
KeyValueDiffers,
Renderer2,
ɵstringify as stringify,
} from '@angular/core';
type NgClassSupportedTypes = string[] | Set<string> | {[klass: string]: any} | null | undefined;
const WS_REGEXP = /\s+/;
const EMPTY_ARRAY: string[] = [];
/**
* Represents internal object used to track state of each CSS class. There are 3 different (boolean)
* flags that, combined together, indicate state of a given CSS class:
* - enabled: indicates if a class should be present in the DOM (true) or not (false);
* - changed: tracks if a class was toggled (added or removed) during the custom dirty-checking
* process; changed classes must be synchronized with the DOM;
* - touched: tracks if a class is present in the current object bound to the class / ngClass input;
* classes that are not present any more can be removed from the internal data structures;
*/
interface CssClassState {
// PERF: could use a bit mask to represent state as all fields are boolean flags
enabled: boolean;
changed: boolean;
touched: boolean;
}
/**
* @ngModule CommonModule
*
* @usageNotes
* ```
* <some-element [ngClass]="'first second'">...</some-element>
*
* <some-element [ngClass]="['first', 'second']">...</some-element>
*
* <some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
*
* <some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
*
* <some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
* ```
*
* @description
*
* Adds and removes CSS classes on an HTML element.
*
* The CSS classes are updated as follows, depending on the type of the expression evaluation:
* - `string` - the CSS classes listed in the string (space delimited) are added,
* - `Array` - the CSS classes declared as Array elements are added,
* - `Object` - keys are CSS classes that get added when the expression given in the value
* evaluates to a truthy value, otherwise they are removed.
*
* @publicApi
*/
@Directive({
selector: '[ngClass]',
standalone: true,
})
export class NgClass implements DoCheck {
private initialClasses = EMPTY_ARRAY;
private rawClass: NgClassSupportedTypes;
private stateMap = new Map<string, CssClassState>();
constructor(
private _ngEl: ElementRef,
private _renderer: Renderer2,
) {}
@Input('class')
set klass(value: string) {
this.initialClasses = value != null ? value.trim().split(WS_REGEXP) : EMPTY_ARRAY;
}
@Input('ngClass')
set ngClass(value: string | string[] | Set<string> | {[klass: string]: any} | null | undefined) {
this.rawClass = typeof value === 'string' ? value.trim().split(WS_REGEXP) : value;
}
/*
The NgClass directive uses the custom change detection algorithm for its inputs. The custom
algorithm is necessary since inputs are represented as complex object or arrays that need to be
deeply-compared.
This algorithm is perf-sensitive since NgClass is used very frequently and its poor performance
might negatively impact runtime performance of the entire change detection cycle. The design of
this algorithm is making sure that:
- there is no unnecessary DOM manipulation (CSS classes are added / removed from the DOM only when
needed), even if references to bound objects change;
- there is no memory allocation if nothing changes (even relatively modest memory allocation
during the change detection cycle can result in GC pauses for some of the CD cycles).
The algorithm works by iterating over the set of bound classes, staring with [class] binding and
then going over [ngClass] binding. For each CSS class name:
- check if it was seen before (this information is tracked in the state map) and if its value
changed;
- mark it as "touched" - names that are not marked are not present in the latest set of binding
and we can remove such class name from the internal data structures;
After iteration over all the CSS class names we've got data structure with all the information
necessary to synchronize changes to the DOM - it is enough to iterate over the state map, flush
changes to the DOM and reset internal data structures so those are ready for the next change
detection cycle.
*/
ngDoCheck(): void {
// classes from the [class] binding
for (const klass of this.initialClasses) {
this._updateState(klass, true);
}
// classes from the [ngClass] binding
const rawClass = this.rawClass;
if (Array.isArray(rawClass) || rawClass instanceof Set) {
for (const klass of rawClass) {
this._updateState(klass, true);
}
} else if (rawClass != null) {
for (const klass of Object.keys(rawClass)) {
this._updateState(klass, Boolean(rawClass[klass]));
}
}
this._applyStateDiff();
}
private _updateState(klass: string, nextEnabled: boolean) {
const state = this.stateMap.get(klass);
if (state !== undefined) {
if (state.enabled !== nextEnabled) {
state.changed = true;
state.enabled = nextEnabled;
}
state.touched = true;
} else {
this.stateMap.set(klass, {enabled: nextEnabled, changed: true, touched: true});
}
}
private _applyStateDiff() {
for (const stateEntry of this.stateMap) {
const klass = stateEntry[0];
const state = stateEntry[1];
if (state.changed) {
this._toggleClass(klass, state.enabled);
state.changed = false;
} else if (!state.touched) {
// A class that was previously active got removed from the new collection of classes -
// remove from the DOM as well.
if (state.enabled) {
this._toggleClass(klass, false);
}
this.stateMap.delete(klass);
}
state.touched = false;
}
}
private _toggleClass(klass: string, enabled: boolean): void {
if (ngDevMode) {
if (typeof klass !== 'string') {
throw new Error(
`NgClass can only toggle CSS classes expressed as strings, got ${stringify(klass)}`,
);
}
}
klass = klass.trim();
if (klass.length > 0) {
klass.split(WS_REGEXP).forEach((klass) => {
if (enabled) {
this._renderer.addClass(this._ngEl.nativeElement, klass);
} else {
this._renderer.removeClass(this._ngEl.nativeElement, klass);
}
});
}
}
}
| |
012385
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
EmbeddedViewRef,
Injector,
Input,
OnChanges,
SimpleChange,
SimpleChanges,
TemplateRef,
ViewContainerRef,
} from '@angular/core';
/**
* @ngModule CommonModule
*
* @description
*
* Inserts an embedded view from a prepared `TemplateRef`.
*
* You can attach a context object to the `EmbeddedViewRef` by setting `[ngTemplateOutletContext]`.
* `[ngTemplateOutletContext]` should be an object, the object's keys will be available for binding
* by the local template `let` declarations.
*
* @usageNotes
* ```
* <ng-container *ngTemplateOutlet="templateRefExp; context: contextExp"></ng-container>
* ```
*
* Using the key `$implicit` in the context object will set its value as default.
*
* ### Example
*
* {@example common/ngTemplateOutlet/ts/module.ts region='NgTemplateOutlet'}
*
* @publicApi
*/
@Directive({
selector: '[ngTemplateOutlet]',
standalone: true,
})
export class NgTemplateOutlet<C = unknown> implements OnChanges {
private _viewRef: EmbeddedViewRef<C> | null = null;
/**
* A context object to attach to the {@link EmbeddedViewRef}. This should be an
* object, the object's keys will be available for binding by the local template `let`
* declarations.
* Using the key `$implicit` in the context object will set its value as default.
*/
@Input() public ngTemplateOutletContext: C | null = null;
/**
* A string defining the template reference and optionally the context object for the template.
*/
@Input() public ngTemplateOutlet: TemplateRef<C> | null = null;
/** Injector to be used within the embedded view. */
@Input() public ngTemplateOutletInjector: Injector | null = null;
constructor(private _viewContainerRef: ViewContainerRef) {}
ngOnChanges(changes: SimpleChanges) {
if (this._shouldRecreateView(changes)) {
const viewContainerRef = this._viewContainerRef;
if (this._viewRef) {
viewContainerRef.remove(viewContainerRef.indexOf(this._viewRef));
}
// If there is no outlet, clear the destroyed view ref.
if (!this.ngTemplateOutlet) {
this._viewRef = null;
return;
}
// Create a context forward `Proxy` that will always bind to the user-specified context,
// without having to destroy and re-create views whenever the context changes.
const viewContext = this._createContextForwardProxy();
this._viewRef = viewContainerRef.createEmbeddedView(this.ngTemplateOutlet, viewContext, {
injector: this.ngTemplateOutletInjector ?? undefined,
});
}
}
/**
* We need to re-create existing embedded view if either is true:
* - the outlet changed.
* - the injector changed.
*/
private _shouldRecreateView(changes: SimpleChanges): boolean {
return !!changes['ngTemplateOutlet'] || !!changes['ngTemplateOutletInjector'];
}
/**
* For a given outlet instance, we create a proxy object that delegates
* to the user-specified context. This allows changing, or swapping out
* the context object completely without having to destroy/re-create the view.
*/
private _createContextForwardProxy(): C {
return <C>new Proxy(
{},
{
set: (_target, prop, newValue) => {
if (!this.ngTemplateOutletContext) {
return false;
}
return Reflect.set(this.ngTemplateOutletContext, prop, newValue);
},
get: (_target, prop, receiver) => {
if (!this.ngTemplateOutletContext) {
return undefined;
}
return Reflect.get(this.ngTemplateOutletContext, prop, receiver);
},
},
);
}
}
| |
012396
|
ptimizedImage implements OnInit, OnChanges, OnDestroy {
private imageLoader = inject(IMAGE_LOADER);
private config: ImageConfig = processConfig(inject(IMAGE_CONFIG));
private renderer = inject(Renderer2);
private imgElement: HTMLImageElement = inject(ElementRef).nativeElement;
private injector = inject(Injector);
private readonly isServer = isPlatformServer(inject(PLATFORM_ID));
private readonly preloadLinkCreator = inject(PreloadLinkCreator);
// a LCP image observer - should be injected only in the dev mode
private lcpObserver = ngDevMode ? this.injector.get(LCPImageObserver) : null;
/**
* Calculate the rewritten `src` once and store it.
* This is needed to avoid repetitive calculations and make sure the directive cleanup in the
* `ngOnDestroy` does not rely on the `IMAGE_LOADER` logic (which in turn can rely on some other
* instance that might be already destroyed).
*/
private _renderedSrc: string | null = null;
/**
* Name of the source image.
* Image name will be processed by the image loader and the final URL will be applied as the `src`
* property of the image.
*/
@Input({required: true, transform: unwrapSafeUrl}) ngSrc!: string;
/**
* A comma separated list of width or density descriptors.
* The image name will be taken from `ngSrc` and combined with the list of width or density
* descriptors to generate the final `srcset` property of the image.
*
* Example:
* ```
* <img ngSrc="hello.jpg" ngSrcset="100w, 200w" /> =>
* <img src="path/hello.jpg" srcset="path/hello.jpg?w=100 100w, path/hello.jpg?w=200 200w" />
* ```
*/
@Input() ngSrcset!: string;
/**
* The base `sizes` attribute passed through to the `<img>` element.
* Providing sizes causes the image to create an automatic responsive srcset.
*/
@Input() sizes?: string;
/**
* For responsive images: the intrinsic width of the image in pixels.
* For fixed size images: the desired rendered width of the image in pixels.
*/
@Input({transform: numberAttribute}) width: number | undefined;
/**
* For responsive images: the intrinsic height of the image in pixels.
* For fixed size images: the desired rendered height of the image in pixels.
*/
@Input({transform: numberAttribute}) height: number | undefined;
/**
* The desired loading behavior (lazy, eager, or auto). Defaults to `lazy`,
* which is recommended for most images.
*
* Warning: Setting images as loading="eager" or loading="auto" marks them
* as non-priority images and can hurt loading performance. For images which
* may be the LCP element, use the `priority` attribute instead of `loading`.
*/
@Input() loading?: 'lazy' | 'eager' | 'auto';
/**
* Indicates whether this image should have a high priority.
*/
@Input({transform: booleanAttribute}) priority = false;
/**
* Data to pass through to custom loaders.
*/
@Input() loaderParams?: {[key: string]: any};
/**
* Disables automatic srcset generation for this image.
*/
@Input({transform: booleanAttribute}) disableOptimizedSrcset = false;
/**
* Sets the image to "fill mode", which eliminates the height/width requirement and adds
* styles such that the image fills its containing element.
*/
@Input({transform: booleanAttribute}) fill = false;
/**
* A URL or data URL for an image to be used as a placeholder while this image loads.
*/
@Input({transform: booleanOrUrlAttribute}) placeholder?: string | boolean;
/**
* Configuration object for placeholder settings. Options:
* * blur: Setting this to false disables the automatic CSS blur.
*/
@Input() placeholderConfig?: ImagePlaceholderConfig;
/**
* Value of the `src` attribute if set on the host `<img>` element.
* This input is exclusively read to assert that `src` is not set in conflict
* with `ngSrc` and that images don't start to load until a lazy loading strategy is set.
* @internal
*/
@Input() src?: string;
/**
* Value of the `srcset` attribute if set on the host `<img>` element.
* This input is exclusively read to assert that `srcset` is not set in conflict
* with `ngSrcset` and that images don't start to load until a lazy loading strategy is set.
* @internal
*/
@Input() srcset?: string;
/** @nodoc */
ngOnInit() {
performanceMarkFeature('NgOptimizedImage');
if (ngDevMode) {
const ngZone = this.injector.get(NgZone);
assertNonEmptyInput(this, 'ngSrc', this.ngSrc);
assertValidNgSrcset(this, this.ngSrcset);
assertNoConflictingSrc(this);
if (this.ngSrcset) {
assertNoConflictingSrcset(this);
}
assertNotBase64Image(this);
assertNotBlobUrl(this);
if (this.fill) {
assertEmptyWidthAndHeight(this);
// This leaves the Angular zone to avoid triggering unnecessary change detection cycles when
// `load` tasks are invoked on images.
ngZone.runOutsideAngular(() =>
assertNonZeroRenderedHeight(this, this.imgElement, this.renderer),
);
} else {
assertNonEmptyWidthAndHeight(this);
if (this.height !== undefined) {
assertGreaterThanZero(this, this.height, 'height');
}
if (this.width !== undefined) {
assertGreaterThanZero(this, this.width, 'width');
}
// Only check for distorted images when not in fill mode, where
// images may be intentionally stretched, cropped or letterboxed.
ngZone.runOutsideAngular(() =>
assertNoImageDistortion(this, this.imgElement, this.renderer),
);
}
assertValidLoadingInput(this);
if (!this.ngSrcset) {
assertNoComplexSizes(this);
}
assertValidPlaceholder(this, this.imageLoader);
assertNotMissingBuiltInLoader(this.ngSrc, this.imageLoader);
assertNoNgSrcsetWithoutLoader(this, this.imageLoader);
assertNoLoaderParamsWithoutLoader(this, this.imageLoader);
if (this.lcpObserver !== null) {
const ngZone = this.injector.get(NgZone);
ngZone.runOutsideAngular(() => {
this.lcpObserver!.registerImage(this.getRewrittenSrc(), this.ngSrc, this.priority);
});
}
if (this.priority) {
const checker = this.injector.get(PreconnectLinkChecker);
checker.assertPreconnect(this.getRewrittenSrc(), this.ngSrc);
if (!this.isServer) {
const applicationRef = this.injector.get(ApplicationRef);
assetPriorityCountBelowThreshold(applicationRef);
}
}
}
if (this.placeholder) {
this.removePlaceholderOnLoad(this.imgElement);
}
this.setHostAttributes();
}
private setHostAttributes() {
// Must set width/height explicitly in case they are bound (in which case they will
// only be reflected and not found by the browser)
if (this.fill) {
this.sizes ||= '100vw';
} else {
this.setHostAttribute('width', this.width!.toString());
this.setHostAttribute('height', this.height!.toString());
}
this.setHostAttribute('loading', this.getLoadingBehavior());
this.setHostAttribute('fetchpriority', this.getFetchPriority());
// The `data-ng-img` attribute flags an image as using the directive, to allow
// for analysis of the directive's performance.
this.setHostAttribute('ng-img', 'true');
// The `src` and `srcset` attributes should be set last since other attributes
// could affect the image's loading behavior.
const rewrittenSrcset = this.updateSrcAndSrcset();
if (this.sizes) {
if (this.getLoadingBehavior() === 'lazy') {
this.setHostAttribute('sizes', 'auto, ' + this.sizes);
} else {
this.setHostAttribute('sizes', this.sizes);
}
} else {
if (
this.ngSrcset &&
VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset) &&
this.getLoadingBehavior() === 'lazy'
) {
this.setHostAttribute('sizes', 'auto, 100vw');
}
}
if (this.isServer && this.priority) {
this.preloadLinkCreator.createPreloadLinkTag(
this.renderer,
this.getRewrittenSrc(),
rewrittenSrcset,
this.sizes,
);
}
}
/** @nodoc */
ngOnCh
| |
012419
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ChangeDetectorRef,
EventEmitter,
OnDestroy,
Pipe,
PipeTransform,
untracked,
ɵisPromise,
ɵisSubscribable,
} from '@angular/core';
import {Observable, Subscribable, Unsubscribable} from 'rxjs';
import {invalidPipeArgumentError} from './invalid_pipe_argument_error';
interface SubscriptionStrategy {
createSubscription(
async: Subscribable<any> | Promise<any>,
updateLatestValue: any,
): Unsubscribable | Promise<any>;
dispose(subscription: Unsubscribable | Promise<any>): void;
}
class SubscribableStrategy implements SubscriptionStrategy {
createSubscription(async: Subscribable<any>, updateLatestValue: any): Unsubscribable {
// Subscription can be side-effectful, and we don't want any signal reads which happen in the
// side effect of the subscription to be tracked by a component's template when that
// subscription is triggered via the async pipe. So we wrap the subscription in `untracked` to
// decouple from the current reactive context.
//
// `untracked` also prevents signal _writes_ which happen in the subscription side effect from
// being treated as signal writes during the template evaluation (which throws errors).
return untracked(() =>
async.subscribe({
next: updateLatestValue,
error: (e: any) => {
throw e;
},
}),
);
}
dispose(subscription: Unsubscribable): void {
// See the comment in `createSubscription` above on the use of `untracked`.
untracked(() => subscription.unsubscribe());
}
}
class PromiseStrategy implements SubscriptionStrategy {
createSubscription(async: Promise<any>, updateLatestValue: (v: any) => any): Promise<any> {
return async.then(updateLatestValue, (e) => {
throw e;
});
}
dispose(subscription: Promise<any>): void {}
}
const _promiseStrategy = new PromiseStrategy();
const _subscribableStrategy = new SubscribableStrategy();
/**
* @ngModule CommonModule
* @description
*
* Unwraps a value from an asynchronous primitive.
*
* The `async` pipe subscribes to an `Observable` or `Promise` and returns the latest value it has
* emitted. When a new value is emitted, the `async` pipe marks the component to be checked for
* changes. When the component gets destroyed, the `async` pipe unsubscribes automatically to avoid
* potential memory leaks. When the reference of the expression changes, the `async` pipe
* automatically unsubscribes from the old `Observable` or `Promise` and subscribes to the new one.
*
* @usageNotes
*
* ### Examples
*
* This example binds a `Promise` to the view. Clicking the `Resolve` button resolves the
* promise.
*
* {@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'}
*
* It's also possible to use `async` with Observables. The example below binds the `time` Observable
* to the view. The Observable continuously updates the view with the current time.
*
* {@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'}
*
* @publicApi
*/
@Pipe({
name: 'async',
pure: false,
standalone: true,
})
export class AsyncPipe implements OnDestroy, PipeTransform {
private _ref: ChangeDetectorRef | null;
private _latestValue: any = null;
private markForCheckOnValueUpdate = true;
private _subscription: Unsubscribable | Promise<any> | null = null;
private _obj: Subscribable<any> | Promise<any> | EventEmitter<any> | null = null;
private _strategy: SubscriptionStrategy | null = null;
constructor(ref: ChangeDetectorRef) {
// Assign `ref` into `this._ref` manually instead of declaring `_ref` in the constructor
// parameter list, as the type of `this._ref` includes `null` unlike the type of `ref`.
this._ref = ref;
}
ngOnDestroy(): void {
if (this._subscription) {
this._dispose();
}
// Clear the `ChangeDetectorRef` and its association with the view data, to mitigate
// potential memory leaks in Observables that could otherwise cause the view data to
// be retained.
// https://github.com/angular/angular/issues/17624
this._ref = null;
}
// NOTE(@benlesh): Because Observable has deprecated a few call patterns for `subscribe`,
// TypeScript has a hard time matching Observable to Subscribable, for more information
// see https://github.com/microsoft/TypeScript/issues/43643
transform<T>(obj: Observable<T> | Subscribable<T> | Promise<T>): T | null;
transform<T>(obj: null | undefined): null;
transform<T>(obj: Observable<T> | Subscribable<T> | Promise<T> | null | undefined): T | null;
transform<T>(obj: Observable<T> | Subscribable<T> | Promise<T> | null | undefined): T | null {
if (!this._obj) {
if (obj) {
try {
// Only call `markForCheck` if the value is updated asynchronously.
// Synchronous updates _during_ subscription should not wastefully mark for check -
// this value is already going to be returned from the transform function.
this.markForCheckOnValueUpdate = false;
this._subscribe(obj);
} finally {
this.markForCheckOnValueUpdate = true;
}
}
return this._latestValue;
}
if (obj !== this._obj) {
this._dispose();
return this.transform(obj);
}
return this._latestValue;
}
private _subscribe(obj: Subscribable<any> | Promise<any> | EventEmitter<any>): void {
this._obj = obj;
this._strategy = this._selectStrategy(obj);
this._subscription = this._strategy.createSubscription(obj, (value: Object) =>
this._updateLatestValue(obj, value),
);
}
private _selectStrategy(
obj: Subscribable<any> | Promise<any> | EventEmitter<any>,
): SubscriptionStrategy {
if (ɵisPromise(obj)) {
return _promiseStrategy;
}
if (ɵisSubscribable(obj)) {
return _subscribableStrategy;
}
throw invalidPipeArgumentError(AsyncPipe, obj);
}
private _dispose(): void {
// Note: `dispose` is only called if a subscription has been initialized before, indicating
// that `this._strategy` is also available.
this._strategy!.dispose(this._subscription!);
this._latestValue = null;
this._subscription = null;
this._obj = null;
}
private _updateLatestValue(async: any, value: Object): void {
if (async === this._obj) {
this._latestValue = value;
if (this.markForCheckOnValueUpdate) {
this._ref?.markForCheck();
}
}
}
}
| |
012499
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Angular Examples</title>
<base href="/" />
<!-- Prevent the browser from requesting any favicon. This could throw off the console
output checks. -->
<link rel="icon" href="data:," />
</head>
<body>
<example-app>Loading...</example-app>
<script src="/app_bundle.js"></script>
</body>
</html>
| |
012541
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/* tslint:disable:no-console */
// #docregion Component
import {Component} from '@angular/core';
import {FormArray, FormControl, FormGroup} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div formArrayName="cities">
<div *ngFor="let city of cities.controls; index as i">
<input [formControlName]="i" placeholder="City" />
</div>
</div>
<button>Submit</button>
</form>
<button (click)="addCity()">Add City</button>
<button (click)="setPreset()">Set preset</button>
`,
standalone: false,
})
export class NestedFormArray {
form = new FormGroup({
cities: new FormArray([new FormControl('SF'), new FormControl('NY')]),
});
get cities(): FormArray {
return this.form.get('cities') as FormArray;
}
addCity() {
this.cities.push(new FormControl());
}
onSubmit() {
console.log(this.cities.value); // ['SF', 'NY']
console.log(this.form.value); // { cities: ['SF', 'NY'] }
}
setPreset() {
this.cities.patchValue(['LA', 'MTV']);
}
}
// #enddocregion
| |
012558
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {BrowserModule} from '@angular/platform-browser';
import {SimpleFormComp} from './simple_form_example';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [SimpleFormComp],
bootstrap: [SimpleFormComp],
})
export class AppModule {}
export {SimpleFormComp as AppComponent};
| |
012569
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
inject,
InjectFlags,
InjectionToken,
InjectOptions,
Injector,
ProviderToken,
ɵInjectorProfilerContext,
ɵsetCurrentInjector as setCurrentInjector,
ɵsetInjectorProfilerContext,
} from '@angular/core';
class MockRootScopeInjector implements Injector {
constructor(readonly parent: Injector) {}
get<T>(
token: ProviderToken<T>,
defaultValue?: any,
flags: InjectFlags | InjectOptions = InjectFlags.Default,
): T {
if ((token as any).ɵprov && (token as any).ɵprov.providedIn === 'root') {
const old = setCurrentInjector(this);
const previousInjectorProfilerContext = ɵsetInjectorProfilerContext({
injector: this,
token: null,
});
try {
return (token as any).ɵprov.factory();
} finally {
setCurrentInjector(old);
ɵsetInjectorProfilerContext(previousInjectorProfilerContext);
}
}
return this.parent.get(token, defaultValue, flags);
}
}
{
describe('injector metadata examples', () => {
it('works', () => {
// #docregion Injector
const injector: Injector = Injector.create({
providers: [{provide: 'validToken', useValue: 'Value'}],
});
expect(injector.get('validToken')).toEqual('Value');
expect(() => injector.get('invalidToken')).toThrowError();
expect(injector.get('invalidToken', 'notFound')).toEqual('notFound');
// #enddocregion
});
it('injects injector', () => {
// #docregion injectInjector
const injector = Injector.create({providers: []});
expect(injector.get(Injector)).toBe(injector);
// #enddocregion
});
it('should infer type', () => {
// #docregion InjectionToken
const BASE_URL = new InjectionToken<string>('BaseUrl');
const injector = Injector.create({
providers: [{provide: BASE_URL, useValue: 'http://localhost'}],
});
const url = injector.get(BASE_URL);
// Note: since `BASE_URL` is `InjectionToken<string>`
// `url` is correctly inferred to be `string`
expect(url).toBe('http://localhost');
// #enddocregion
});
it('injects a tree-shakeable InjectionToken', () => {
class MyDep {}
const injector = new MockRootScopeInjector(
Injector.create({providers: [{provide: MyDep, deps: []}]}),
);
// #docregion ShakableInjectionToken
class MyService {
constructor(readonly myDep: MyDep) {}
}
const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', {
providedIn: 'root',
factory: () => new MyService(inject(MyDep)),
});
const instance = injector.get(MY_SERVICE_TOKEN);
expect(instance instanceof MyService).toBeTruthy();
expect(instance.myDep instanceof MyDep).toBeTruthy();
// #enddocregion
});
});
}
| |
012607
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
AfterContentChecked,
AfterContentInit,
AfterViewChecked,
AfterViewInit,
Component,
DoCheck,
Input,
OnChanges,
OnDestroy,
OnInit,
SimpleChanges,
Type,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
(function () {
describe('lifecycle hooks examples', () => {
it('should work with ngOnInit', () => {
// #docregion OnInit
@Component({
selector: 'my-cmp',
template: `...`,
standalone: false,
})
class MyComponent implements OnInit {
ngOnInit() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngOnInit', []]]);
});
it('should work with ngDoCheck', () => {
// #docregion DoCheck
@Component({
selector: 'my-cmp',
template: `...`,
standalone: false,
})
class MyComponent implements DoCheck {
ngDoCheck() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngDoCheck', []]]);
});
it('should work with ngAfterContentChecked', () => {
// #docregion AfterContentChecked
@Component({
selector: 'my-cmp',
template: `...`,
standalone: false,
})
class MyComponent implements AfterContentChecked {
ngAfterContentChecked() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterContentChecked', []]]);
});
it('should work with ngAfterContentInit', () => {
// #docregion AfterContentInit
@Component({
selector: 'my-cmp',
template: `...`,
standalone: false,
})
class MyComponent implements AfterContentInit {
ngAfterContentInit() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterContentInit', []]]);
});
it('should work with ngAfterViewChecked', () => {
// #docregion AfterViewChecked
@Component({
selector: 'my-cmp',
template: `...`,
standalone: false,
})
class MyComponent implements AfterViewChecked {
ngAfterViewChecked() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterViewChecked', []]]);
});
it('should work with ngAfterViewInit', () => {
// #docregion AfterViewInit
@Component({
selector: 'my-cmp',
template: `...`,
standalone: false,
})
class MyComponent implements AfterViewInit {
ngAfterViewInit() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterViewInit', []]]);
});
it('should work with ngOnDestroy', () => {
// #docregion OnDestroy
@Component({
selector: 'my-cmp',
template: `...`,
standalone: false,
})
class MyComponent implements OnDestroy {
ngOnDestroy() {
// ...
}
}
// #enddocregion
expect(createAndLogComponent(MyComponent)).toEqual([['ngOnDestroy', []]]);
});
it('should work with ngOnChanges', () => {
// #docregion OnChanges
@Component({
selector: 'my-cmp',
template: `...`,
standalone: false,
})
class MyComponent implements OnChanges {
@Input() prop: number = 0;
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
}
// #enddocregion
const log = createAndLogComponent(MyComponent, ['prop']);
expect(log.length).toBe(1);
expect(log[0][0]).toBe('ngOnChanges');
const changes: SimpleChanges = log[0][1][0];
expect(changes['prop'].currentValue).toBe(true);
});
});
function createAndLogComponent(clazz: Type<any>, inputs: string[] = []): any[] {
const log: any[] = [];
createLoggingSpiesFromProto(clazz, log);
const inputBindings = inputs.map((input) => `[${input}] = true`).join(' ');
@Component({
template: `<my-cmp ${inputBindings}></my-cmp>`,
standalone: false,
})
class ParentComponent {}
const fixture = TestBed.configureTestingModule({
declarations: [ParentComponent, clazz],
}).createComponent(ParentComponent);
fixture.detectChanges();
fixture.destroy();
return log;
}
function createLoggingSpiesFromProto(clazz: Type<any>, log: any[]) {
const proto = clazz.prototype;
// For ES2015+ classes, members are not enumerable in the prototype.
Object.getOwnPropertyNames(proto).forEach((method) => {
if (method === 'constructor') {
return;
}
proto[method] = (...args: any[]) => {
log.push([method, args]);
};
});
}
})();
| |
012617
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
Injectable,
Injector,
Input,
NgModule,
OnInit,
TemplateRef,
ViewChild,
ViewContainerRef,
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
// #docregion SimpleExample
@Component({
selector: 'hello-world',
template: 'Hello World!',
standalone: false,
})
export class HelloWorld {}
@Component({
selector: 'ng-component-outlet-simple-example',
template: `<ng-container *ngComponentOutlet="HelloWorld"></ng-container>`,
standalone: false,
})
export class NgComponentOutletSimpleExample {
// This field is necessary to expose HelloWorld to the template.
HelloWorld = HelloWorld;
}
// #enddocregion
// #docregion CompleteExample
@Injectable()
export class Greeter {
suffix = '!';
}
@Component({
selector: 'complete-component',
template: `{{ label }}: <ng-content></ng-content> <ng-content></ng-content>{{ greeter.suffix }}`,
standalone: false,
})
export class CompleteComponent {
@Input() label!: string;
constructor(public greeter: Greeter) {}
}
@Component({
selector: 'ng-component-outlet-complete-example',
template: ` <ng-template #ahoj>Ahoj</ng-template>
<ng-template #svet>Svet</ng-template>
<ng-container
*ngComponentOutlet="
CompleteComponent;
inputs: myInputs;
injector: myInjector;
content: myContent
"
></ng-container>`,
standalone: false,
})
export class NgComponentOutletCompleteExample implements OnInit {
// This field is necessary to expose CompleteComponent to the template.
CompleteComponent = CompleteComponent;
myInputs = {'label': 'Complete'};
myInjector: Injector;
@ViewChild('ahoj', {static: true}) ahojTemplateRef!: TemplateRef<any>;
@ViewChild('svet', {static: true}) svetTemplateRef!: TemplateRef<any>;
myContent?: any[][];
constructor(
injector: Injector,
private vcr: ViewContainerRef,
) {
this.myInjector = Injector.create({
providers: [{provide: Greeter, deps: []}],
parent: injector,
});
}
ngOnInit() {
// Create the projectable content from the templates
this.myContent = [
this.vcr.createEmbeddedView(this.ahojTemplateRef).rootNodes,
this.vcr.createEmbeddedView(this.svetTemplateRef).rootNodes,
];
}
}
// #enddocregion
@Component({
selector: 'example-app',
template: `<ng-component-outlet-simple-example></ng-component-outlet-simple-example>
<hr />
<ng-component-outlet-complete-example></ng-component-outlet-complete-example>`,
standalone: false,
})
export class AppComponent {}
@NgModule({
imports: [BrowserModule],
declarations: [
AppComponent,
NgComponentOutletSimpleExample,
NgComponentOutletCompleteExample,
HelloWorld,
CompleteComponent,
],
})
export class AppModule {}
| |
012660
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// #docregion activated-route
import {Component, NgModule} from '@angular/core';
// #enddocregion activated-route
import {BrowserModule} from '@angular/platform-browser';
// #docregion activated-route
import {ActivatedRoute, RouterModule} from '@angular/router';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
// #enddocregion activated-route
// #docregion activated-route
@Component({
// #enddocregion activated-route
selector: 'example-app',
template: '...',
standalone: false,
})
export class ActivatedRouteComponent {
constructor(route: ActivatedRoute) {
const id: Observable<string> = route.params.pipe(map((p) => p['id']));
const url: Observable<string> = route.url.pipe(map((segments) => segments.join('')));
// route.data includes both `data` and `resolve`
const user = route.data.pipe(map((d) => d['user']));
}
}
// #enddocregion activated-route
@NgModule({
imports: [BrowserModule, RouterModule.forRoot([])],
declarations: [ActivatedRouteComponent],
bootstrap: [ActivatedRouteComponent],
})
export class AppModule {}
| |
012818
|
# DESIGN DOC (Ivy): Separate Compilation
AUTHOR: chuckj@
## Background
### Angular 5 (Renderer2)
In 5.0 and prior versions of Angular the compiler performs whole program
analysis and generates template and injector definitions that use
this global knowledge to flatten injector scope definitions, inline
directives into the component, pre-calculate queries, pre-calculate
content projection, etc. This global knowledge requires that module and
component factories are generated as the final global step when compiling
a module. If any of the transitive information changed, then all factories
need to be regenerated.
Separate component and module compilation is supported only at the module
definition level and only from the source. That is, npm packages must contain
the metadata necessary to generate the factories. They cannot contain,
themselves, the generated factories. This is because if any of their
dependencies change, their factories would be invalid, preventing them from
using version ranges in their dependencies. To support producing factories
from compiled source (already translated by TypeScript into JavaScript)
libraries include metadata that describe the content of the Angular
decorators.
This document refers to this style of code generation as Renderer2 (after the
name of the renderer class it uses at runtime).
### Angular Ivy
In Ivy, the runtime is crafted in a way that allows for separate compilation
by performing at runtime much of what was previously pre-calculated by
the compiler. This allows the definition of components to change without
requiring modules and components that depend on them to be recompiled.
The mental model of Ivy is that the decorator is the compiler. That is,
the decorator can be thought of as parameters to a class transformer that
transforms the class by generating definitions based on the decorator
parameters. A `@Component` decorator transforms the class by adding
an `ɵcmp` static property, `@Directive` adds `ɵdir`,
`@Pipe` adds `ɵpipe`, etc. In most cases the values supplied to the
decorator are sufficient to generate the definition. However, in the case of
interpreting the template, the compiler needs to know the selector defined for
each component, directive and pipe that are in the scope of the template. The
purpose of this document is to define the information that is needed by the
compiler, and how that information is serialized to be discovered and
used by subsequent calls to `ngc`.
This document refers to this style of code generation as Ivy (after the code
name of the project to create it). It would be more consistent to refer to it
as Renderer3, but that looks too similar to Renderer2.
## Information needed
The information available across compilations in Angular 5 is represented in
the compiler by a summary description. For example, components and directives
are represented by the [`CompileDirectiveSummary`](https://github.com/angular/angular/blob/d3827a0017fd5ff5ac0f6de8a19692ce47bf91b4/packages/compiler/src/compile_metadata.ts#L257).
The following table shows where this information ends up in an ivy compiled
class:
### `CompileDirectiveSummary`
| field | destination |
|---------------------|-----------------------|
| `type` | implicit |
| `isComponent` | `ɵcmp` |
| `selector` | `ngModuleScope` |
| `exportAs` | `ɵdir` |
| `inputs` | `ɵdir` |
| `outputs` | `ɵdir` |
| `hostListeners` | `ɵdir` |
| `hostProperties` | `ɵdir` |
| `hostAttributes` | `ɵdir` |
| `providers` | `ɵinj` |
| `viewProviders` | `ɵcmp` |
| `queries` | `ɵdir` |
| `guards` | not used |
| `viewQueries` | `ɵcmp` |
| `changeDetection` | `ɵcmp` |
| `template` | `ɵcmp` |
| `componentViewType` | not used |
| `renderType` | not used |
| `componentFactory` | not used |
Only one definition is generated per class. All components are directives so a
`ɵcmp` contains all the `ɵdir` information. All directives
are injectable so `ɵcmp` and `ɵdir` contain `ɵprov`
information.
For `CompilePipeSummary` the table looks like:
#### `CompilePipeSummary`
| field | destination |
|---------------------|-----------------------|
| `type` | implicit |
| `name` | `ngModuleScope` |
| `pure` | `ɵpipe` |
The only pieces of information that are not generated into the definition are
the directive selector and the pipe name as they go into the module scope.
The information needed to build an `ngModuleScope` needs to be communicated
from the directive and pipe to the module that declares them.
## Metadata
### Angul
| |
012822
|
# DESIGN DOC(Ivy): Compiler Architecture
AUTHOR: arick@, chuckj@
Status: Draft
## Overview
This document details the new architecture of the Angular compiler in a post-Ivy world, as well as the compatibility functionality needed for the ecosystem to gradually migrate to Ivy without breaking changes. This compatibility ensures Ivy and non-Ivy libraries can coexist during the migration period.
### The Ivy Compilation Model
Broadly speaking, The Ivy model is that Angular decorators (`@Injectable`, etc) are compiled to static properties on the classes (`ɵprov`). This operation must take place without global program knowledge, and in most cases only with knowledge of that single decorator.
The one exception is `@Component`, which requires knowledge of the metadata from the `@NgModule` which declares the component in order to properly generate the component def (`ɵcmp`). In particular, the selectors which are applicable during compilation of a component template are determined by the module that declares that component, and the transitive closure of the exports of that module's imports.
Going forward, this will be the model by which Angular code will be compiled, shipped to NPM, and eventually bundled into applications.
### Existing code on NPM
Existing Angular libraries exist on NPM today and are distributed in the Angular Package Format, which details the artifacts shipped. Today this includes compiled `.js` files in both ES2015 and ESM (ES5 + ES2015 modules) flavors, `.d.ts` files, and `.metadata.json` files. The `.js` files have the Angular decorator information removed, and the `.metadata.json` files preserve the decorator metadata in an alternate format.
### High Level Proposal
We will produce two compiler entry-points, `ngtsc` and `ngcc`.
`ngtsc` will be a Typescript-to-Javascript transpiler that reifies Angular decorators into static properties. It is a minimal wrapper around `tsc` which includes a set of Angular transforms. While Ivy is experimental, `ngc` operates as `ngtsc` when the `angularCompilerOption` `enableIvy` flag is set to `true` in the `tsconfig.json` file for the project.
`ngcc` (which stands for Angular compatibility compiler) is designed to process code coming from NPM and produce the equivalent Ivy version, as if the code was compiled with `ngtsc`. It will operate given a `node_modules` directory and a set of packages to compile, and will produce an equivalent directory from which the Ivy equivalents of those modules can be read. `ngcc` is a separate script entry point to `@angular/compiler-cli`.
`ngcc` can also be run as part of a code loader (e.g. for Webpack) to transpile packages being read from `node_modules` on-demand.
##
| |
012823
|
Detailed Design
### Ivy Compilation Model
The overall architecture of `ngtsc` it is a set of transformers that adjust what is emitted by TypeScript for a TypeScript program. Angular transforms both the `.js` files and the `.d.ts` files to reflect the content of Angular decorators that are then erased. This transformation is done file by file with no global knowledge except during the type-checking and for reference inversion discussed below.
For example, the following class declaration:
```ts
import {Component, Input} from '@angular/core';
@Component({
selector: 'greet',
template: '<div> Hello, {{name}}! </div>'
})
export class GreetComponent {
@Input() name: string;
}
```
will normally be translated into something like this:
```js
const tslib_1 = require("tslib");
const core_1 = require("@angular/core");
let GreetComponent = class GreetComponent {
};
tslib_1.__decorate([
core_1.Input(),
tslib_1.__metadata("design:type", String)
], GreetComponent.prototype, "name", void 0);
GreetComponent = tslib_1.__decorate([
core_1.Component({
selector: 'greet',
template: '<div> Hello, {{name}}! </div>'
})
], GreetComponent);
```
which translates the decorator into a form that is executed at runtime. A `.d.ts` file is also emitted that might look something like
```ts
export class GreetComponent {
name: string;
}
```
In `ngtsc` this is instead emitted as,
```js
const i0 = require("@angular/core");
class GreetComponent {}
GreetComponent.ɵcmp = i0.ɵɵdefineComponent({
type: GreetComponent,
tag: 'greet',
factory: () => new GreetComponent(),
template: function (rf, ctx) {
if (rf & RenderFlags.Create) {
i0.ɵɵelementStart(0, 'div');
i0.ɵɵtext(1);
i0.ɵɵelementEnd();
}
if (rf & RenderFlags.Update) {
i0.ɵɵadvance();
i0.ɵɵtextInterpolate1('Hello ', ctx.name, '!');
}
}
});
```
and the `.d.ts` contains:
```ts
import * as i0 from '@angular/core';
export class GreetComponent {
static ɵcmp: i0.NgComponentDef<
GreetComponent,
'greet',
{input: 'input'}
>;
}
```
The information needed by reference inversion and type-checking is included in
the type declaration of the `ɵcmp` in the `.d.ts`.
#### TypeScript architecture
The overall architecture of TypeScript is:
|------------|
|----------------------------------> | TypeScript |
| | .d.ts |
| |------------|
|
|------------| |-----| |-----| |------------|
| TypeScript | -parse-> | AST | ->transform-> | AST | ->print-> | JavaScript |
| source | | |-----| | |-----| | source |
|------------| | | | |------------|
| type-check |
| | |
| v |
| |--------| |
|--> | errors | <---|
|--------|
The parse step is a traditional recursive descent parser, augmented to support incremental parsing, that emits an abstract syntax tree (AST).
The type-checker construct a symbol table and then performs type analysis of every expression in the file, reporting errors it finds. This process is not extended or modified by `ngtsc`.
The transform step is a set of AST to AST transformations that perform various tasks such as, removing type declarations, lowering module and class declarations to ES5, converting `async` methods to state-machines, etc.
#### Extension points
TypeScript supports the following extension points to alter its output. You can,
1. Modify the TypeScript source it sees (`CompilerHost.getSourceFile`)
2. Alter the list of transforms (`CustomTransformers`)
3. Intercept the output before it is written (`WriteFileCallback`)
It is not recommended to alter the source code as this complicates the managing of source maps, makes it difficult to support incremental parsing, and is not supported by TypeScript's language service plug-in model.
#### Angular Extensions
Angular transforms the `.js` output by adding Angular specific transforms to the list of transforms executed by TypeScript.
As of TypeScript 2.7, there is no similar transformer pipe-line for `.d.ts` files so the .d.ts files will be altered during the `WriteFileCallback`.
#### Decorator Reification
Angular supports the following class decorators:
- `@Component`
- `@Directive`
- `@Injectable`
- `@NgModule`
- `@Pipe`
There are also a list of helper decorators that make the `@Component` and `@Directive` easier to use such as `@Input`, `@Output`, etc.; as well as a set of decorators that help `@Injectable` classes customize the injector such as `@Inject` and `@SkipSelf`.
Each of the class decorators can be thought of as class transformers that take the declared class and transform it, possibly using information from the helper decorators, to produce an Angular class. The JIT compiler performs this transformation at runtime. The AOT compiler performs this transformation at compile time.
Each of the class decorators' class transformer creates a corresponding static member on the class that describes to the runtime how to use the class. For example, the `@Component` decorator creates a `ɵcmp` static member, `@Directive` create a `ɵdir`, etc. Internally, these class transformers are called a "Compiler". Most of the compilers are straight forward translations of the metadata specified in the decorator to the information provided in the corresponding definition and, therefore, do not require anything outside the source file to perform the conversion. However, the component, during production builds and for type checking a template require the module scope of the component which requires information from other files in the program.
#### Compiler design
Each "Compiler" which transforms a single decorator into a static field will operate as a "pure function". Given input metadata about a particular type and decorator, it will produce an object describing the field to be added to the type, as well as the initializer value for that field (in Output AST format).
A Compiler must not depend on any inputs not directly passed to it (for example, it must not scan sources or metadata for other symbols). This restriction is important for two reasons:
1. It helps to enforce the Ivy locality principle, since all inputs to the Compiler will be visible.
2. It protects against incorrect builds during `--watch` mode, since the dependencies between files will be easily traceable.
Compilers will also not take Typescript nodes directly as input, but will operate against information extracted from TS sources by the transformer. In addition to helping enforce the rules above, this restriction also enables Compilers to run at runtime during JIT mode.
For example, the input to the `@Component` compiler will be:
* A reference to the class of the component.
* The template and style resources of the component.
* The selector of the component.
* A selector map for the module to which the component belongs.
#### Need for static value resolution
During some parts of compilation, the compiler will need to statically interpret particular values in the AST, especially values from the decorator metadata. This is a complex problem. For example, while this form of a component is common:
```javascript
@Component({
selector: 'foo-cmp',
templateUrl: 'templates/foo.html',
})
export class Foo {}
```
The following is also permitted:
```javascript
export const TEMPLATE_BASE = 'templates/';
export function getTemplateUrl(cmp: string): string {
return TEMPLATE_BASE + cmp + '.html';
}
export const FOO_SELECTOR = 'foo-cmp';
export const FOO_TEMPLATE_URL = getTemplateUrl('foo');
@Component({
selector: FOO_SELECTOR,
templateUrl: FOO_TEMPLATE_URL,
})
export class Foo {}
```
`ngc` has a metadata system which attempts to statically understand the "value side" of a program. This allowed it to follow the references and evaluate the expressions required to understand that `FOO_TEMPLATE_URL` evaluates statically to `templates/foo.html`. `ngtsc` will need a similar capability, though the design will be different.
The `ngtsc` metadata evaluator will be built as a partial Typescript interpreter, which visits Typescript nodes and evaluates expressions statically. This allows metadata evaluation to happen on demand. It will have some restrictions that aren't present in the `ngc` model - in particular, evaluation will not cross `node_module` boundaries.
#### Compiling a te
| |
012826
|
ty compiler
#### The compatibility problem
Not all Angular code is compiled at the same time. Applications have dependencies on shared libraries, and those libraries are published on NPM in their compiled form and not as Typescript source code. Even if an application is built using `ngtsc`, its dependencies may not have been.
If a particular library was not compiled with `ngtsc`, it does not have reified decorator properties in its `.js` distribution as described above. Linking it against a dependency that was not compiled in the same way will fail at runtime.
#### Converting pre-Ivy code
Since Ivy code can only be linked against other Ivy code, to build the application all pre-Ivy dependencies from NPM must be converted to Ivy dependencies. This transformation must happen as a precursor to running `ngtsc` on the application, and future compilation and linking operations need to be made against this transformed version of the dependencies.
It is possible to transpile non-Ivy code in the Angular Package Format (v6) into Ivy code, even though the `.js` files no longer contain the decorator information. This works because the Angular Package Format includes `.metadata.json` files for each `.js` file. These metadata files contain information that was present in the Typescript source but was removed during transpilation to Javascript, and this information is sufficient to generate patched `.js` files which add the Ivy static properties to decorated classes.
#### Metadata from APF
The `.metadata.json` files currently being shipped to NPM includes, among other information, the arguments to the Angular decorators which `ngtsc` downlevels to static properties. For example, the `.metadata.json` file for `CommonModule` contains the information for its `NgModule` decorator which was originally present in the Typescript source:
```json
"CommonModule": {
"__symbolic": "class",
"decorators": [{
"__symbolic": "call",
"expression": {
"__symbolic": "reference",
"module": "@angular/core",
"name": "NgModule",
"line": 22,
"character": 1
},
"arguments": [{
"declarations": [...],
"exports": [...],
"providers": [...]
}]
}]
}
```
#### ngcc operation
`ngcc` will by default scan `node_modules` and produce Ivy-compatible versions of every package it discovers built using Angular Package Format (APF). It detects the APF by looking for the presence of a `.metadata.json` file alongside the package's `module` entrypoint.
Alternatively, `ngcc` can be initiated by passing the name of a single NPM package. It will begin converting that package, and recurse into any dependencies of that package that it discovers which have not yet been converted.
The output of `ngcc` is a directory called `ngcc_node_modules` by default, but can be renamed based on an option. Its structure mirrors that of `node_modules`, and the packages that are converted have the non-transpiled files copied verbatim - `package.json`, etc are all preserved in the output. Only the `.js` and `.d.ts` files are changed, and the `.metadata.json` files are removed.
An example directory layout would be:
```
# input
node_modules/
ng-dep/
package.json
index.js (pre-ivy)
index.d.ts (pre-ivy)
index.metadata.json
other.js
# output
ngcc_node_modules
ng-dep/
package.json
index.js (ivy compatible)
index.d.ts (ivy-compatible)
other.js (copied verbatim)
```
#### Operation as a loader
`ngcc` can be called as a standalone entrypoint, but it can also be integrated into the dependency loading operation of a bundler such as Rollup or Webpack. In this mode, the `ngcc` API can be used to read a file originally in `node_modules`. If the file is from a package which has not yet been converted, `ngcc` will convert the package and its dependencies before returning the file's contents.
In this mode, the on-disk `ngcc_node_modules` directory functions as a cache. If the file being requested has previously been converted, its contents will be read from `ngcc_node_modules`.
#### Compilation Model
`ngtsc` operates using a pipeline of different transformations, each one processing a different Angular decorator and converting it into a static property on the type being decorated. `ngcc` is architected to reuse as much of that process as possible.
Compiling a package in `ngcc` involves the following steps:
1. Parse the JS files of the package with the Typescript parser.
2. Invoke the `StaticReflector` system from the legacy `@angular/compiler` to parse the `.metadata.json` files.
3. Run through each Angular decorator in the Ivy system and compile:
1. Use the JS AST plus the information from the `StaticReflector` to construct the input to the annotation's Compiler.
2. Run the annotation's Compiler which will produce a partial class and its type declaration.
3. Extract the static property definition from the partial class.
4. Combine the compiler outputs with the JS AST to produce the resulting `.js` and `.d.ts` files, and write them to disk.
5. Copy over all other files.
#### Merging with JS output
At first glance it is desirable for each Compiler's output to be patched into the AST for the modules being compiled, and then to generate the resulting JS code and sourcemaps using Typescript's emit on the AST. This is undesirable for several reasons:
* The round-trip through the Typescript parser and emitter might subtly change the input JS code - dropping comments, reformatting code, etc. This is not ideal, as users expect the input code to remain as unchanged as possible.
* It isn't possible in Typescript to directly emit without going through any of Typescript's own transformations. This may cause expressions to be reformatted, code to be downleveled, and requires configuration of an output module system into which the code will be transformed.
For these reasons, `ngcc` will not use the TS emitter to produce the final patched `.js` files. Instead, the JS text will be manipulated directly, with the help of the `magic-string` or similar library to ensure the changes are reflected in the output sourcemaps. The AST which is parsed from the JS files contains position information of all the types in the JS source, and this information can be used to determine the correct insertion points for the Ivy static fields.
Similarly, the `.d.ts` files will be parsed by the TS parser, and the information used to determine the insertion points of typing information that needs to be added to individual types (as well as associated imports).
##### Module systems
The Angular Package Format includes more than one copy of a package's code. At minimum, it includes one ESM5 (ES5 code in ES Modules) entrypoint, one ES2015 entrypoint, and one UMD entrypoint. Some libraries _not_ following the package format may still work in the Angular CLI, if they export code that can be loaded by Webpack.
Thus, `ngcc` will have two approaches for dealing with packages on NPM.
1. APF Path: libraries following the Angular package format will have their source code updated to contain Ivy definitions. This ensures tree-shaking will work properly.
2. Compatibility Path: libraries where `ngcc` cannot determine how to safely modify the existing code will have a patching operation applied. This patching operation produces a "wrapper" file for each file containing an Angular entity, which re-exports patched versions of the Angular entities. This is not compatible with tree-shaking, but will work for libraries which `ngcc` cannot otherwise understand. A warning will be printed to notify the user they should update the version of the library if possible.
For example, if a library ships with commonjs-only code or a UMD bundle that `ngcc` isn't able to patch directly, it can generate patching wrappers instead of modifying the input code.
### Language Service
The `@angular/language-service` is mostly out of scope for this document, and will be treated in a separate design document. However, it's worth a consideration here as the architecture of the compiler impacts the language service's design.
A Language Service is an analysis engine that integrates into an IDE such as Visual Studio Code. It processes code and provides static analysis information regarding that code, as well as enables specific IDE operations such as code completion, tracing of references, and refactoring. The `@angular/language-service` is a wrapper around the Typescript language service (much as `ngtsc` wraps `tsc`) and extends the analysis of Typescript with a specific understanding of Angular concepts. In particular, it also understands the Angular Template Syntax and can bridge between the component class in Typescript and expressions in the templates.
To provide code completion and other intelligence around template contents, the Angular Language Service must have a similar understanding of the template contents as the `ngtsc` compiler - it must know the selector map associated with the component, and the metadata of each directive or pipe used in the template. Whether the language service consumes the output of `ngcc` or reuses its metadata transformation logic, the data it needs will be available.
| |
012876
|
describe('for loop blocks', () => {
it('should parse a for loop block', () => {
expectFromHtml(`
@for (item of items.foo.bar; track item.id) {
{{ item }}
} @empty {
There were no items in the list.
}
`).toEqual([
['ForLoopBlock', 'items.foo.bar', 'item.id'],
['Variable', 'item', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['BoundText', ' {{ item }} '],
['ForLoopBlockEmpty'],
['Text', ' There were no items in the list. '],
]);
});
it('should parse a for loop block with optional parentheses', () => {
expectFromHtml(`
@for ((item of items.foo.bar); track item.id){
{{ item }}
}
`).toEqual([
['ForLoopBlock', 'items.foo.bar', 'item.id'],
['Variable', 'item', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['BoundText', ' {{ item }} '],
]);
expectFromHtml(`
@for ((item of items.foo.bar()); track item.id) {
{{ item }}
}
`).toEqual([
['ForLoopBlock', 'items.foo.bar()', 'item.id'],
['Variable', 'item', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['BoundText', ' {{ item }} '],
]);
expectFromHtml(`
@for (( ( (item of items.foo.bar()) ) ); track item.id) {
{{ item }}
}
`).toEqual([
['ForLoopBlock', 'items.foo.bar()', 'item.id'],
['Variable', 'item', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['BoundText', ' {{ item }} '],
]);
});
it('should parse a for loop block with let parameters', () => {
expectFromHtml(`
@for (item of items.foo.bar; track item.id; let idx = $index, f = $first, c = $count; let l = $last, ev = $even, od = $odd) {
{{ item }}
}
`).toEqual([
['ForLoopBlock', 'items.foo.bar', 'item.id'],
['Variable', 'item', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['Variable', 'idx', '$index'],
['Variable', 'f', '$first'],
['Variable', 'c', '$count'],
['Variable', 'l', '$last'],
['Variable', 'ev', '$even'],
['Variable', 'od', '$odd'],
['BoundText', ' {{ item }} '],
]);
});
it('should parse a for loop block with newlines in its let parameters', () => {
expectFromHtml(`
@for (item of items.foo.bar; track item.id; let\nidx = $index,\nf = $first,\nc = $count,\nl = $last,\nev = $even,\nod = $odd) {
{{ item }}
}
`).toEqual([
['ForLoopBlock', 'items.foo.bar', 'item.id'],
['Variable', 'item', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['Variable', 'idx', '$index'],
['Variable', 'f', '$first'],
['Variable', 'c', '$count'],
['Variable', 'l', '$last'],
['Variable', 'ev', '$even'],
['Variable', 'od', '$odd'],
['BoundText', ' {{ item }} '],
]);
});
it('should parse nested for loop blocks', () => {
expectFromHtml(`
@for (item of items.foo.bar; track item.id) {
{{ item }}
<div>
@for (subitem of item.items; track subitem.id) {<h1>{{subitem}}</h1>}
</div>
} @empty {
There were no items in the list.
}
`).toEqual([
['ForLoopBlock', 'items.foo.bar', 'item.id'],
['Variable', 'item', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['BoundText', ' {{ item }} '],
['Element', 'div'],
['ForLoopBlock', 'item.items', 'subitem.id'],
['Variable', 'subitem', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['Element', 'h1'],
['BoundText', '{{ subitem }}'],
['ForLoopBlockEmpty'],
['Text', ' There were no items in the list. '],
]);
});
it('should parse a for loop block with a function call in the `track` expression', () => {
expectFromHtml(`
@for (item of items.foo.bar; track trackBy(item.id, 123)) {
{{ item }}
}
`).toEqual([
['ForLoopBlock', 'items.foo.bar', 'trackBy(item.id, 123)'],
['Variable', 'item', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['BoundText', ' {{ item }} '],
]);
});
it('should parse a for loop block with newlines in its expression', () => {
const expectedResult = [
['ForLoopBlock', 'items.foo.bar', 'item.id + foo'],
['Variable', 'item', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['BoundText', '{{ item }}'],
];
expectFromHtml(`
@for (item\nof\nitems.foo.bar; track item.id +\nfoo) {{{ item }}}
`).toEqual(expectedResult);
expectFromHtml(`
@for ((item\nof\nitems.foo.bar); track (item.id +\nfoo)) {{{ item }}}
`).toEqual(expectedResult);
});
it('should parse for loop block expression containing new lines', () => {
expectFromHtml(`
@for (item of [
{ id: 1 },
{ id: 2 }
]; track item.id) {
{{ item }}
}
`).toEqual([
['ForLoopBlock', '[{id: 1}, {id: 2}]', 'item.id'],
['Variable', 'item', '$implicit'],
['Variable', '$index', '$index'],
['Variable', '$first', '$first'],
['Variable', '$last', '$last'],
['Variable', '$even', '$even'],
['Variable', '$odd', '$odd'],
['Variable', '$count', '$count'],
['BoundText', ' {{ item }} '],
]);
});
| |
012877
|
describe('validations', () => {
it('should report if for loop does not have an expression', () => {
expect(() => parse(`@for {hello}`)).toThrowError(/@for loop does not have an expression/);
});
it('should report if for loop does not have a tracking expression', () => {
expect(() => parse(`@for (a of b) {hello}`)).toThrowError(
/@for loop must have a "track" expression/,
);
expect(() => parse(`@for (a of b; track ) {hello}`)).toThrowError(
/@for loop must have a "track" expression/,
);
});
it('should report mismatching optional parentheses around for loop expression', () => {
expect(() => parse(`@for ((a of b; track c) {hello}`)).toThrowError(
/Unclosed parentheses in expression/,
);
expect(() => parse(`@for ((a of b(); track c) {hello}`)).toThrowError(
/Unexpected end of expression: b\(/,
);
expect(() => parse(`@for (a of b); track c) {hello}`)).toThrowError(
/Unexpected character "EOF"/,
);
});
it('should report unrecognized for loop parameters', () => {
expect(() => parse(`@for (a of b; foo bar) {hello}`)).toThrowError(
/Unrecognized @for loop paramater "foo bar"/,
);
});
it('should report multiple `track` parameters', () => {
expect(() => parse(`@for (a of b; track c; track d) {hello}`)).toThrowError(
/@for loop can only have one "track" expression/,
);
});
it('should report invalid for loop expression', () => {
const errorPattern =
/Cannot parse expression\. @for loop expression must match the pattern "<identifier> of <expression>"/;
expect(() => parse(`@for (//invalid of items) {hello}`)).toThrowError(errorPattern);
expect(() => parse(`@for (item) {hello}`)).toThrowError(errorPattern);
expect(() => parse(`@for (item in items) {hello}`)).toThrowError(errorPattern);
expect(() => parse(`@for (item of ) {hello}`)).toThrowError(errorPattern);
});
it('should report syntax error in for loop expression', () => {
expect(() => parse(`@for (item of items..foo) {hello}`)).toThrowError(
/Unexpected token \./,
);
});
it('should report for loop with multiple `empty` blocks', () => {
expect(() =>
parse(`
@for (a of b; track a) {
Main
} @empty {
Empty one
} @empty {
Empty two
}
`),
).toThrowError(/@for loop can only have one @empty block/);
});
it('should report empty block with parameters', () => {
expect(() =>
parse(`
@for (a of b; track a) {
main
} @empty (foo) {
empty
}
`),
).toThrowError(/@empty block cannot have parameters/);
});
it('should content between @for and @empty blocks', () => {
expect(() =>
parse(`
@for (a of b; track a) {
main
} <div></div> @empty {
empty
}
`),
).toThrowError(/@empty block can only be used after an @for block/);
});
it('should report an empty block used without a @for loop block', () => {
expect(() => parse(`@empty {hello}`)).toThrowError(
/@empty block can only be used after an @for block/,
);
});
it('should report an empty `let` parameter', () => {
expect(() => parse(`@for (item of items.foo.bar; track item.id; let ) {}`)).toThrowError(
/Invalid @for loop "let" parameter. Parameter should match the pattern "<name> = <variable name>"/,
);
});
it('should report an invalid `let` parameter', () => {
expect(() =>
parse(`@for (item of items.foo.bar; track item.id; let i = $index, $odd) {}`),
).toThrowError(
/Invalid @for loop "let" parameter\. Parameter should match the pattern "<name> = <variable name>"/,
);
});
it('should an unknown variable in a `let` parameter', () => {
expect(() =>
parse(`@for (item of items.foo.bar; track item.id; let foo = $foo) {}`),
).toThrowError(/Unknown "let" parameter variable "\$foo"\. The allowed variables are:/);
});
it('should report duplicate `let` parameter variables', () => {
expect(() =>
parse(
`@for (item of items.foo.bar; track item.id; let i = $index, f = $first, i = $index) {}`,
),
).toThrowError(/Duplicate "let" parameter variable "\$index"/);
expect(() =>
parse(`@for (item of items.foo.bar; track item.id; let $index = $index) {}`),
).toThrowError(/Duplicate "let" parameter variable "\$index"/);
});
it('should report an item name that conflicts with the implicit context variables', () => {
['$index', '$count', '$first', '$last', '$even', '$odd'].forEach((varName) => {
expect(() => parse(`@for (${varName} of items; track $index) {}`)).toThrowError(
/@for loop item name cannot be one of \$index, \$first, \$last, \$even, \$odd, \$count/,
);
});
});
it('should report a context variable alias that is the same as the variable name', () => {
expect(() =>
parse(`@for (item of items; let item = $index; track $index) {}`),
).toThrowError(/Invalid @for loop "let" parameter. Variable cannot be called "item"/);
});
});
});
| |
013202
|
export function createSwitchBlock(
ast: html.Block,
visitor: html.Visitor,
bindingParser: BindingParser,
): {node: t.SwitchBlock | null; errors: ParseError[]} {
const errors = validateSwitchBlock(ast);
const primaryExpression =
ast.parameters.length > 0
? parseBlockParameterToBinding(ast.parameters[0], bindingParser)
: bindingParser.parseBinding('', false, ast.sourceSpan, 0);
const cases: t.SwitchBlockCase[] = [];
const unknownBlocks: t.UnknownBlock[] = [];
let defaultCase: t.SwitchBlockCase | null = null;
// Here we assume that all the blocks are valid given that we validated them above.
for (const node of ast.children) {
if (!(node instanceof html.Block)) {
continue;
}
if ((node.name !== 'case' || node.parameters.length === 0) && node.name !== 'default') {
unknownBlocks.push(new t.UnknownBlock(node.name, node.sourceSpan, node.nameSpan));
continue;
}
const expression =
node.name === 'case' ? parseBlockParameterToBinding(node.parameters[0], bindingParser) : null;
const ast = new t.SwitchBlockCase(
expression,
html.visitAll(visitor, node.children, node.children),
node.sourceSpan,
node.startSourceSpan,
node.endSourceSpan,
node.nameSpan,
node.i18n,
);
if (expression === null) {
defaultCase = ast;
} else {
cases.push(ast);
}
}
// Ensure that the default case is last in the array.
if (defaultCase !== null) {
cases.push(defaultCase);
}
return {
node: new t.SwitchBlock(
primaryExpression,
cases,
unknownBlocks,
ast.sourceSpan,
ast.startSourceSpan,
ast.endSourceSpan,
ast.nameSpan,
),
errors,
};
}
/** Parses the parameters of a `for` loop block. */
function parseForLoopParameters(
block: html.Block,
errors: ParseError[],
bindingParser: BindingParser,
) {
if (block.parameters.length === 0) {
errors.push(new ParseError(block.startSourceSpan, '@for loop does not have an expression'));
return null;
}
const [expressionParam, ...secondaryParams] = block.parameters;
const match = stripOptionalParentheses(expressionParam, errors)?.match(
FOR_LOOP_EXPRESSION_PATTERN,
);
if (!match || match[2].trim().length === 0) {
errors.push(
new ParseError(
expressionParam.sourceSpan,
'Cannot parse expression. @for loop expression must match the pattern "<identifier> of <expression>"',
),
);
return null;
}
const [, itemName, rawExpression] = match;
if (ALLOWED_FOR_LOOP_LET_VARIABLES.has(itemName)) {
errors.push(
new ParseError(
expressionParam.sourceSpan,
`@for loop item name cannot be one of ${Array.from(ALLOWED_FOR_LOOP_LET_VARIABLES).join(
', ',
)}.`,
),
);
}
// `expressionParam.expression` contains the variable declaration and the expression of the
// for...of statement, i.e. 'user of users' The variable of a ForOfStatement is _only_ the "const
// user" part and does not include "of x".
const variableName = expressionParam.expression.split(' ')[0];
const variableSpan = new ParseSourceSpan(
expressionParam.sourceSpan.start,
expressionParam.sourceSpan.start.moveBy(variableName.length),
);
const result = {
itemName: new t.Variable(itemName, '$implicit', variableSpan, variableSpan),
trackBy: null as {expression: ASTWithSource; keywordSpan: ParseSourceSpan} | null,
expression: parseBlockParameterToBinding(expressionParam, bindingParser, rawExpression),
context: Array.from(ALLOWED_FOR_LOOP_LET_VARIABLES, (variableName) => {
// Give ambiently-available context variables empty spans at the end of
// the start of the `for` block, since they are not explicitly defined.
const emptySpanAfterForBlockStart = new ParseSourceSpan(
block.startSourceSpan.end,
block.startSourceSpan.end,
);
return new t.Variable(
variableName,
variableName,
emptySpanAfterForBlockStart,
emptySpanAfterForBlockStart,
);
}),
};
for (const param of secondaryParams) {
const letMatch = param.expression.match(FOR_LOOP_LET_PATTERN);
if (letMatch !== null) {
const variablesSpan = new ParseSourceSpan(
param.sourceSpan.start.moveBy(letMatch[0].length - letMatch[1].length),
param.sourceSpan.end,
);
parseLetParameter(
param.sourceSpan,
letMatch[1],
variablesSpan,
itemName,
result.context,
errors,
);
continue;
}
const trackMatch = param.expression.match(FOR_LOOP_TRACK_PATTERN);
if (trackMatch !== null) {
if (result.trackBy !== null) {
errors.push(
new ParseError(param.sourceSpan, '@for loop can only have one "track" expression'),
);
} else {
const expression = parseBlockParameterToBinding(param, bindingParser, trackMatch[1]);
if (expression.ast instanceof EmptyExpr) {
errors.push(
new ParseError(block.startSourceSpan, '@for loop must have a "track" expression'),
);
}
const keywordSpan = new ParseSourceSpan(
param.sourceSpan.start,
param.sourceSpan.start.moveBy('track'.length),
);
result.trackBy = {expression, keywordSpan};
}
continue;
}
errors.push(
new ParseError(param.sourceSpan, `Unrecognized @for loop paramater "${param.expression}"`),
);
}
return result;
}
/** Parses the `let` parameter of a `for` loop block. */
function parseLetParameter(
sourceSpan: ParseSourceSpan,
expression: string,
span: ParseSourceSpan,
loopItemName: string,
context: t.Variable[],
errors: ParseError[],
): void {
const parts = expression.split(',');
let startSpan = span.start;
for (const part of parts) {
const expressionParts = part.split('=');
const name = expressionParts.length === 2 ? expressionParts[0].trim() : '';
const variableName = expressionParts.length === 2 ? expressionParts[1].trim() : '';
if (name.length === 0 || variableName.length === 0) {
errors.push(
new ParseError(
sourceSpan,
`Invalid @for loop "let" parameter. Parameter should match the pattern "<name> = <variable name>"`,
),
);
} else if (!ALLOWED_FOR_LOOP_LET_VARIABLES.has(variableName)) {
errors.push(
new ParseError(
sourceSpan,
`Unknown "let" parameter variable "${variableName}". The allowed variables are: ${Array.from(
ALLOWED_FOR_LOOP_LET_VARIABLES,
).join(', ')}`,
),
);
} else if (name === loopItemName) {
errors.push(
new ParseError(
sourceSpan,
`Invalid @for loop "let" parameter. Variable cannot be called "${loopItemName}"`,
),
);
} else if (context.some((v) => v.name === name)) {
errors.push(
new ParseError(sourceSpan, `Duplicate "let" parameter variable "${variableName}"`),
);
} else {
const [, keyLeadingWhitespace, keyName] =
expressionParts[0].match(CHARACTERS_IN_SURROUNDING_WHITESPACE_PATTERN) ?? [];
const keySpan =
keyLeadingWhitespace !== undefined && expressionParts.length === 2
? new ParseSourceSpan(
/* strip leading spaces */
startSpan.moveBy(keyLeadingWhitespace.length),
/* advance to end of the variable name */
startSpan.moveBy(keyLeadingWhitespace.length + keyName.length),
)
: span;
let valueSpan: ParseSourceSpan | undefined = undefined;
if (expressionParts.length === 2) {
const [, valueLeadingWhitespace, implicit] =
expressionParts[1].match(CHARACTERS_IN_SURROUNDING_WHITESPACE_PATTERN) ?? [];
valueSpan =
valueLeadingWhitespace !== undefined
? new ParseSourceSpan(
startSpan.moveBy(expressionParts[0].length + 1 + valueLeadingWhitespace.length),
startSpan.moveBy(
expressionParts[0].length + 1 + valueLeadingWhitespace.length + implicit.length,
),
)
: undefined;
}
const sourceSpan = new ParseSourceSpan(keySpan.start, valueSpan?.end ?? keySpan.end);
context.push(new t.Variable(name, variableName, sourceSpan, keySpan, valueSpan));
}
startSpan = startSpan.moveBy(part.length + 1 /* add 1 to move past the comma */);
}
}
| |
013337
|
Implements a domain-specific language (DSL) for defining web animation sequences for HTML elements as
multiple transformations over time.
Use this API to define how an HTML element can move, change color, grow or shrink, fade, or slide off
the page. These changes can occur simultaneously or sequentially. You can control the timing of each
of these transformations. The function calls generate the data structures and metadata that enable Angular
to integrate animations into templates and run them based on application states.
Animation definitions are linked to components through the `{@link Component.animations animations}`
property in the `@Component` metadata, typically in the component file of the HTML element to be animated.
The `trigger()` function encapsulates a named animation, with all other function calls nested within. Use
the trigger name to bind the named animation to a specific triggering element in the HTML template.
Angular animations are based on CSS web transition functionality, so anything that can be styled or
transformed in CSS can be animated the same way in Angular. Angular animations allow you to:
* Set animation timings, styles, keyframes, and transitions.
* Animate HTML elements in complex sequences and choreographies.
* Animate HTML elements as they are inserted and removed from the DOM, including responsive real-time
filtering.
* Create reusable animations.
* Animate parent and child elements.
Additional animation functionality is provided in other Angular modules for animation testing, for
route-based animations, and for programmatic animation controls that allow an end user to fast forward
and reverse an animation sequence.
@see Find out more in the [animations guide](guide/animations).
@see See what polyfills you might need in the [browser support guide](reference/versions#browser-support).
| |
013544
|
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {isPlatformBrowser} from '@angular/common';
import {
APP_INITIALIZER,
ApplicationRef,
EnvironmentProviders,
InjectionToken,
Injector,
makeEnvironmentProviders,
NgZone,
PLATFORM_ID,
} from '@angular/core';
import {merge, from, Observable, of} from 'rxjs';
import {delay, take} from 'rxjs/operators';
import {NgswCommChannel} from './low_level';
import {SwPush} from './push';
import {SwUpdate} from './update';
export const SCRIPT = new InjectionToken<string>(ngDevMode ? 'NGSW_REGISTER_SCRIPT' : '');
export function ngswAppInitializer(
injector: Injector,
script: string,
options: SwRegistrationOptions,
platformId: string,
): Function {
return () => {
if (
!(isPlatformBrowser(platformId) && 'serviceWorker' in navigator && options.enabled !== false)
) {
return;
}
const ngZone = injector.get(NgZone);
const appRef = injector.get(ApplicationRef);
// Set up the `controllerchange` event listener outside of
// the Angular zone to avoid unnecessary change detections,
// as this event has no impact on view updates.
ngZone.runOutsideAngular(() => {
// Wait for service worker controller changes, and fire an INITIALIZE action when a new SW
// becomes active. This allows the SW to initialize itself even if there is no application
// traffic.
const sw = navigator.serviceWorker;
const onControllerChange = () => sw.controller?.postMessage({action: 'INITIALIZE'});
sw.addEventListener('controllerchange', onControllerChange);
appRef.onDestroy(() => {
sw.removeEventListener('controllerchange', onControllerChange);
});
});
let readyToRegister$: Observable<unknown>;
if (typeof options.registrationStrategy === 'function') {
readyToRegister$ = options.registrationStrategy();
} else {
const [strategy, ...args] = (
options.registrationStrategy || 'registerWhenStable:30000'
).split(':');
switch (strategy) {
case 'registerImmediately':
readyToRegister$ = of(null);
break;
case 'registerWithDelay':
readyToRegister$ = delayWithTimeout(+args[0] || 0);
break;
case 'registerWhenStable':
const whenStable$ = from(injector.get(ApplicationRef).whenStable());
readyToRegister$ = !args[0]
? whenStable$
: merge(whenStable$, delayWithTimeout(+args[0]));
break;
default:
// Unknown strategy.
throw new Error(
`Unknown ServiceWorker registration strategy: ${options.registrationStrategy}`,
);
}
}
// Don't return anything to avoid blocking the application until the SW is registered.
// Also, run outside the Angular zone to avoid preventing the app from stabilizing (especially
// given that some registration strategies wait for the app to stabilize).
// Catch and log the error if SW registration fails to avoid uncaught rejection warning.
ngZone.runOutsideAngular(() =>
readyToRegister$
.pipe(take(1))
.subscribe(() =>
navigator.serviceWorker
.register(script, {scope: options.scope})
.catch((err) => console.error('Service worker registration failed with:', err)),
),
);
};
}
function delayWithTimeout(timeout: number): Observable<unknown> {
return of(null).pipe(delay(timeout));
}
export function ngswCommChannelFactory(
opts: SwRegistrationOptions,
platformId: string,
): NgswCommChannel {
return new NgswCommChannel(
isPlatformBrowser(platformId) && opts.enabled !== false ? navigator.serviceWorker : undefined,
);
}
/**
* Token that can be used to provide options for `ServiceWorkerModule` outside of
* `ServiceWorkerModule.register()`.
*
* You can use this token to define a provider that generates the registration options at runtime,
* for example via a function call:
*
* {@example service-worker/registration-options/module.ts region="registration-options"
* header="app.module.ts"}
*
* @publicApi
*/
export abstract class SwRegistrationOptions {
/**
* Whether the ServiceWorker will be registered and the related services (such as `SwPush` and
* `SwUpdate`) will attempt to communicate and interact with it.
*
* Default: true
*/
enabled?: boolean;
/**
* A URL that defines the ServiceWorker's registration scope; that is, what range of URLs it can
* control. It will be used when calling
* [ServiceWorkerContainer#register()](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).
*/
scope?: string;
/**
* Defines the ServiceWorker registration strategy, which determines when it will be registered
* with the browser.
*
* The default behavior of registering once the application stabilizes (i.e. as soon as there are
* no pending micro- and macro-tasks) is designed to register the ServiceWorker as soon as
* possible but without affecting the application's first time load.
*
* Still, there might be cases where you want more control over when the ServiceWorker is
* registered (for example, there might be a long-running timeout or polling interval, preventing
* the app from stabilizing). The available option are:
*
* - `registerWhenStable:<timeout>`: Register as soon as the application stabilizes (no pending
* micro-/macro-tasks) but no later than `<timeout>` milliseconds. If the app hasn't
* stabilized after `<timeout>` milliseconds (for example, due to a recurrent asynchronous
* task), the ServiceWorker will be registered anyway.
* If `<timeout>` is omitted, the ServiceWorker will only be registered once the app
* stabilizes.
* - `registerImmediately`: Register immediately.
* - `registerWithDelay:<timeout>`: Register with a delay of `<timeout>` milliseconds. For
* example, use `registerWithDelay:5000` to register the ServiceWorker after 5 seconds. If
* `<timeout>` is omitted, is defaults to `0`, which will register the ServiceWorker as soon
* as possible but still asynchronously, once all pending micro-tasks are completed.
* - An Observable factory function: A function that returns an `Observable`.
* The function will be used at runtime to obtain and subscribe to the `Observable` and the
* ServiceWorker will be registered as soon as the first value is emitted.
*
* Default: 'registerWhenStable:30000'
*/
registrationStrategy?: string | (() => Observable<unknown>);
}
/**
* @publicApi
*
* Sets up providers to register the given Angular Service Worker script.
*
* If `enabled` is set to `false` in the given options, the module will behave as if service
* workers are not supported by the browser, and the service worker will not be registered.
*
* Example usage:
* ```ts
* bootstrapApplication(AppComponent, {
* providers: [
* provideServiceWorker('ngsw-worker.js')
* ],
* });
* ```
*/
export function provideServiceWorker(
script: string,
options: SwRegistrationOptions = {},
): EnvironmentProviders {
return makeEnvironmentProviders([
SwPush,
SwUpdate,
{provide: SCRIPT, useValue: script},
{provide: SwRegistrationOptions, useValue: options},
{
provide: NgswCommChannel,
useFactory: ngswCommChannelFactory,
deps: [SwRegistrationOptions, PLATFORM_ID],
},
{
provide: APP_INITIALIZER,
useFactory: ngswAppInitializer,
deps: [Injector, SCRIPT, SwRegistrationOptions, PLATFORM_ID],
multi: true,
},
]);
}
| |
013581
|
### Error
By default, `zone.js/plugins/zone-error` will not be loaded for performance reasons.
This package provides the following functionality:
1. **Error Inheritance:** Handle the `extend Error` issue:
```ts
class MyError extends Error {}
const myError = new MyError();
console.log('is MyError instanceof Error', (myError instanceof Error));
```
Without the `zone-error` patch, the example above will output `false`. With the patch, the result will be `true`.
2. **ZoneJsInternalStackFrames:** Remove the zone.js stack from `stackTrace` and add `zone` information. Without this patch, many `zone.js` invocation stacks will be displayed in the stack frames.
```
at zone.run (polyfill.bundle.js: 3424)
at zoneDelegate.invokeTask (polyfill.bundle.js: 3424)
at zoneDelegate.runTask (polyfill.bundle.js: 3424)
at zone.drainMicroTaskQueue (polyfill.bundle.js: 3424)
at a.b.c (vendor.bundle.js: 12345 <angular>)
at d.e.f (main.bundle.js: 23456)
```
With this patch, those zone frames will be removed, and the zone information `<angular>/<root>` will be added.
```
at a.b.c (vendor.bundle.js: 12345 <angular>)
at d.e.f (main.bundle.js: 23456 <root>)
```
The second feature may slow down `Error` performance, so `zone.js` provides a flag that allows you to control this behavior.
The flag is `__Zone_Error_ZoneJsInternalStackFrames_policy`. The available options are:
1. **default:** This is the default setting. If you load `zone.js/plugins/zone-error` without setting the flag, `default` will be used. In this case, `ZoneJsInternalStackFrames` will be available when using `new Error()`, allowing you to obtain an `error.stack` that is zone-stack-free. However, this may slightly slow down the performance of new `Error()`.
2. **disable:** This option will disable the `ZoneJsInternalStackFrames` feature. If you load `zone.js/plugins/zone-error`, you will only receive a wrapped `Error`, which can handle the `Error` inheritance issue.
3. **lazy:** This feature allows you to access `ZoneJsInternalStackFrames` without impacting performance. However, as a trade-off, you won't be able to obtain the zone-free stack frames via `error.stack`. You can only access them through `error.zoneAwareStack`.
### Angular
Angular uses zone.js to manage asynchronous operations and determine when to perform change detection. Therefore, in Angular, the following APIs should be patched; otherwise, Angular may not work as expected:
1. ZoneAwarePromise
2. timer
3. on_property
4. EventTarget
5. XHR
| |
014005
|
Supports execution of Angular apps on different supported browsers.
The `BrowserModule` is included by default in any app created through the CLI,
and it re-exports the `CommonModule` and `ApplicationModule` exports,
making basic Angular functionality available to the app.
For more information, see [Browser Support](reference/versions#browser-support).
| |
014009
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DOCUMENT} from '@angular/common';
import {HttpClient, HttpTransferCacheOptions, provideHttpClient} from '@angular/common/http';
import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing';
import {
ApplicationRef,
Component,
Injectable,
PLATFORM_ID,
ɵSSR_CONTENT_INTEGRITY_MARKER as SSR_CONTENT_INTEGRITY_MARKER,
} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {withBody} from '@angular/private/testing';
import {BehaviorSubject} from 'rxjs';
import {provideClientHydration, withNoHttpTransferCache} from '../public_api';
import {withHttpTransferCacheOptions} from '../src/hydration';
describe('provideClientHydration', () => {
@Component({
selector: 'test-hydrate-app',
template: '',
standalone: false,
})
class SomeComponent {}
function makeRequestAndExpectOne(
url: string,
body: string,
options: HttpTransferCacheOptions | boolean = true,
): void {
TestBed.inject(HttpClient).get(url, {transferCache: options}).subscribe();
TestBed.inject(HttpTestingController).expectOne(url).flush(body);
}
function makeRequestAndExpectNone(
url: string,
options: HttpTransferCacheOptions | boolean = true,
): void {
TestBed.inject(HttpClient).get(url, {transferCache: options}).subscribe();
TestBed.inject(HttpTestingController).expectNone(url);
}
@Injectable()
class ApplicationRefPatched extends ApplicationRef {
override isStable = new BehaviorSubject<boolean>(false);
}
describe('default', () => {
beforeEach(
withBody(
`<!--${SSR_CONTENT_INTEGRITY_MARKER}--><test-hydrate-app></test-hydrate-app>`,
() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: 'server'},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
provideClientHydration(),
provideHttpClient(),
provideHttpClientTesting(),
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
},
),
);
it(`should use cached HTTP calls`, () => {
makeRequestAndExpectOne('/test-1', 'foo');
// Do the same call, this time it should served from cache.
makeRequestAndExpectNone('/test-1');
});
});
describe('withNoHttpTransferCache', () => {
beforeEach(
withBody(
`<!--${SSR_CONTENT_INTEGRITY_MARKER}--><test-hydrate-app></test-hydrate-app>`,
() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: 'server'},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
provideClientHydration(withNoHttpTransferCache()),
provideHttpClient(),
provideHttpClientTesting(),
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
},
),
);
it(`should not cache HTTP calls`, () => {
makeRequestAndExpectOne('/test-1', 'foo', false);
// Do the same call, this time should pass through as cache is disabled.
makeRequestAndExpectOne('/test-1', 'foo');
});
});
describe('withHttpTransferCacheOptions', () => {
beforeEach(
withBody(
`<!--${SSR_CONTENT_INTEGRITY_MARKER}--><test-hydrate-app></test-hydrate-app>`,
() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
declarations: [SomeComponent],
providers: [
{provide: PLATFORM_ID, useValue: 'server'},
{provide: DOCUMENT, useFactory: () => document},
{provide: ApplicationRef, useClass: ApplicationRefPatched},
provideClientHydration(
withHttpTransferCacheOptions({includePostRequests: true, includeHeaders: ['foo']}),
),
provideHttpClient(),
provideHttpClientTesting(),
],
});
const appRef = TestBed.inject(ApplicationRef);
appRef.bootstrap(SomeComponent);
},
),
);
it(`should cache HTTP POST calls`, () => {
const url = '/test-1';
const body = 'foo';
TestBed.inject(HttpClient).post(url, body).subscribe();
TestBed.inject(HttpTestingController).expectOne(url).flush(body);
TestBed.inject(HttpClient).post(url, body).subscribe();
TestBed.inject(HttpTestingController).expectNone(url);
});
});
});
| |
014020
|
escribe('with animations', () => {
@Component({
standalone: true,
selector: 'hello-app',
template:
'<div @myAnimation (@myAnimation.start)="onStart($event)">Hello from AnimationCmp!</div>',
animations: [
trigger('myAnimation', [transition('void => *', [style({opacity: 1}), animate(5)])]),
],
})
class AnimationCmp {
renderer = _inject(ANIMATION_MODULE_TYPE, {optional: true}) ?? 'not found';
startEvent?: {};
onStart(event: {}) {
this.startEvent = event;
}
}
it('should enable animations when using provideAnimations()', async () => {
const appRef = await bootstrapApplication(AnimationCmp, {
providers: [provideAnimations()],
});
const cmp = appRef.components[0].instance;
// Wait until animation is completed.
await new Promise((resolve) => setTimeout(resolve, 10));
expect(cmp.renderer).toBe('BrowserAnimations');
expect(cmp.startEvent.triggerName).toEqual('myAnimation');
expect(cmp.startEvent.phaseName).toEqual('start');
expect(el.innerText).toBe('Hello from AnimationCmp!');
});
it('should use noop animations renderer when using provideNoopAnimations()', async () => {
const appRef = await bootstrapApplication(AnimationCmp, {
providers: [provideNoopAnimations()],
});
const cmp = appRef.components[0].instance;
// Wait until animation is completed.
await new Promise((resolve) => setTimeout(resolve, 10));
expect(cmp.renderer).toBe('NoopAnimations');
expect(cmp.startEvent.triggerName).toEqual('myAnimation');
expect(cmp.startEvent.phaseName).toEqual('start');
expect(el.innerText).toBe('Hello from AnimationCmp!');
});
});
it('initializes modules inside the NgZone when using `provideZoneChangeDetection`', async () => {
let moduleInitialized = false;
@NgModule({})
class SomeModule {
constructor() {
expect(NgZone.isInAngularZone()).toBe(true);
moduleInitialized = true;
}
}
@Component({
template: '',
selector: 'hello-app',
imports: [SomeModule],
standalone: true,
})
class AnimationCmp {}
await bootstrapApplication(AnimationCmp, {
providers: [provideZoneChangeDetection({eventCoalescing: true})],
});
expect(moduleInitialized).toBe(true);
});
});
it('should throw if bootstrapped Directive is not a Component', (done) => {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
bootstrap(HelloRootDirectiveIsNotCmp, [{provide: ErrorHandler, useValue: errorHandler}]).catch(
(error: Error) => {
expect(error).toEqual(
new Error(`HelloRootDirectiveIsNotCmp cannot be used as an entry component.`),
);
done();
},
);
});
it('should have the TransferState token available in NgModule bootstrap', async () => {
let state: TransferState | undefined;
@Component({
selector: 'hello-app',
template: '...',
standalone: false,
})
class NonStandaloneComponent {
constructor() {
state = _inject(TransferState);
}
}
await bootstrap(NonStandaloneComponent);
expect(state).toBeInstanceOf(TransferState);
});
it('should retrieve sanitizer', inject([Injector], (injector: Injector) => {
const sanitizer: Sanitizer | null = injector.get(Sanitizer, null);
// We don't want to have sanitizer in DI. We use DI only to overwrite the
// sanitizer, but not for default one. The default one is pulled in by the Ivy
// instructions as needed.
expect(sanitizer).toBe(null);
}));
it('should throw if no element is found', (done) => {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
bootstrap(NonExistentComp, [{provide: ErrorHandler, useValue: errorHandler}]).then(
null,
(reason) => {
expect(reason.message).toContain('The selector "non-existent" did not match any elements');
done();
return null;
},
);
});
it('should throw if no provider', async () => {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
class IDontExist {}
@Component({
selector: 'cmp',
template: 'Cmp',
standalone: false,
})
class CustomCmp {
constructor(iDontExist: IDontExist) {}
}
@Component({
selector: 'hello-app',
template: '<cmp></cmp>',
standalone: false,
})
class RootCmp {}
@NgModule({declarations: [CustomCmp], exports: [CustomCmp]})
class CustomModule {}
await expectAsync(
bootstrap(RootCmp, [{provide: ErrorHandler, useValue: errorHandler}], [], [CustomModule]),
).toBeRejected();
});
if (getDOM().supportsDOMEvents) {
it('should forward the error to promise when bootstrap fails', (done) => {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
const refPromise = bootstrap(NonExistentComp, [
{provide: ErrorHandler, useValue: errorHandler},
]);
refPromise.then(null, (reason: any) => {
expect(reason.message).toContain('The selector "non-existent" did not match any elements');
done();
});
});
it('should invoke the default exception handler when bootstrap fails', (done) => {
const logger = new MockConsole();
const errorHandler = new ErrorHandler();
(errorHandler as any)._console = logger as any;
const refPromise = bootstrap(NonExistentComp, [
{provide: ErrorHandler, useValue: errorHandler},
]);
refPromise.then(null, (reason) => {
expect(logger.res[0].join('#')).toContain(
'ERROR#Error: NG05104: The selector "non-existent" did not match any elements',
);
done();
return null;
});
});
}
it('should create an injector promise', async () => {
const refPromise = bootstrap(HelloRootCmp, testProviders);
expect(refPromise).toEqual(jasmine.any(Promise));
await refPromise; // complete component initialization before switching to the next test
});
it('should set platform name to browser', (done) => {
const refPromise = bootstrap(HelloRootCmp, testProviders);
refPromise.then((ref) => {
expect(isPlatformBrowser(ref.injector.get(PLATFORM_ID))).toBe(true);
done();
}, done.fail);
});
it('should display hello world', (done) => {
const refPromise = bootstrap(HelloRootCmp, testProviders);
refPromise.then((ref) => {
expect(el).toHaveText('hello world!');
expect(el.getAttribute('ng-version')).toEqual(VERSION.full);
done();
}, done.fail);
});
it('should throw a descriptive error if BrowserModule is installed again via a lazily loaded module', (done) => {
@NgModule({imports: [BrowserModule]})
class AsyncModule {}
bootstrap(HelloRootCmp, testProviders)
.then((ref: ComponentRef<HelloRootCmp>) => {
const compiler: Compiler = ref.injector.get(Compiler);
return compiler.compileModuleAsync(AsyncModule).then((factory) => {
expect(() => factory.create(ref.injector)).toThrowError(
'NG05100: Providers from the `BrowserModule` have already been loaded. ' +
'If you need access to common directives such as NgIf and NgFor, ' +
'import the `CommonModule` instead.',
);
});
})
.then(
() => done(),
(err) => done.fail(err),
);
});
it('should support multiple calls to bootstrap', (done) => {
const refPromise1 = bootstrap(HelloRootCmp, testProviders);
const refPromise2 = bootstrap(HelloRootCmp2, testProviders);
Promise.all([refPromise1, refPromise2]).then((refs) => {
expect(el).toHaveText('hello world!');
expect(el2).toHaveText('hello world, again!');
done();
}, done.fail);
});
it('should not crash if change detection is invoked when the root component is disposed', (done) => {
bootstrap(HelloOnDestroyTickCmp, testProviders).then((ref) => {
expect(() => ref.destroy()).not.toThrow();
done();
});
});
| |
014023
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Component,
destroyPlatform,
ErrorHandler,
Inject,
Injectable,
InjectionToken,
NgModule,
NgZone,
PlatformRef,
} from '@angular/core';
import {R3Injector} from '@angular/core/src/di/r3_injector';
import {NoopNgZone} from '@angular/core/src/zone/ng_zone';
import {withBody} from '@angular/private/testing';
import {bootstrapApplication, BrowserModule} from '../../src/browser';
describe('bootstrapApplication for standalone components', () => {
beforeEach(destroyPlatform);
afterEach(destroyPlatform);
class SilentErrorHandler extends ErrorHandler {
override handleError() {
// the error is already re-thrown by the application ref.
// we don't want to print it, but instead catch it in tests.
}
}
it(
'should create injector where ambient providers shadow explicit providers',
withBody('<test-app></test-app>', async () => {
const testToken = new InjectionToken('test token');
@NgModule({
providers: [{provide: testToken, useValue: 'Ambient'}],
})
class AmbientModule {}
@Component({
selector: 'test-app',
standalone: true,
template: `({{testToken}})`,
imports: [AmbientModule],
})
class StandaloneCmp {
constructor(@Inject(testToken) readonly testToken: String) {}
}
const appRef = await bootstrapApplication(StandaloneCmp, {
providers: [{provide: testToken, useValue: 'Bootstrap'}],
});
appRef.tick();
// make sure that ambient providers "shadow" ones explicitly provided during bootstrap
expect(document.body.textContent).toBe('(Ambient)');
}),
);
it(
'should be able to provide a custom zone implementation in DI',
withBody('<test-app></test-app>', async () => {
@Component({
selector: 'test-app',
standalone: true,
template: ``,
})
class StandaloneCmp {}
class CustomZone extends NoopNgZone {}
const instance = new CustomZone();
const appRef = await bootstrapApplication(StandaloneCmp, {
providers: [{provide: NgZone, useValue: instance}],
});
appRef.tick();
expect(appRef.injector.get(NgZone)).toEqual(instance);
}),
);
/*
This test verifies that ambient providers for the standalone component being bootstrapped
(providers collected from the import graph of a standalone component) are instantiated in a
dedicated standalone injector. As the result we are ending up with the following injectors
hierarchy:
- platform injector (platform specific providers go here);
- application injector (providers specified in the bootstrap options go here);
- standalone injector (ambient providers go here);
*/
it(
'should create a standalone injector for standalone components with ambient providers',
withBody('<test-app></test-app>', async () => {
const ambientToken = new InjectionToken('ambient token');
@NgModule({
providers: [{provide: ambientToken, useValue: 'Only in AmbientNgModule'}],
})
class AmbientModule {}
@Injectable()
class NeedsAmbientProvider {
constructor(@Inject(ambientToken) readonly ambientToken: String) {}
}
@Component({
selector: 'test-app',
template: `({{service.ambientToken}})`,
standalone: true,
imports: [AmbientModule],
})
class StandaloneCmp {
constructor(readonly service: NeedsAmbientProvider) {}
}
try {
await bootstrapApplication(StandaloneCmp, {
providers: [{provide: ErrorHandler, useClass: SilentErrorHandler}, NeedsAmbientProvider],
});
// we expect the bootstrap process to fail since the "NeedsAmbientProvider" service
// (located in the application injector) can't "see" ambient providers (located in a
// standalone injector that is a child of the application injector).
fail('Expected to throw');
} catch (e: unknown) {
expect(e).toBeInstanceOf(Error);
expect((e as Error).message).toContain('No provider for InjectionToken ambient token!');
}
}),
);
it(
'should throw if `BrowserModule` is imported in the standalone bootstrap scenario',
withBody('<test-app></test-app>', async () => {
@Component({
selector: 'test-app',
template: '...',
standalone: true,
imports: [BrowserModule],
})
class StandaloneCmp {}
try {
await bootstrapApplication(StandaloneCmp, {
providers: [{provide: ErrorHandler, useClass: SilentErrorHandler}],
});
// The `bootstrapApplication` already includes the set of providers from the
// `BrowserModule`, so including the `BrowserModule` again will bring duplicate
// providers and we want to avoid it.
fail('Expected to throw');
} catch (e: unknown) {
expect(e).toBeInstanceOf(Error);
expect((e as Error).message).toContain(
'NG05100: Providers from the `BrowserModule` have already been loaded.',
);
}
}),
);
it(
'should throw if `BrowserModule` is imported indirectly in the standalone bootstrap scenario',
withBody('<test-app></test-app>', async () => {
@NgModule({
imports: [BrowserModule],
})
class SomeDependencyModule {}
@Component({
selector: 'test-app',
template: '...',
standalone: true,
imports: [SomeDependencyModule],
})
class StandaloneCmp {}
try {
await bootstrapApplication(StandaloneCmp, {
providers: [{provide: ErrorHandler, useClass: SilentErrorHandler}],
});
// The `bootstrapApplication` already includes the set of providers from the
// `BrowserModule`, so including the `BrowserModule` again will bring duplicate
// providers and we want to avoid it.
fail('Expected to throw');
} catch (e: unknown) {
expect(e).toBeInstanceOf(Error);
expect((e as Error).message).toContain(
'NG05100: Providers from the `BrowserModule` have already been loaded.',
);
}
}),
);
it(
'should trigger an app destroy when a platform is destroyed',
withBody('<test-app></test-app>', async () => {
let compOnDestroyCalled = false;
let serviceOnDestroyCalled = false;
let injectorOnDestroyCalled = false;
@Injectable({providedIn: 'root'})
class ServiceWithOnDestroy {
ngOnDestroy() {
serviceOnDestroyCalled = true;
}
}
@Component({
selector: 'test-app',
standalone: true,
template: 'Hello',
})
class ComponentWithOnDestroy {
constructor(service: ServiceWithOnDestroy) {}
ngOnDestroy() {
compOnDestroyCalled = true;
}
}
const appRef = await bootstrapApplication(ComponentWithOnDestroy);
const injector = (appRef as unknown as {injector: R3Injector}).injector;
injector.onDestroy(() => (injectorOnDestroyCalled = true));
expect(document.body.textContent).toBe('Hello');
const platformRef = injector.get(PlatformRef);
platformRef.destroy();
// Verify the callbacks were invoked.
expect(compOnDestroyCalled).toBe(true);
expect(serviceOnDestroyCalled).toBe(true);
expect(injectorOnDestroyCalled).toBe(true);
// Make sure the DOM has been cleaned up as well.
expect(document.body.textContent).toBe('');
}),
);
});
| |
014070
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ModuleWithProviders,
NgModule,
Provider,
ɵperformanceMarkFeature as performanceMarkFeature,
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {BROWSER_ANIMATIONS_PROVIDERS, BROWSER_NOOP_ANIMATIONS_PROVIDERS} from './providers';
/**
* Object used to configure the behavior of {@link BrowserAnimationsModule}
* @publicApi
*/
export interface BrowserAnimationsModuleConfig {
/**
* Whether animations should be disabled. Passing this is identical to providing the
* `NoopAnimationsModule`, but it can be controlled based on a runtime value.
*/
disableAnimations?: boolean;
}
/**
* Exports `BrowserModule` with additional dependency-injection providers
* for use with animations. See [Animations](guide/animations).
* @publicApi
*/
@NgModule({
exports: [BrowserModule],
providers: BROWSER_ANIMATIONS_PROVIDERS,
})
export class BrowserAnimationsModule {
/**
* Configures the module based on the specified object.
*
* @param config Object used to configure the behavior of the `BrowserAnimationsModule`.
* @see {@link BrowserAnimationsModuleConfig}
*
* @usageNotes
* When registering the `BrowserAnimationsModule`, you can use the `withConfig`
* function as follows:
* ```
* @NgModule({
* imports: [BrowserAnimationsModule.withConfig(config)]
* })
* class MyNgModule {}
* ```
*/
static withConfig(
config: BrowserAnimationsModuleConfig,
): ModuleWithProviders<BrowserAnimationsModule> {
return {
ngModule: BrowserAnimationsModule,
providers: config.disableAnimations
? BROWSER_NOOP_ANIMATIONS_PROVIDERS
: BROWSER_ANIMATIONS_PROVIDERS,
};
}
}
/**
* Returns the set of dependency-injection providers
* to enable animations in an application. See [animations guide](guide/animations)
* to learn more about animations in Angular.
*
* @usageNotes
*
* The function is useful when you want to enable animations in an application
* bootstrapped using the `bootstrapApplication` function. In this scenario there
* is no need to import the `BrowserAnimationsModule` NgModule at all, just add
* providers returned by this function to the `providers` list as show below.
*
* ```typescript
* bootstrapApplication(RootComponent, {
* providers: [
* provideAnimations()
* ]
* });
* ```
*
* @publicApi
*/
export function provideAnimations(): Provider[] {
performanceMarkFeature('NgEagerAnimations');
// Return a copy to prevent changes to the original array in case any in-place
// alterations are performed to the `provideAnimations` call results in app code.
return [...BROWSER_ANIMATIONS_PROVIDERS];
}
/**
* A null player that must be imported to allow disabling of animations.
* @publicApi
*/
@NgModule({
exports: [BrowserModule],
providers: BROWSER_NOOP_ANIMATIONS_PROVIDERS,
})
export class NoopAnimationsModule {}
/**
* Returns the set of dependency-injection providers
* to disable animations in an application. See [animations guide](guide/animations)
* to learn more about animations in Angular.
*
* @usageNotes
*
* The function is useful when you want to bootstrap an application using
* the `bootstrapApplication` function, but you need to disable animations
* (for example, when running tests).
*
* ```typescript
* bootstrapApplication(RootComponent, {
* providers: [
* provideNoopAnimations()
* ]
* });
* ```
*
* @publicApi
*/
export function provideNoopAnimations(): Provider[] {
// Return a copy to prevent changes to the original array in case any in-place
// alterations are performed to the `provideNoopAnimations` call results in app code.
return [...BROWSER_NOOP_ANIMATIONS_PROVIDERS];
}
| |
014073
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @module
* @description
* Entry point for all animation APIs of the animation browser package.
*/
export {ANIMATION_MODULE_TYPE} from '@angular/core';
export {
BrowserAnimationsModule,
BrowserAnimationsModuleConfig,
NoopAnimationsModule,
provideAnimations,
provideNoopAnimations,
} from './module';
export * from './private_export';
| |
014079
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
CommonModule,
DOCUMENT,
XhrFactory,
ɵPLATFORM_BROWSER_ID as PLATFORM_BROWSER_ID,
} from '@angular/common';
import {
APP_ID,
ApplicationConfig as ApplicationConfigFromCore,
ApplicationModule,
ApplicationRef,
createPlatformFactory,
ErrorHandler,
Inject,
InjectionToken,
ModuleWithProviders,
NgModule,
NgZone,
Optional,
PLATFORM_ID,
PLATFORM_INITIALIZER,
platformCore,
PlatformRef,
Provider,
RendererFactory2,
SkipSelf,
StaticProvider,
Testability,
TestabilityRegistry,
Type,
ɵINJECTOR_SCOPE as INJECTOR_SCOPE,
ɵinternalCreateApplication as internalCreateApplication,
ɵRuntimeError as RuntimeError,
ɵsetDocument,
ɵTESTABILITY as TESTABILITY,
ɵTESTABILITY_GETTER as TESTABILITY_GETTER,
} from '@angular/core';
import {BrowserDomAdapter} from './browser/browser_adapter';
import {BrowserGetTestability} from './browser/testability';
import {BrowserXhr} from './browser/xhr';
import {DomRendererFactory2} from './dom/dom_renderer';
import {DomEventsPlugin} from './dom/events/dom_events';
import {EVENT_MANAGER_PLUGINS, EventManager} from './dom/events/event_manager';
import {KeyEventsPlugin} from './dom/events/key_events';
import {SharedStylesHost} from './dom/shared_styles_host';
import {RuntimeErrorCode} from './errors';
/**
* Set of config options available during the application bootstrap operation.
*
* @publicApi
*
* @deprecated
* `ApplicationConfig` has moved, please import `ApplicationConfig` from `@angular/core` instead.
*/
// The below is a workaround to add a deprecated message.
type ApplicationConfig = ApplicationConfigFromCore;
export {ApplicationConfig};
/**
* Bootstraps an instance of an Angular application and renders a standalone component as the
* application's root component. More information about standalone components can be found in [this
* guide](guide/components/importing).
*
* @usageNotes
* The root component passed into this function *must* be a standalone one (should have the
* `standalone: true` flag in the `@Component` decorator config).
*
* ```typescript
* @Component({
* standalone: true,
* template: 'Hello world!'
* })
* class RootComponent {}
*
* const appRef: ApplicationRef = await bootstrapApplication(RootComponent);
* ```
*
* You can add the list of providers that should be available in the application injector by
* specifying the `providers` field in an object passed as the second argument:
*
* ```typescript
* await bootstrapApplication(RootComponent, {
* providers: [
* {provide: BACKEND_URL, useValue: 'https://yourdomain.com/api'}
* ]
* });
* ```
*
* The `importProvidersFrom` helper method can be used to collect all providers from any
* existing NgModule (and transitively from all NgModules that it imports):
*
* ```typescript
* await bootstrapApplication(RootComponent, {
* providers: [
* importProvidersFrom(SomeNgModule)
* ]
* });
* ```
*
* Note: the `bootstrapApplication` method doesn't include [Testability](api/core/Testability) by
* default. You can add [Testability](api/core/Testability) by getting the list of necessary
* providers using `provideProtractorTestingSupport()` function and adding them into the `providers`
* array, for example:
*
* ```typescript
* import {provideProtractorTestingSupport} from '@angular/platform-browser';
*
* await bootstrapApplication(RootComponent, {providers: [provideProtractorTestingSupport()]});
* ```
*
* @param rootComponent A reference to a standalone component that should be rendered.
* @param options Extra configuration for the bootstrap operation, see `ApplicationConfig` for
* additional info.
* @returns A promise that returns an `ApplicationRef` instance once resolved.
*
* @publicApi
*/
export function bootstrapApplication(
rootComponent: Type<unknown>,
options?: ApplicationConfig,
): Promise<ApplicationRef> {
return internalCreateApplication({rootComponent, ...createProvidersConfig(options)});
}
/**
* Create an instance of an Angular application without bootstrapping any components. This is useful
* for the situation where one wants to decouple application environment creation (a platform and
* associated injectors) from rendering components on a screen. Components can be subsequently
* bootstrapped on the returned `ApplicationRef`.
*
* @param options Extra configuration for the application environment, see `ApplicationConfig` for
* additional info.
* @returns A promise that returns an `ApplicationRef` instance once resolved.
*
* @publicApi
*/
export function createApplication(options?: ApplicationConfig) {
return internalCreateApplication(createProvidersConfig(options));
}
function createProvidersConfig(options?: ApplicationConfig) {
return {
appProviders: [...BROWSER_MODULE_PROVIDERS, ...(options?.providers ?? [])],
platformProviders: INTERNAL_BROWSER_PLATFORM_PROVIDERS,
};
}
/**
* Returns a set of providers required to setup [Testability](api/core/Testability) for an
* application bootstrapped using the `bootstrapApplication` function. The set of providers is
* needed to support testing an application with Protractor (which relies on the Testability APIs
* to be present).
*
* @returns An array of providers required to setup Testability for an application and make it
* available for testing using Protractor.
*
* @publicApi
*/
export function provideProtractorTestingSupport(): Provider[] {
// Return a copy to prevent changes to the original array in case any in-place
// alterations are performed to the `provideProtractorTestingSupport` call results in app
// code.
return [...TESTABILITY_PROVIDERS];
}
export function initDomAdapter() {
BrowserDomAdapter.makeCurrent();
}
export function errorHandler(): ErrorHandler {
return new ErrorHandler();
}
export function _document(): any {
// Tell ivy about the global document
ɵsetDocument(document);
return document;
}
export const INTERNAL_BROWSER_PLATFORM_PROVIDERS: StaticProvider[] = [
{provide: PLATFORM_ID, useValue: PLATFORM_BROWSER_ID},
{provide: PLATFORM_INITIALIZER, useValue: initDomAdapter, multi: true},
{provide: DOCUMENT, useFactory: _document, deps: []},
];
/**
* A factory function that returns a `PlatformRef` instance associated with browser service
* providers.
*
* @publicApi
*/
export const platformBrowser: (extraProviders?: StaticProvider[]) => PlatformRef =
createPlatformFactory(platformCore, 'browser', INTERNAL_BROWSER_PLATFORM_PROVIDERS);
/**
* Internal marker to signal whether providers from the `BrowserModule` are already present in DI.
* This is needed to avoid loading `BrowserModule` providers twice. We can't rely on the
* `BrowserModule` presence itself, since the standalone-based bootstrap just imports
* `BrowserModule` providers without referencing the module itself.
*/
const BROWSER_MODULE_PROVIDERS_MARKER = new InjectionToken(
typeof ngDevMode === 'undefined' || ngDevMode ? 'BrowserModule Providers Marker' : '',
);
const TESTABILITY_PROVIDERS = [
{
provide: TESTABILITY_GETTER,
useClass: BrowserGetTestability,
deps: [],
},
{
provide: TESTABILITY,
useClass: Testability,
deps: [NgZone, TestabilityRegistry, TESTABILITY_GETTER],
},
{
provide: Testability, // Also provide as `Testability` for backwards-compatibility.
useClass: Testability,
deps: [NgZone, TestabilityRegistry, TESTABILITY_GETTER],
},
];
const BROWSER_MODULE_PROVIDERS: Provider[] = [
{provide: INJECTOR_SCOPE, useValue: 'root'},
{provide: ErrorHandler, useFactory: errorHandler, deps: []},
{
provide: EVENT_MANAGER_PLUGINS,
useClass: DomEventsPlugin,
multi: true,
deps: [DOCUMENT, NgZone, PLATFORM_ID],
},
{provide: EVENT_MANAGER_PLUGINS, useClass: KeyEventsPlugin, multi: true, deps: [DOCUMENT]},
DomRendererFactory2,
SharedStylesHost,
EventManager,
{provide: RendererFactory2, useExisting: DomRendererFactory2},
{provide: XhrFactory, useClass: BrowserXhr, deps: []},
typeof ngDevMode === 'undefined' || ngDevMode
? {provide: BROWSER_MODULE_PROVIDERS_MARKER, useValue: true}
: [],
];
/**
* Exports required infrastructure for all Angular apps.
* Included by default in all Angular apps created with the CLI
* `new` command.
* Re-exports `CommonModule` and `ApplicationModule`, making their
* exports and providers available to all apps.
*
* @publicApi
*/
@NgModu
| |
014080
|
e({
providers: [...BROWSER_MODULE_PROVIDERS, ...TESTABILITY_PROVIDERS],
exports: [CommonModule, ApplicationModule],
})
export class BrowserModule {
constructor(
@Optional()
@SkipSelf()
@Inject(BROWSER_MODULE_PROVIDERS_MARKER)
providersAlreadyPresent: boolean | null,
) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && providersAlreadyPresent) {
throw new RuntimeError(
RuntimeErrorCode.BROWSER_MODULE_ALREADY_LOADED,
`Providers from the \`BrowserModule\` have already been loaded. If you need access ` +
`to common directives such as NgIf and NgFor, import the \`CommonModule\` instead.`,
);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.