id
stringlengths
6
6
text
stringlengths
20
17.2k
title
stringclasses
1 value
006153
import {Component} from '@angular/core'; @Component({ selector: 'app-user', template: ` Username: {{ username }} `, standalone: true, }) export class UserComponent { username = 'youngTech'; } @Component({ selector: 'app-root', template: ` <section> <app-user /> </section> `, standalone: true, imports: [UserComponent], }) export class AppComponent {}
006157
import {Component} from '@angular/core'; import {FormsModule} from '@angular/forms'; @Component({ selector: 'app-user', template: ` <p>Username: {{ username }}</p> <p>Framework: {{ favoriteFramework }}</p> <label for="framework"> Favorite Framework: <input id="framework" type="text" [(ngModel)]="favoriteFramework" /> </label> <button (click)="showFramework()">Show Framework</button> `, standalone: true, imports: [FormsModule], }) export class UserComponent { favoriteFramework = ''; username = 'youngTech'; showFramework() { alert(this.favoriteFramework); } }
006159
import {Component} from '@angular/core'; import {FormsModule} from '@angular/forms'; @Component({ selector: 'app-user', template: ` <p>Username: {{ username }}</p> <p>Framework:</p> <label for="framework"> Favorite Framework: <input id="framework" type="text" [(ngModel)]="favoriteFramework" /> </label> <button (click)="showFramework()">Show Framework</button> `, standalone: true, imports: [FormsModule], }) export class UserComponent { favoriteFramework = ''; username = 'youngTech'; showFramework() {} }
006163
# Forms Overview Forms are a big part of many apps because they enable your app to accept user input. Let's learn about how forms are handled in Angular. In Angular, there are two types of forms: template-driven and reactive. You'll learn about both over the next few activities. In this activity, you'll learn how to setup a form using a template-driven approach. <hr> <docs-workflow> <docs-step title="Create an input field"> In `user.component.ts`, update the template by adding a text input with the `id` set to `framework`, type set to `text`. ```angular-html <label for="framework"> Favorite Framework: <input id="framework" type="text" /> </label> ``` </docs-step> <docs-step title="Import `FormsModule`"> For this form to use Angular features that enable data binding to forms, you'll need to import the `FormsModule`. Import the `FormsModule` from `@angular/forms` and add it to the `imports` array of the `UserComponent`. <docs-code language="ts" highlight="[2, 7]"> import {Component} from '@angular/core'; import {FormsModule} from '@angular/forms'; @Component({ ... standalone: true, imports: [FormsModule], }) export class UserComponent {} </docs-code> </docs-step> <docs-step title="Add binding to the value of the input"> The `FormsModule` has a directive called `ngModel` that binds the value of the input to a property in your class. Update the input to use the `ngModel` directive, specifically with the following syntax `[(ngModel)]="favoriteFramework"` to bind to the `favoriteFramework` property. <docs-code language="html" highlight="[3]"> <label for="framework"> Favorite Framework: <input id="framework" type="text" [(ngModel)]="favoriteFramework" /> </label> </docs-code> After you've made changes, try entering a value in the input field. Notice how it updates on the screen (yes, very cool). Note: The syntax `[()]` is known as "banana in a box" but it represents two-way binding: property binding and event binding. Learn more in the [Angular docs about two-way data binding](guide/templates/two-way-binding). </docs-step> </docs-workflow> You've now taken an important first step towards building forms with Angular. Nice work. Let's keep the momentum going!
006165
import {Component} from '@angular/core'; import {FormsModule} from '@angular/forms'; @Component({ selector: 'app-user', template: ` <p>Username: {{ username }}</p> <p>{{ username }}'s favorite framework: {{ favoriteFramework }}</p> <label for="framework"> Favorite Framework: <input id="framework" type="text" [(ngModel)]="favoriteFramework" /> </label> `, standalone: true, imports: [FormsModule], }) export class UserComponent { favoriteFramework = ''; username = 'youngTech'; }
006168
# Constructor-based dependency injection In previous activities you used the `inject()` function to make resources available, "providing" them to your components. The `inject()` function is one pattern and it is useful to know that there is another pattern for injecting resources called constructor-based dependency injection. You specify the resources as parameters to the `constructor` function of a component. Angular will make those resources available to your component. <br><br> In this activity, you will learn how to use constructor-based dependency injection. <hr> To inject a service or some other injectable resource into your component use the following syntax: <docs-code language="ts" highlight="[3]"> @Component({...}) class PetCarDashboardComponent { constructor(private petCareService: PetCareService) { ... } } </docs-code> There are a few things to notice here: - Use the `private` keyword - The `petCareService` becomes a property you can use in your class - The `PetCareService` class is the injected class Alright, now you give this a try: <docs-workflow> <docs-step title="Update the code to use constructor-based DI"> In `app.component.ts`, update the constructor code to match the code below: Tip: Remember, if you get stuck refer to the example on this activity page. ```ts constructor(private carService: CarService) { this.display = this.carService.getCars().join(' ⭐️ '); } ``` </docs-step> </docs-workflow> Congratulations on completing this activity. The example code works the same as with using the `inject` function. While these two approaches are largely the same, there are some small differences that are beyond the scope of this tutorial. <br> You can find out more information about dependency injection in the [Angular Documentation](guide/di).
006200
# Defer triggers While the default options for `@defer` offer great options for lazy loading parts of your components it may still be desirable to further customize the deferred loading experience. By default, deferred content loads when the browser is idle. You can, however, customize when this loading occurs by specifying a **trigger**. This lets you pick the loading behavior best suited to your component. Deferrable views offer two types of loading trigger: <div class="docs-table docs-scroll-track-transparent"> <table> <tr> <td><code>on</code></td> <td> A trigger condition using a trigger from the list of built-in triggers.<br/> For example: <code>@defer (on viewport)</code> </td> </tr> <tr> <td><code>when</code></td> <td> A condition as an expression which is evaluated for truthiness. When the expression is truthy, the placeholder is swapped with the lazily loaded content.<br/> For example: <code>@defer (when customizedCondition)</code> </td> </tr> </table> </div> If the `when` condition evaluates to `false`, the `defer` block is not reverted back to the placeholder. The swap is a one-time operation. You can define multiple event triggers at once, these triggers will be evaluated as OR conditions. * Ex: `@defer (on viewport; on timer(2s))` * Ex: `@defer (on viewport; when customizedCondition)` In this activity, you'll learn how to use triggers to specify the condition to load the deferrable views. <hr> <docs-workflow> <docs-step title="Add `on hover` trigger"> In your `app.component.ts`, add an `on hover` trigger to the `@defer` block. <docs-code language="angular-html" hightlight="[1]"> @defer (on hover) { <article-comments /> } @placeholder (minimum 1s) { <p>Placeholder for comments</p> } @loading (minimum 1s; after 500ms) { <p>Loading comments...</p> } @error { <p>Failed to load comments</p> } </docs-code> Now, the page will not render the comments section until you hover its placeholder. </docs-step> <docs-step title="Add a 'Show all comments' button"> Next, update the template to include a button with the label "Show all comments". Include a template variable called `#showComments` with the button. <docs-code language="angular-html" hightlight="[1]"> <button type="button" #showComments>Show all comments</button> @defer (on hover) { <article-comments /> } @placeholder (minimum 1s) { <p>Placeholder for comments</p> } @loading (minimum 1s; after 500ms) { <p>Loading comments...</p> } @error { <p>Failed to load comments</p> } </docs-code> Note: for more information on [template variables check the documentation](https://angular.dev/guide/templates/reference-variables#). </docs-step> <docs-step title="Add `on interaction` trigger"> Update the `@defer` block in the template to use the `on interaction` trigger. Provide the `showComments` template variable as the parameter to `interaction`. <docs-code language="angular-html" hightlight="[3]"> <button type="button" #showComments>Show all comments</button> @defer (on hover; on interaction(showComments)) { <article-comments /> } @placeholder (minimum 1s) { <p>Placeholder for comments</p> } @loading (minimum 1s; after 500ms) { <p>Loading comments...</p> } @error { <p>Failed to load comments</p> } </docs-code> With these changes, the page will wait for one of the following conditions before rendering the comments section: * User hovers the comments section’s placeholder * User clicks on the “Show all comments" button You can reload the page to try out different triggers to render the comments section. </docs-step> </docs-workflow> If you would like to learn more, check out the documentation for [Deferrable View](https://angular.dev/guide/defer). Keep learning to unlock more of Angular's great features.
006210
# Angular versioning and releases We recognize that you need stability from the Angular framework. Stability ensures that reusable components and libraries, tutorials, tools, and learned practices don't become obsolete unexpectedly. Stability is essential for the ecosystem around Angular to thrive. We also share with you the need for Angular to keep evolving. We strive to ensure that the foundation on top of which you are building is continuously improving and enabling you to stay up-to-date with the rest of the web ecosystem and your user needs. This document contains the practices that we follow to provide you with a leading-edge application development platform, balanced with stability. We strive to ensure that future changes are always introduced in a predictable way. We want everyone who depends on Angular to know when and how new features are added, and to be well-prepared when obsolete ones are removed. Sometimes *breaking changes*, such as the removal of APIs or features, are necessary to innovate and stay current with evolving best practices, changing dependencies, or shifts in the web platform. These breaking changes go through a deprecation process explained in our [deprecation policy](#deprecation-policy). To make these transitions as straightforward as possible, the Angular team makes these commitments: * We work hard to minimize the number of breaking changes and to provide migration tools when possible * We follow the deprecation policy described here, so you have time to update your applications to the latest APIs and best practices HELPFUL: The practices described in this document apply to Angular 2.0 and later. If you are currently using AngularJS, see [Upgrading from AngularJS](https://angular.io/guide/upgrade "Upgrading from Angular JS"). *AngularJS* is the name for all v1.x versions of Angular. ## Angular versioning Angular version numbers indicate the level of changes that are introduced by the release. This use of [semantic versioning](https://semver.org/ "Semantic Versioning Specification") helps you understand the potential impact of updating to a new version. Angular version numbers have three parts: `major.minor.patch`. For example, version 7.2.11 indicates major version 7, minor version 2, and patch level 11. The version number is incremented based on the level of change included in the release. | Level of change | Details | |:--- |:--- | | Major release | Contains significant new features, some but minimal developer assistance is expected during the update. When updating to a new major release, you might need to run update scripts, refactor code, run additional tests, and learn new APIs. | | Minor release | Contains new smaller features. Minor releases are fully backward-compatible; no developer assistance is expected during update, but you can optionally modify your applications and libraries to begin using new APIs, features, and capabilities that were added in the release. We update peer dependencies in minor versions by expanding the supported versions, but we do not require projects to update these dependencies. | | Patch release | Low risk, bug fix release. No developer assistance is expected during update. | HELPFUL: As of Angular version 7, the major versions of Angular core and the CLI are aligned. This means that in order to use the CLI as you develop an Angular app, the version of `@angular/core` and the CLI need to be the same. ### Preview releases We let you preview what's coming by providing "Next" and Release Candidates \(`rc`\) pre-releases for each major and minor release: | Pre-release type | Details | |:--- |:--- | | Next | The release that is under active development and testing. The next release is indicated by a release tag appended with the `-next` identifier, such as `8.1.0-next.0`. | | Release candidate | A release that is feature complete and in final testing. A release candidate is indicated by a release tag appended with the `-rc` identifier, such as version `8.1.0-rc.0`. | The latest `next` or `rc` pre-release version of the documentation is available at [next.angular.dev](https://next.angular.dev). ## Release frequency We work toward a regular schedule of releases, so that you can plan and coordinate your updates with the continuing evolution of Angular. HELPFUL: Dates are offered as general guidance and are subject to change. In general, expect the following release cycle: * A major release every 6 months * 1-3 minor releases for each major release * A patch release and pre-release \(`next` or `rc`\) build almost every week This cadence of releases gives eager developers access to new features as soon as they are fully developed and pass through our code review and integration testing processes, while maintaining the stability and reliability of the platform for production users that prefer to receive features after they have been validated by Google and other developers that use the pre-release builds. ## Support policy and schedule HELPFUL: Approximate dates are offered as general guidance and are subject to change. ### Release schedule | Version | Date | |:--------|:-------------------| | v18.1 | Week of 2024-07-08 | | v18.2 | Week of 2024-08-12 | | v19.0 | Week of 2024-11-19 | ### Support window All major releases are typically supported for 18 months. | Support stage | Support Timing | Details | |:--- |:--- |:--- | | Active | 6 months | Regularly-scheduled updates and patches are released | | Long-term \(LTS\) | 12 months | Only [critical fixes and security patches](#lts-fixes) are released | ### Actively supported versions The following table provides the status for Angular versions under support. | Version | Status | Released | Active ends | LTS ends | |:--------|:-------|:-----------|:------------|:-----------| | ^18.0.0 | Active | 2024-05-22 | 2024-11-15 | 2025-11-15 | | ^17.0.0 | LTS | 2023-11-08 | 2024-05-08 | 2025-05-15 | | ^16.0.0 | LTS | 2023-05-03 | 2023-11-08 | 2024-11-08 | Angular versions v2 to v15 are no longer supported. ### LTS fixes As a general rule, a fix is considered for an LTS version if it resolves one of: * A newly identified security vulnerability, * A regression, since the start of LTS, caused by a 3rd party change, such as a new browser version. ## Deprecation policy When the Angular team intends to remove an API or feature, it will be marked as *deprecated*. This occurs when an API is obsolete, superseded by another API, or otherwise discontinued. Deprecated API remain available through their deprecated phase, which lasts a minimum two major versions (approximately one year). To help ensure that you have sufficient time and a clear path to update, this is our deprecation policy: | Deprecation stages | Details | |:--- |:--- | | Announcement | We announce deprecated APIs and features in the [change log](https://github.com/angular/angular/blob/main/CHANGELOG.md "Angular change log"). Deprecated APIs appear in the [documentation](api?status=deprecated) with ~~strikethrough~~. When we announce a deprecation, we also announce a recommended update path. Additionally, all deprecated APIs are annotated with `@deprecated` in the corresponding documentation, which enables text editors and IDEs to provide hints if your project depends on them. | | Deprecation period | When an API or a feature is deprecated, it is still present in at least the next two major releases (period of at least 12 months). After that, deprecated APIs and features are candidates for removal. A deprecation can be announced in any release, but the removal of a deprecated API or feature happens only in major release. Until a deprecated API or feature is removed, it is maintained according to the LTS support policy, meaning that only critical and security issues are fixed. | | npm dependencies | We only make npm dependency updates that require changes to your applications in a major release. In minor releases, we update peer dependencies by expanding the supported versions, but we do not require projects to update these dependencies until a future major version. This means that during minor Angular releases, npm dependency updates within Angular applications and libraries are optional. |
006211
## Compatibility policy Angular is a collection of many packages, subprojects, and tools. To prevent accidental use of private APIs and so that you can clearly understand what is covered by the practices described here — we document what is and is not considered our public API surface. For details, see [Supported Public API Surface of Angular](https://github.com/angular/angular/blob/main/contributing-docs/public-api-surface.md "Supported Public API Surface of Angular"). To guarantee backward compatibility of Angular we run a series of checks before we merge any change: * Unit tests and integration tests * Comparing the type definitions of the public API surface before and after the change * Running the tests of all the applications at Google that depend on Angular Any changes to the public API surface are made in accordance with the versioning, support, and depreciation policies previously described. In exceptional cases, such as critical security patches, fixes may introduce backwards incompatible changes. Such exceptional cases are accompanied by explicit notice on the framework's official communication channels. ## Breaking change policy and update paths Breaking change requires you to do work because the state after it is not backward compatible with the state before it. You can find the rare exceptions from this rule in the [Compatibility policy](#compatibility-policy). Examples of breaking changes are the removal of public APIs or other changes of the type definition of Angular, changing the timing of calls, or updating to a new version of a dependency of Angular, which includes breaking changes itself. To support you in case of breaking changes in Angular: * We follow our [deprecation policy](#deprecation-policy) before we remove a public API * Support update automation via the `ng update` command. It provides code transformations which we often have tested ahead of time over hundreds of thousands of projects at Google * Step by step instructions how to update from one major version to another at the ["Angular Update Guide"](update-guide) You can `ng update` to any version of Angular, provided that the following criteria are met: * The version you want to update *to* is supported. * The version you want to update *from* is within one major version of the version you want to upgrade to. For example, you can update from version 11 to version 12, provided that version 12 is still supported. If you want to update across multiple major versions, perform each update one major version at a time. For example, to update from version 10 to version 12: 1. Update from version 10 to version 11. 1. Update from version 11 to version 12. ## Developer Preview Occasionally we introduce new APIs under the label of "Developer Preview". These are APIs that are fully functional and polished, but that we are not ready to stabilize under our normal deprecation policy. This may be because we want to gather feedback from real applications before stabilization, or because the associated documentation or migration tooling is not fully complete. The policies and practices that are described in this document do not apply to APIs marked as Developer Preview. Such APIs can change at any time, even in new patch versions of the framework. Teams should decide for themselves whether the benefits of using Developer Preview APIs are worth the risk of breaking changes outside of our normal use of semantic versioning. ## Experimental These are APIs might not become stable at all or have significant changes before becoming stable. The policies and practices that are described in this document do not apply to APIs marked as experimental. Such APIs can change at any time, even in new patch versions of the framework. Teams should decide for themselves whether the benefits of using experimental APIs are worth the risk of breaking changes outside of our normal use of semantic versioning.
006214
## Unsupported Angular versions This table covers Angular versions that are no longer under long-term support (LTS). This information was correct when each version went out of LTS and is provided without any further guarantees. It is listed here for historical reference. | Angular | Node.js | TypeScript | RxJS | | ------------------ | ------------------------------------ | -------------- | ------------------ | | 15.1.x \|\| 15.2.x | ^14.20.0 \|\| ^16.13.0 \|\| ^18.10.0 | >=4.8.2 <5.0.0 | ^6.5.3 \|\| ^7.4.0 | | 15.0.x | ^14.20.0 \|\| ^16.13.0 \|\| ^18.10.0 | ~4.8.2 | ^6.5.3 \|\| ^7.4.0 | | 14.2.x \|\| 14.3.x | ^14.15.0 \|\| ^16.10.0 | >=4.6.2 <4.9.0 | ^6.5.3 \|\| ^7.4.0 | | 14.0.x \|\| 14.1.x | ^14.15.0 \|\| ^16.10.0 | >=4.6.2 <4.8.0 | ^6.5.3 \|\| ^7.4.0 | | 13.3.x \|\| 13.4.x | ^12.20.0 \|\| ^14.15.0 \|\| ^16.10.0 | >=4.4.3 <4.7.0 | ^6.5.3 \|\| ^7.4.0 | | 13.1.x \|\| 13.2.x | ^12.20.0 \|\| ^14.15.0 \|\| ^16.10.0 | >=4.4.3 <4.6.0 | ^6.5.3 \|\| ^7.4.0 | | 13.0.x | ^12.20.0 \|\| ^14.15.0 \|\| ^16.10.0 | ~4.4.3 | ^6.5.3 \|\| ^7.4.0 | | 12.2.x | ^12.14.0 \|\| ^14.15.0 | >=4.2.3 <4.4.0 | ^6.5.3 \|\| ^7.0.0 | | 12.1.x | ^12.14.0 \|\| ^14.15.0 | >=4.2.3 <4.4.0 | ^6.5.3 | | 12.0.x | ^12.14.0 \|\| ^14.15.0 | ~4.2.3 | ^6.5.3 | | 11.2.x | ^10.13.0 \|\| ^12.11.0 | >=4.0.0 <4.2.0 | ^6.5.3 | | 11.1.x | ^10.13.0 \|\| ^12.11.0 | >=4.0.0 <4.2.0 | ^6.5.3 | | 11.0.x | ^10.13.0 \|\| ^12.11.0 | ~4.0.0 | ^6.5.3 | | 10.2.x | ^10.13.0 \|\| ^12.11.0 | >=3.9.0 <4.1.0 | ^6.5.3 | | 10.1.x | ^10.13.0 \|\| ^12.11.0 | >=3.9.0 <4.1.0 | ^6.5.3 | | 10.0.x | ^10.13.0 \|\| ^12.11.0 | ~3.9.0 | ^6.5.3 | | 9.1.x | ^10.13.0 \|\| ^12.11.0 | >=3.6.0 <3.9.0 | ^6.5.3 | | 9.0.x | ^10.13.0 \|\| ^12.11.0 | >=3.6.0 <3.8.0 | ^6.5.3 | ### Before v9 Until Angular v9, Angular and Angular CLI versions were not synced. | Angular | Angular CLI | Node.js | TypeScript | RxJS | | --------------------------- | --------------------------- | ------------------- | -------------- | ------ | | 8.2.x | 8.2.x \|\| 8.3.x | ^10.9.0 | >=3.4.2 <3.6.0 | ^6.4.0 | | 8.0.x \|\| 8.1.x | 8.0.x \|\| 8.1.x | ^10.9.0 | ~3.4.2 | ^6.4.0 | | 7.2.x | 7.2.x \|\| 7.3.x | ^8.9.0 \|\| ^10.9.0 | >=3.1.3 <3.3.0 | ^6.0.0 | | 7.0.x \|\| 7.1.x | 7.0.x \|\| 7.1.x | ^8.9.0 \|\| ^10.9.0 | ~3.1.3 | ^6.0.0 | | 6.1.x | 6.1.x \|\| 6.2.x | ^8.9.0 | >=2.7.2 <3.0.0 | ^6.0.0 | | 6.0.x | 6.0.x | ^8.9.0 | ~2.7.2 | ^6.0.0 | | 5.2.x | 1.6.x \|\| 1.7.x | ^6.9.0 \|\| ^8.9.0 | >=2.4.2 <2.7.0 | ^5.5.0 | | 5.0.x \|\| 5.1.x | 1.5.x | ^6.9.0 \|\| ^8.9.0 | ~2.4.2 | ^5.5.0 | | 4.2.x \|\| 4.3.x \|\| 4.4.x | 1.4.x | ^6.9.0 \|\| ^8.9.0 | >=2.1.6 <2.5.0 | ^5.0.1 | | 4.2.x \|\| 4.3.x \|\| 4.4.x | 1.3.x | ^6.9.0 | >=2.1.6 <2.5.0 | ^5.0.1 | | 4.0.x \|\| 4.1.x | 1.0.x \|\| 1.1.x \|\| 1.2.x | ^6.9.0 | >=2.1.6 <2.4.0 | ^5.0.1 | | 2.x | - | ^6.9.0 | >=1.8.0 <2.2.0 | ^5.0.1 | ## Browser support Angular supports most recent browsers. This includes the following specific versions: | Browser | Supported versions | | :------ | :------------------------------------------ | | Chrome | 2 most recent versions | | Firefox | latest and extended support release \(ESR\) | | Edge | 2 most recent major versions | | Safari | 2 most recent major versions | | iOS | 2 most recent major versions | | Android | 2 most recent major versions | HELPFUL: Angular's continuous integration process runs unit tests of the framework on all of these browsers for every pull request, using [Sauce Labs](https://saucelabs.com).
006215
## Polyfills Angular is built on the latest standards of the web platform. Targeting such a wide range of browsers is challenging because they do not support all features of modern browsers. You compensate by loading polyfill scripts \("polyfills"\) for the browsers that you must support. See instructions on how to include polyfills into your project below. IMPORTANT: The suggested polyfills are the ones that run full Angular applications. You might need additional polyfills to support features not covered by this list. HELPFUL: Polyfills cannot magically transform an old, slow browser into a modern, fast one. ## Enabling polyfills with CLI projects The [Angular CLI](tools/cli) provides support for polyfills. If you are not using the CLI to create your projects, see [Polyfill instructions for non-CLI users](#polyfills-for-non-cli-users). The `polyfills` options of the [browser and test builder](tools/cli/cli-builder) can be a full path for a file \(Example: `src/polyfills.ts`\) or, relative to the current workspace or module specifier \(Example: `zone.js`\). If you create a TypeScript file, make sure to include it in the `files` property of your `tsconfig` file. <docs-code language="json"> { "extends": "./tsconfig.json", "compilerOptions": { ... }, "files": [ "src/main.ts", "src/polyfills.ts" ] ... } </docs-code> ## Polyfills for non-CLI users If you are not using the CLI, add your polyfill scripts directly to the host web page \(`index.html`\). For example: <docs-code header="src/index.html" language="html"> <!-- pre-zone polyfills --> <script src="node_modules/core-js/client/shim.min.js"></script> <script> /** * you can configure some zone flags which can disable zone interception for some * asynchronous activities to improve startup performance - use these options only * if you know what you are doing as it could result in hard to trace down bugs. */ // &lowbar;&lowbar;Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame // &lowbar;&lowbar;Zone_disable_on_property = true; // disable patch onProperty such as onclick // &lowbar;&lowbar;zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames /* * in Edge developer tools, the addEventListener will also be wrapped by zone.js * with the following flag, it will bypass `zone.js` patch for Edge. */ // &lowbar;&lowbar;Zone_enable_cross_context_check = true; </script> <!-- zone.js required by Angular --> <script src="node_modules/zone.js/bundles/zone.umd.js"></script> <!-- application polyfills --> </docs-code>
006217
<docs-decorative-header title="Angular Roadmap" imgSrc="adev/src/assets/images/roadmap.svg"> <!-- markdownlint-disable-line --> Learn how the Angular team is building momentum on the web. </docs-decorative-header> As an open source project, Angular’s daily commits, PRs and momentum is all trackable on GitHub. To increase transparency into how this daily work connects to the framework’s future, our roadmap brings together the team’s current and future planned vision. The following projects are not associated with a particular Angular version. We will release them on completion, and they will be part of a specific version based on our release schedule, following semantic versioning. For example, we release features in the next minor after completion or the next major if they include breaking changes. Currently, Angular has two goals for the framework: 1. Improve the [Angular developer experience](#improving-the-angular-developer-experience) and 2. Improve the [framework’s performance](#fast-by-default). Continue reading to learn how we plan to deliver these objectives with specific project work. ## Explore modern Angular Start developing with the latest Angular features from our roadmap. This list represents the current status of new features from our roadmap: ### Available to experiment with * [Explore Angular Signals](guide/signals) * [Event replay with SSR](https://angular.dev/api/platform-browser/withEventReplay) * [Zoneless change detection](https://angular.dev/guide/experimental/zoneless) * [Hydration support for i18n blocks](https://angular.dev/api/platform-browser/withI18nSupport) ### Production ready * [Hydration](guide/hydration) * [Deferrable views](https://angular.dev/guide/defer) * [Built-in control flow](https://angular.dev/guide/templates/control-flow) * [Migrate your Angular Material to MDC](https://material.angular.io/guide/mdc-migration) * [Angular Material 3](https://material.angular.io/guide/theming) * [Migrate to Standalone APIs](reference/migrations/standalone) * [Improve image performance with NgOptimizedImage](guide/image-optimization) * [Try out Inject](/tutorials/learn-angular/20-inject-based-di) * [New CDK directives](https://material.angular.io/cdk/categories) ## Improving the Angular developer experience ### Developer velocity <docs-card-container> <docs-card title="Deliver Angular Signals" href="https://github.com/angular/angular/discussions/49685"> This project rethinks the Angular reactivity model by introducing Signals as a reactivity primitive. The initial planning resulted in hundreds of discussions, conversations with developers, feedback sessions, user experience studies, and a series of RFCs, which received over 1,000 comments. As part of the v17 release, we graduated the Angular Signals library from developer preview. In v18 you can now use signal-based queries, inputs, and model inputs in developer preview. Next we'll continue addressing community feedback before graduating these APIs to stable and integrate signals deeper in Angular's change detection mechanism. </docs-card> <docs-card title="Zoneless Angular" href=""> In v18 we shipped experimental zoneless support in Angular. It enables developers to use the framework without including zone.js in their bundle, which improves performance, debugging experience, and interoperability. As part of the initial release we also introduced zoneless support to the Angular CDK and Angular Material. As the next step, we'll continue iterating on the API to improve developer experience. </docs-card> <docs-card title="Local template variables" href="https://github.com/angular/angular/issues/15280"> Local template variables is one of the most upvoted features in the Angular issue tracker. In Q2 2024 we started initial design and prototyping. Expect updates later in 2024. </docs-card> </docs-card-container> ### Improve Angular Material and the CDK <docs-card-container> <docs-card title="New CDK primitives" href=""> We are working on new CDK primitives to facilitate creating custom components based on the WAI-ARIA design patterns for [Combobox](https://www.w3.org/TR/wai-aria-practices-1.1/#combobox). Angular v14 introduced stable [menu and dialog primitives](https://material.angular.io/cdk/categories) as part of this project, and in v15 Listbox. </docs-card> <docs-card title="Angular component accessibility" href=""> We are evaluating components in Angular Material against accessibility standards such as WCAG and working to fix any issues that arise from this process. </docs-card> </docs-card-container> ### Improve tooling <docs-card-container> <docs-card title="Modernize unit testing tooling with ng test" href=""> In v12, we revisited the Angular end-to-end testing experience by replacing Protractor with modern alternatives such as Cypress, Nightwatch, and Webdriver.io. Next, we'd like to tackle `ng test` to modernize Angular's unit testing experience. In Q2 2023, we introduced experimental [Jest](https://jestjs.io/) support and [announced](https://blog.angular.dev/moving-angular-cli-to-jest-and-web-test-runner-ef85ef69ceca) the transition from Karma to the [Web Test Runner](https://modern-web.dev/docs/test-runner/overview/). Later this year we'll continue making progress towards introducing Web Test Runner as the replacement of Karma. </docs-card> <docs-card title="Streamline standalone imports with Language Service" href=""> As part of this initiative, the language service automatically imports components and pipes in standalone and NgModule-based apps. Additionally, to enable smaller app bundles, we'll work on allowing the language service to propose the automatic removal of unused imports. </docs-card> </docs-card-container> ## Fast by default <docs-card-container> <docs-card title="Exploration of partial hydration" href=""> In v17 we graduated hydration from developer preview and we've been consistently observing 40-50% improvements in LCP. Since then we started prototyping partial hydration and shared a demo on stage at ng-conf. Expect an experimental support in 2024. </docs-card> <docs-card title="Event replay with SSR and prerendering" href="https://angular.dev/api/platform-browser/withEventReplay"> In v18 we introduced an event replay functionality when using server-side rendering or prerendering. For this feature we depend on the event dispatch primitive (previously known as jsaction) that is running on Google.com. Over the next couple of months we'll be collecting feedback from the community for this feature and work towards graduating it to stable. </docs-card> <docs-card title="Server route configuration" href=""> We're working towards enabling a more ergonomic route configuration on the server. We want to make it trivial to declare which routes should be server-side rendered, prerendered or client-side rendered. As of right now, we're in early design and prototyping phase. Expect updates later in 2024. </docs-card> </docs-card-container> ## Futur
006218
e work, explorations, and prototyping This section represents explorations and prototyping of potential future projects. A reasonable outcome is to decide that our current solutions are the best options. Other projects may result in RFCs, graduating to in-progress projects, or being deprioritized as the web continues to innovate along with our framework. <docs-card-container> <docs-card title="Signal debugging in Angular DevTools" href=""> With the evolution of Signals in Angular, we'll be also working on a better tooling for debugging them. High on the priority list is a UI for inspecting and debugging Signal-based components. </docs-card> <docs-card title="Improve HMR (Hot Module Reload)" href="https://github.com/angular/angular/issues/39367#issuecomment-1439537306"> Angular CLI currently supports HMR via `ng serve --hmr`. Under the hood, this mostly rerenders the Angular application from scratch, which is better than a full page reload, but can definitely be improved. Most importantly, our strategy here should be to optimize the turnaround time for any given change scaled with the frequency of that kind of change. In the future, our team will explore a number of opportunities for improving HMR, including: - Fast track CSS-only changes and apply them to any existing components on the page. - Fast track Angular template-only changes and apply them to any existing components on the page. </docs-card> <docs-card title="Exploration of streamed server-side rendering" href=""> Over the past few releases we've been working on making Angular's server-side rendering story more robust. On our priority list is to explore streamed server-side rendering for zoneless application. </docs-card> <docs-card title="Investigation for authoring format improvements" href=""> Based on our developer surveys' results we saw there are opportunities for improving the ergonomics of the component authoring format. The first step of the process will be to gather requirements and understand the problem space in advanced to an RFC. We'll share updates as we make progress. High priority in the future work will be backward compatibility and interoperability. </docs-card> <docs-card title="Support two-dimensional drag-and-drop" href="https://github.com/angular/components/issues/13372"> As part of this project, we'd like to implement mixed orientation support for the Angular CDK drag and drop. This is one of the repository's most highly requested features. </docs-card> <docs-card title="Evaluating Nitro support in the Angular CLI" href="https://nitro.unjs.io/"> We're excited about the set of features that Nitro offers such as portability, minimal design, and file-based routing. Later this year we'll evaluate how it fits in the Angular server-side rendering model. We'll share updates as we make progress in this investigation. </docs-card> </docs-card-container> ## Completed projects <docs-card-container> <docs-card title="Expand the customizability of Angular Material" link="Completed in Q2 2024" href="https://material.angular.io/guide/theming"> To provide better customization of our Angular Material components and enable Material 3 capabilities, we'll be collaborating with Google's Material Design team on defining token-based theming APIs. In v17.2 we shared experimental support for Angular Material 3 and in v18 we graduated it to stable. </docs-card> <docs-card title="Introduce deferred loading" link="Completed in Q2 2024" href="https://next.angular.dev/guide/defer"> In v17 we shipped deferrable views in developer preview, which provide an ergonomic API for deferred code loading. In v18 we enabled deferrable views for library developers and graduated the API to stable. </docs-card> <docs-card title="iframe support in Angular DevTools" link="Completed in Q2 2024" href=""> We enabled debugging and profiling of Angular apps embedded within an iframe on the page. </docs-card> <docs-card title="Automation for transition of existing hybrid rendering projects to esbuild and vite" link="Completed in Q2 2024" href="tools/cli/build-system-migration"> In v17 we shipped a vite and esbuild-based application builder and enabled it for new projects by default. It improves build time for projects using hybrid rendering with up to 87%. As part of v18 we shipped schematics and a guide that migrate existing projects using hybrid rendering to the new build pipeline. </docs-card> <docs-card title="Make Angular.dev the official home for Angular developers" link="Completed in Q2 2024" href="https://goo.gle/angular-dot-dev"> Angular.dev is the new site, domain and home for Angular development. The new site contains updated documentation, tutorials and guidance that will help developers build with Angular’s latest features. </docs-card> <docs-card title="Introduce built-in control flow" link="Completed in Q2 2024" href="https://next.angular.dev/essentials/conditionals-and-loops"> In v17 we shipped a developer preview version of a new control flow. It brings significant performance improvements and better ergonomics for template authoring. We also provided a migration of existing `*ngIf`, `*ngFor`, and `*ngSwitch` which you can run to move your project to the new implementation. As of v18 the built-in control flow is now stable. </docs-card> <docs-card title="Modernize getting started tutorial" link="Completed Q4 2023" href=""> Over the past two quarters, we developed a new [video](https://www.youtube.com/watch?v=xAT0lHYhHMY&list=PL1w1q3fL4pmj9k1FrJ3Pe91EPub2_h4jF) and [textual](https://angular.dev/tutorials/learn-angular) tutorial based on standalone components. </docs-card> <docs-card title="Investigate modern bundlers" link="Completed Q4 2023" href="guide/hydration"> In Angular v16, we released a developer preview of an esbuild-based builder with support for `ng build` and `ng serve`. The `ng serve` development server uses Vite and a multi-file compilation by esbuild and the Angular compiler. In v17 we graduated the build tooling from developer preview and enabled it by default for new projects. </docs-card> <docs-card title="Introduce dependency injection debugging APIs" link="Completed Q4 2023" href="tools/devtools"> To improve the debugging utilities of Angular and Angular DevTools, we'll work on APIs that provide access to the dependency injection runtime. As part of the project, we'll expose debugging methods that allow us to explore the injector hierarchy and the dependencies across their associated providers. As of v17, we shipped a feature that enables us to plug into the dependency injection life-cycle. We also launched a visualization of the injector tree and inspection of the providers declared inside each individual node, </docs-card> <docs-card title="Improve documentation and schematics for standalone components" link="Completed Q4 2023" href="components"> We released a developer preview of the `ng new --standalone` schematics collection, allowing you to create apps free of NgModules. In v17 we switched the new application authoring format to standalone APIs and changed the documentation to reflect the recommendation. Additionally, we shipped schematics which support updating existing applications to standalone components, directives, and pipes. Even though NgModules will stick around for foreseeable future, we recommend you to explore the benefits of the new APIs to improve developer experience and benefit from the new features we build for them. </docs-card> <docs-card title="Explore hydration and server-side rendering improvements" link="Completed Q4 2023"> In v16, we released a developer preview of non-destructive full hydration, see the [hydration guide](guide/hydration) and the [blog post](https://blog.angular.dev/whats-next-for-server-side-rendering-in-angular-2a6f27662b67) for additional information. We're already seeing significant improvements to Core Web Vitals, including [LCP](https://web.dev/lcp) and [CLS](https://web.dev/cls). In lab tests, we consistently observed 45% better LCP of a real-world app. In v17
006222
# Migrations Learn about how you can migrate your existing angular project to the latest features incrementally. <docs-card-container> <docs-card title="Standalone" link="Migrate now" href="reference/migrations/standalone"> Standalone components provide a simplified way to build Angular applications. Standalone components specify their dependencies directly instead of getting them through NgModules. </docs-card> <docs-card title="Control Flow Syntax" link="Migrate now" href="reference/migrations/control-flow"> Built-in Control Flow Syntax allows you to use more ergonomic syntax which is close to JavaScript and has better type checking. It replaces the need to import `CommonModule` to use functionality like `*ngFor`, `*ngIf` and `*ngSwitch`. </docs-card> <docs-card title="inject() Function" link="Migrate now" href="reference/migrations/inject-function"> Angular's `inject` function offers more accurate types and better compatibility with standard decorators, compared to constructor-based injection. </docs-card> <docs-card title="Lazy-loaded routes" link="Migrate now" href="reference/migrations/route-lazy-loading"> Convert eagerly loaded component routes to lazy loaded ones. This allows the build process to split production bundles into smaller chunks, to load less JavaScript at initial page load. </docs-card> <docs-card title="New `input()` API" link="Migrate now" href="reference/migrations/signal-inputs"> Convert existing `@Input` fields to the new signal input API that is now production ready. </docs-card> <docs-card title="Queries as signal" link="Migrate now" href="reference/migrations/signal-queries"> Convert existing decorator query fields to the improved signal queries API. The API is now production ready. </docs-card> </docs-card-container>
006223
# Migration to the `inject` function Angular's `inject` function offers more accurate types and better compatibility with standard decorators, compared to constructor-based injection. This schematic converts constructor-based injection in your classes to use the `inject` function instead. Run the schematic using the following command: <docs-code language="shell"> ng generate @angular/core:inject </docs-code> #### Before <docs-code language="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(DI_TOKEN) @Optional() readonly token: string) {} } </docs-code> #### After <docs-code language="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 }); } </docs-code> ## Migration 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 <docs-code language="typescript"> import { Component } from '@angular/core'; import { MyService } from './service'; @Component() export class MyComp { constructor(private service: MyService) {} } </docs-code> #### After <docs-code language="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() {} } </docs-code> ### `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 <docs-code language="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) {} } </docs-code> #### After <docs-code language="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 }); } </docs-code>
006224
# Migration to lazy-loaded routes This schematic helps developers to convert eagerly loaded component routes to lazy loaded routes. This allows the build process to 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. Run the schematic using the following command: <docs-code language="shell"> ng generate @angular/core:route-lazy-loading </docs-code> ### `path` config option 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: <docs-code language="shell"> ng generate @angular/core:route-lazy-loading --path src/app/sub-component </docs-code> 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 <docs-code language="typescript"> // app.module.ts import { HomeComponent } from './home/home.component'; @NgModule({ imports: [ RouterModule.forRoot([ { path: 'home', // HomeComponent is standalone and eagerly loaded component: HomeComponent, }, ]), ], }) export class AppModule {} </docs-code> #### After <docs-code language="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 {} </docs-code> 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.
006225
# Migration to Control Flow syntax [Control flow syntax](guide/templates/control-flow) is available from Angular v17. The new syntax is baked into the template, so you don't need to import `CommonModule` anymore. This schematic migrates all existing code in your application to use new Control Flow Syntax. Run the schematic using the following command: <docs-code language="shell"> ng generate @angular/core:control-flow </docs-code>
006226
# Migrate an existing Angular project to standalone **Standalone components** provide a simplified way to build Angular applications. Standalone components, directives, and pipes aim to streamline the authoring experience by reducing the need for `NgModule`s. Existing applications can optionally and incrementally adopt the new standalone style without any breaking changes. <docs-video src="https://www.youtube.com/embed/x5PZwb4XurU" title="Getting started with standalone components"/> This schematic helps to transform components, directive and pipes in existing projects to become standalone. The schematic aims to transform as much code as possible automatically, but it may require some manual fixes by the project author. Run the schematic using the following command: <docs-code language="shell"> ng generate @angular/core:standalone </docs-code> ## Before updating Before using the schematic, please ensure that the project: 1. Is using Angular 15.2.0 or later. 2. Builds without any compilation errors. 3. Is on a clean Git branch and all work is saved. ## Schematic options | Option | Details | |:--- |:--- | | `mode` | The transformation to perform. See [Migration modes](#migration-modes) below for details on the available options. | | `path` | The path to migrate, relative to the project root. You can use this option to migrate sections of your project incrementally. | ## Migrations steps The migration process is composed of three steps. You'll have to run it multiple times and check manually that the project builds and behaves as expected. Note: While the schematic can automatically update most code, some edge cases require developer intervention. You should plan to apply manual fixes after each step of the migration. Additionally, the new code generated by the schematic may not match your code's formatting rules. Run the migration in the order listed below, verifying that your code builds and runs between each step: 1. Run `ng g @angular/core:standalone` and select "Convert all components, directives and pipes to standalone" 2. Run `ng g @angular/core:standalone` and select "Remove unnecessary NgModule classes" 3. Run `ng g @angular/core:standalone` and select "Bootstrap the project using standalone APIs" 4. Run any linting and formatting checks, fix any failures, and commit the result ## After the migration Congratulations, your application has been converted to standalone 🎉. These are some optional follow-up steps you may want to take now: * Find and remove any remaining `NgModule` declarations: since the ["Remove unnecessary NgModules" step](#remove-unnecessary-ngmodules) cannot remove all modules automatically, you may have to remove the remaining declarations manually. * Run the project's unit tests and fix any failures. * Run any code formatters, if the project uses automatic formatting. * Run any linters in your project and fix new warnings. Some linters support a `--fix` flag that may resolve some of your warnings automatically. ## Migration modes The migration has the following modes: 1. Convert declarations to standalone. 2. Remove unnecessary NgModules. 3. Switch to standalone bootstrapping API. You should run these migrations in the order given. ### Convert declarations to standalone In this mode, the migration converts all components, directives and pipes to standalone by setting `standalone: true` and adding dependencies to their `imports` array. HELPFUL: The schematic ignores NgModules which bootstrap a component during this step because they are likely root modules used by `bootstrapModule` rather than the standalone-compatible `bootstrapApplication`. The schematic converts these declarations automatically as a part of the ["Switch to standalone bootstrapping API"](#switch-to-standalone-bootstrapping-api) step. **Before:** ```typescript // shared.module.ts @NgModule({ imports: [CommonModule], declarations: [GreeterComponent], exports: [GreeterComponent] }) export class SharedModule {} ``` ```typescript // greeter.component.ts @Component({ selector: 'greeter', template: '<div *ngIf="showGreeting">Hello</div>', }) export class GreeterComponent { showGreeting = true; } ``` **After:** ```typescript // shared.module.ts @NgModule({ imports: [CommonModule, GreeterComponent], exports: [GreeterComponent] }) export class SharedModule {} ``` ```typescript // greeter.component.ts @Component({ selector: 'greeter', template: '<div *ngIf="showGreeting">Hello</div>', standalone: true, imports: [NgIf] }) export class GreeterComponent { showGreeting = true; } ``` ### Remove unnecessary NgModules After converting all declarations to standalone, many NgModules can be safely removed. This step deletes such module declarations and as many corresponding references as possible. If the migration cannot delete a reference automatically, it leaves the following TODO comment so that you can delete the NgModule manually: ```typescript /* TODO(standalone-migration): clean up removed NgModule reference manually */ ``` The migration considers a module safe to remove if that module: * 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: [FooComponent, BarPipe], exports: [FooComponent, BarPipe] }) export class ImporterModule {} ``` **After:** ```typescript // importer.module.ts // Does not exist! ``` ### Switch to standalone bootstrapping API This step converts any usages of `bootstrapModule` to the new, standalone-based `bootstrapApplication`. It also switches the root component to `standalone: true` and deletes the root NgModule. If the root module has any `providers` or `imports`, the migration attempts to copy as much of this configuration as possible into the new bootstrap call. **Before:** ```typescript // ./app/app.module.ts import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], bootstrap: [AppComponent] }) export class AppModule {} ``` ```typescript // ./app/app.component.ts @Component({ selector: 'app', template: 'hello' }) 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 // Does not exist! ``` ```typescript // ./app/app.component.ts @Component({ selector: 'app', template: 'hello', standalone: true }) export class AppComponent {} ``` ```typescript // ./main.ts import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; bootstrapApplication(AppComponent).catch(e => console.error(e)); ``` ## Common problems Some common problems that may prevent the schematic from working correctly include: * Compilation errors - if the project has compilation errors, Angular cannot analyze and migrate it correctly. * Files not included in a tsconfig - the schematic determines which files to migrate by analyzing your project's `tsconfig.json` files. The schematic excludes any files not captured by a tsconfig. * Code that cannot be statically analyzed - the schematic uses static analysis to understand your code and determine where to make changes. The migration may skip any classes with metadata that cannot be statically analyzed at build time. ## Limitations Due to the size and complexity of the migration, there are some cases that the schematic cannot handle: * Because unit tests are not ahead-of-time (AoT) compiled, `imports` added to components in unit tests might not be entirely correct. * The schematic relies on direct calls to Angular APIs. The schematic cannot recognize custom wrappers around Angular APIs. For example, if there you define a custom `customConfigureTestModule` function that wraps `TestBed.configureTestingModule`, components it declares may not be recognized.
006232
## Configuring CLI builders Architect is the tool that the Angular CLI uses to perform complex tasks, such as compilation and test running. Architect is a shell that runs a specified builder to perform a given task, according to a target configuration. You can define and configure new builders and targets to extend the Angular CLI. See [Angular CLI Builders](tools/cli/cli-builder). ### Default Architect builders and targets Angular defines default builders for use with specific commands, or with the general `ng run` command. The JSON schemas that define the options and defaults for each of these builders are collected in the [`@angular-devkit/build-angular`](https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/build_angular/builders.json) package. The schemas configure options for the following builders. ### Configuring builder targets The `architect` section of `angular.json` contains a set of Architect targets. Many of the targets correspond to the Angular CLI commands that run them. Other targets can be executed using the `ng run` command, and you can define your own targets. Each target object specifies the `builder` for that target, which is the npm package for the tool that Architect runs. Each target also has an `options` section that configures default options for the target, and a `configurations` section that names and specifies alternative configurations for the target. See the example in [Build target](#build-target) below. | Property | Details | |:--- |:--- | | `build` | Configures defaults for options of the `ng build` command. See the [Build target](#build-target) section for more information. | | `serve` | Overrides build defaults and supplies extra serve defaults for the `ng serve` command. Besides the options available for the `ng build` command, it adds options related to serving the application. | | `e2e` | Overrides build defaults for building end-to-end testing applications using the `ng e2e` command. | | `test` | Overrides build defaults for test builds and supplies extra test-running defaults for the `ng test` command. | | `lint` | Configures defaults for options of the `ng lint` command, which performs static code analysis on project source files. | | `extract-i18n` | Configures defaults for options of the `ng extract-i18n` command, which extracts localized message strings from source code and outputs translation files for internationalization. | HELPFUL: All options in the configuration file must use `camelCase`, rather than `dash-case` as used on the command line. ## Build target Each target under `architect` has the following properties: | Property | Details | |:--- |:--- | | `builder` | The CLI builder used to create this target in the form of `<package-name>:<builder-name>`. | | `options` | Build target default options. | | `configurations`| Alternative configurations for executing the target. Each configuration sets the default options for that intended environment, overriding the associated value under `options`. See [Alternate build configurations](#alternate-build-configurations) below. | For example, to configure a build with optimizations disabled: <docs-code language="json"> { "projects": { "my-app": { "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "optimization": false } } } } } } </docs-code> ### Alternate build configurations Angular CLI comes with two build configurations: `production` and `development`. By default, the `ng build` command uses the `production` configuration, which applies several build optimizations, including: * Bundling files * Minimizing excess whitespace * Removing comments and dead code * Minifying code to use short, mangled names You can define and name extra alternate configurations (such as `staging`, for instance) appropriate to your development process. You can select an alternate configuration by passing its name to the `--configuration` command line flag. For example, to configure a build where optimization is enabled only for production builds (`ng build --configuration production`): <docs-code language="json"> { "projects": { "my-app": { "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "optimization": false }, "configurations": { "production": { "optimization": true } } } } } } } </docs-code> You can also pass in more than one configuration name as a comma-separated list. For example, to apply both `staging` and `french` build configurations, use the command `ng build --configuration staging,french`. In this case, the command parses the named configurations from left to right. If multiple configurations change the same setting, the last-set value is the final one. In this example, if both `staging` and `french` configurations set the output path, the value in `french` would get used. ### Extra build and test options The configurable options for a default or targeted build generally correspond to the options available for the [`ng build`](cli/build), [`ng serve`](cli/serve), and [`ng test`](cli/test) commands. For details of those options and their possible values, see the [Angular CLI Reference](cli). | Options properties | Details | |:--- |:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `assets` | An object containing paths to static assets to serve with the application. The default paths point to the project's `public` directory. See more in the [Assets configuration](#assets-configuration) section. | | `styles` | An array of CSS files to add to the global context of the project. Angular CLI supports CSS imports and all major CSS preprocessors. See more in the [Styles and scripts configuration](#styles-and-scripts-configuration) section. | | `stylePreprocessorOptions` | An object containing option-value pairs to pass to style preprocessors. See more in the [Styles and scripts configuration](#styles-and-scripts-configuration) section. | | `scripts` | An object containing JavaScript files to add to the application. The scripts are loaded exactly as if you had added them in a `<script>` tag inside `index.html`. See more in the [Styles and scripts configuration](#styles-and-scripts-configuration) section. | | `budgets` | Default size-budget type and thresholds for all or parts of your application. You can configure the builder to report a warning or an error when the output reaches or exceeds a threshold size. See [Configure size budgets](tools/cli/build#configure-size-budgets). | | `fileReplacements` | An object containing files and their compile-time replacements. See more in [Configure target-specific file replacements](tools/cli/build#configure-target-specific-file-replacements). | | `index` | A base HTML document which loads the application. See more in [Index configuration](#index-configuration). |
006234
### Source map configuration The `sourceMap` builder option can be either a boolean or an object for more fine-tune configuration to control the source maps of an application. | Options | Details | Value type | Default value | |:--- |:--- |:--- |:--- | | `scripts` | Output source maps for all scripts. | `boolean` | `true` | | `styles` | Output source maps for all styles. | `boolean` | `true` | | `vendor` | Resolve vendor packages source maps. | `boolean` | `false` | | `hidden` | Omit link to sourcemaps from the output JavaScript. | `boolean` | `false` | The example below shows how to toggle one or more values to configure the source map outputs: <docs-code language="json"> { "projects": { "my-app": { "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "sourceMap": { "scripts": true, "styles": false, "hidden": true, "vendor": true } } } } } } } </docs-code> HELPFUL: When using hidden source maps, source maps are not referenced in the bundle. These are useful if you only want source maps to map stack traces in error reporting tools without showing up in browser developer tools. Note that even though `hidden` prevents the source map from being linked in the output bundle, your deployment process must take care not to serve the generated sourcemaps in production, or else the information is still leaked. ### Index configuration Configures generation of the application's HTML index. The `index` option can be either a string or an object for more fine-tune configuration. When supplying the value as a string the filename of the specified path will be used for the generated file and will be created in the root of the application's configured output path. #### Index options | Options | Details | Value type | Default value | |:--- |:--- |:--- |:--- | | `input` | The path of a file to use for the application's generated HTML index. | `string` | None (required) | | `output` | The output path of the application's generated HTML index file. The full provided path will be used and will be considered relative to the application's configured output path. | `string` | `index.html` | ### Output path configuration The `outputPath` option can be either a String which will be used as the `base` value or an Object for more fine-tune configuration. Several options can be used to fine-tune the output structure of an application. | Options | Details | Value type | Default value | |:--- |:--- |:--- |:--- | | `base` | Specify the output path relative to workspace root. | `string` | | | `browser` | The output directory name for your browser build is within the base output path. This can be safely served to users. | `string` | `browser` | | `server` | The output directory name of your server build within the output path base. | `string` | `server` | | `media` | The output directory name for your media files located within the output browser directory. These media files are commonly referred to as resources in CSS files. | `string` | `media` |
006235
# Workspace and project file structure You develop applications in the context of an Angular workspace. A workspace contains the files for one or more projects. A project is the set of files that comprise an application or a shareable library. The Angular CLI `ng new` command creates a workspace. <docs-code language="shell"> ng new my-project </docs-code> When you run this command, the CLI installs the necessary Angular npm packages and other dependencies in a new workspace, with a root-level application named *my-project*. By default, `ng new` creates an initial skeleton application at the root level of the workspace, along with its end-to-end tests. The skeleton is for a simple welcome application that is ready to run and easy to modify. The root-level application has the same name as the workspace, and the source files reside in the `src/` subfolder of the workspace. This default behavior is suitable for a typical "multi-repo" development style where each application resides in its own workspace. Beginners and intermediate users are encouraged to use `ng new` to create a separate workspace for each application. Angular also supports workspaces with [multiple projects](#multiple-projects). This type of development environment is suitable for advanced users who are developing shareable libraries, and for enterprises that use a "monorepo" development style, with a single repository and global configuration for all Angular projects. To set up a monorepo workspace, you should skip creating the root application. See [Setting up for a multi-project workspace](#multiple-projects) below. ## Workspace configuration files All projects within a workspace share a [configuration](reference/configs/workspace-config). The top level of the workspace contains workspace-wide configuration files, configuration files for the root-level application, and subfolders for the root-level application source and test files. | Workspace configuration files | Purpose | |:--- |:--- | | `.editorconfig` | Configuration for code editors. See [EditorConfig](https://editorconfig.org). | | `.gitignore` | Specifies intentionally untracked files that [Git](https://git-scm.com) should ignore. | | `README.md` | Documentation for the workspace. | | `angular.json` | CLI configuration for all projects in the workspace, including configuration options for how to build, serve, and test each project. For details, see [Angular Workspace Configuration](reference/configs/workspace-config). | | `package.json` | Configures [npm package dependencies](reference/configs/npm-packages) that are available to all projects in the workspace. See [npm documentation](https://docs.npmjs.com/files/package.json) for the specific format and contents of this file. | | `package-lock.json` | Provides version information for all packages installed into `node_modules` by the npm client. See [npm documentation](https://docs.npmjs.com/files/package-lock.json) for details. | | `src/` | Source files for the root-level application project. | | `public/` | Contains image and other asset files to be served as static files by the dev server and copied as-is when you build your application. | | `node_modules/` | Installed [npm packages](reference/configs/npm-packages) for the entire workspace. Workspace-wide `node_modules` dependencies are visible to all projects. | | `tsconfig.json` | The base [TypeScript](https://www.typescriptlang.org) configuration for projects in the workspace. All other configuration files inherit from this base file. For more information, see the [relevant TypeScript documentation](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#tsconfig-bases). | ## Application project files By default, the CLI command `ng new my-app` creates a workspace folder named "my-app" and generates a new application skeleton in a `src/` folder at the top level of the workspace. A newly generated application contains source files for a root module, with a root component and template. When the workspace file structure is in place, you can use the `ng generate` command on the command line to add functionality and data to the application. This initial root-level application is the *default app* for CLI commands (unless you change the default after creating [additional apps](#multiple-projects)). For a single-application workspace, the `src` subfolder of the workspace contains the source files (application logic, data, and assets) for the root application. For a multi-project workspace, additional projects in the `projects` folder contain a `project-name/src/` subfolder with the same structure. ### Application source files Files at the top level of `src/` support running your application. Subfolders contain the application source and application-specific configuration. | Application support files | Purpose | |:--- |:--- | | `app/` | Contains the component files in which your application logic and data are defined. See details [below](#app-src). | | `favicon.ico` | An icon to use for this application in the bookmark bar. | | `index.html` | The main HTML page that is served when someone visits your site. The CLI automatically adds all JavaScript and CSS files when building your app, so you typically don't need to add any `<script>` or`<link>` tags here manually. | | `main.ts` | The main entry point for your application. | | `styles.css` | Global CSS styles applied to the entire application. | Inside the `src` folder, the `app` folder contains your project's logic and data. Angular components, templates, and styles go here. | `src/app/` files | Purpose | |:--- |:--- | | `app.config.ts` | Defines the application configuration that tells Angular how to assemble the application. As you add more providers to the app, they should be declared here.<br><br>*Only generated when using the `--standalone` option.* | | `app.component.ts` | Defines the application's root component, named `AppComponent`. The view associated with this root component becomes the root of the view hierarchy as you add components and services to your application. | | `app.component.html` | Defines the HTML template associated with `AppComponent`. | | `app.component.css` | Defines the CSS stylesheet for `AppComponent`. | | `app.component.spec.ts` | Defines a unit test for `AppComponent`. | | `app.module.ts` | Defines the root module, named `AppModule`, that tells Angular how to assemble the application. Initially declares only the `AppComponent`. As you add more components to the app, they must be declared here.<br><br>*Only generated when using the `--standalone false` option.* | | `app.routes.ts` | Defines the application's routing configuration. | ### Application configuration files Application-specific configuration files for the root application reside at the workspace root level. For a multi-project workspace, project-specific configuration files are in the project root, under `projects/project-name/`. Project-specific [TypeScript](https://www.typescriptlang.org) configuration files inherit from the workspace-wide `tsconfig.json`. | Application-specific configuration files | Purpose | |:--- |:--- | | `tsconfig.app.json` | Application-specific [TypeScript configuration](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html), including [Angular compiler options](reference/configs/angular-compiler-options). | | `tsconfig.spec.json` | [TypeScript configuration](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) for application tests. |
006250
# Optional chain not nullable This diagnostic detects when the left side of an optional chain operation (`.?`) does not include `null` or `undefined` in its type in Angular templates. <docs-code language="typescript"> import {Component} from '@angular/core'; @Component({ // Print the user's name safely, even if `user` is `null` or `undefined`. template: `<div>User name: {{ user?.name }}</div>`, }) class MyComponent { // `user` is declared as an object which *cannot* be `null` or `undefined`. user: { name: string } = { name: 'Angelino' }; } </docs-code> ## What's wrong with that? Using the optional chain operator with a non-nullable input has no effect and is indicative of a discrepancy between the allowed type of a value and how it is presented in the template. A developer might reasonably assume that the output of the optional chain operator is could be `null` or `undefined`, but it will never actually be either of those values. This can lead to confusion about the expected output of the program. ## What should I do instead? Update the template and declared type to be in sync. Double-check the type of the input and confirm whether it is actually expected to be nullable. If the input should be nullable, add `null` or `undefined` to its type to indicate this. <docs-code language="typescript"> import {Component} from '@angular/core'; @Component({ // If `user` is nullish, `name` won't be evaluated and the expression will // return the nullish value (`null` or `undefined`). template: `<div>{{ user?.name }}</div>`, }) class MyComponent { user: { name: string } | null = { name: 'Angelino' }; } </docs-code> If the input should not be nullable, delete the `?` operator. <docs-code language="typescript"> import {Component} from '@angular/core'; @Component({ // Template always displays `name` as `user` is guaranteed to never be `null` // or `undefined`. template: `<div>{{ foo.bar }}</div>`, }) class MyComponent { user: { name: string } = { name: 'Angelino' }; } </docs-code> ## Configuration requirements [`strictTemplates`](tools/cli/template-typecheck#strict-mode) must be enabled for any extended diagnostic to emit. [`strictNullChecks`](tools/cli/template-typecheck#strict-null-checks) must also be enabled to emit `optionalChainNotNullable` diagnostics. ## What if I can't avoid this? This diagnostic can be disabled by editing the project's `tsconfig.json` file: <docs-code language="json"> { "angularCompilerOptions": { "extendedDiagnostics": { "checks": { "optionalChainNotNullable": "suppress" } } } } </docs-code> See [extended diagnostic configuration](extended-diagnostics#configuration) for more info.
006253
# Missing control flow directive This diagnostics ensures that a standalone component which uses known control flow directives (such as `*ngIf`, `*ngFor`, or `*ngSwitch`) in a template, also imports those directives either individually or by importing the `CommonModule`. <docs-code language="typescript"> import {Component} from '@angular/core'; @Component({ standalone: true, // Template uses `*ngIf`, but no corresponding directive imported. imports: [], template: `<div *ngIf="visible">Hi</div>`, }) class MyComponent {} </docs-code> ## What's wrong with that? Using a control flow directive without importing it will fail at runtime, as Angular attempts to bind to an `ngIf` property of the HTML element, which does not exist. ## What should I do instead? Make sure that a corresponding control flow directive is imported. A directive can be imported individually: <docs-code language="typescript"> import {Component} from '@angular/core'; import {NgIf} from '@angular/common'; @Component({ standalone: true, imports: [NgIf], template: `<div *ngIf="visible">Hi</div>`, }) class MyComponent {} </docs-code> or you could import the entire `CommonModule`, which contains all control flow directives: <docs-code language="typescript"> import {Component} from '@angular/core'; import {CommonModule} from '@angular/common'; @Component({ standalone: true, imports: [CommonModule], template: `<div *ngIf="visible">Hi</div>`, }) class MyComponent {} </docs-code> ## Configuration requirements [`strictTemplates`](tools/cli/template-typecheck#strict-mode) must be enabled for any extended diagnostic to emit. `missingControlFlowDirective` has no additional requirements beyond `strictTemplates`. ## What if I can't avoid this? This diagnostic can be disabled by editing the project's `tsconfig.json` file: <docs-code language="json"> { "angularCompilerOptions": { "extendedDiagnostics": { "checks": { "missingControlFlowDirective": "suppress" } } } } </docs-code> See [extended diagnostic configuration](extended-diagnostics#configuration) for more info.
006257
# Track expression resulted in duplicated keys for a given collection. A track expression specified in the `@for` loop evaluated to duplicated keys for a given collection, ex.: ```typescript @Component({ template: `@for (item of items; track item.value) {{{item.value}}}`, }) class TestComponent { items = [{key: 1, value: 'a'}, {key: 2, value: 'b'}, {key: 3, value: 'a'}]; } ``` In the provided example the `item.key` tracking expression will find two duplicate keys `a` (at index 0 and 2). Duplicate keys are problematic from the correctness point of view: since the `@for` loop can't uniquely identify items it might choose DOM nodes corresponding to _another_ item (with the same key) when performing DOM moves or destroy. There is also performance penalty associated with duplicated keys - internally Angular must use more sophisticated and slower data structures while repeating over collections with duplicated keys. ## Fixing the error Change the tracking expression such that it uniquely identifies an item in a collection. In the discussed example the correct track expression would use the unique `key` property (`item.key`): ```typescript @Component({ template: `@for (item of items; track item.key) {{{item.value}}}`, }) class TestComponent { items = [{key: 1, value: 'a'}, {key: 2, value: 'b'}, {key: 3, value: 'a'}]; } ```
006270
# Invalid Element One or more elements cannot be resolved during compilation because the element is not defined by the HTML spec, or there is no component or directive with such element selector. HELPFUL: This is the compiler equivalent of a common runtime error `NG0304: '${tagName}' is not a known element: ...`. ## Debugging the error Use the element name in the error to find the file(s) where the element is being used. Check that the name and selector are correct. Make sure that the component is correctly imported inside your NgModule or standalone component, by checking its presence in the `imports` field. If the component is declared in an NgModule (meaning that it is not standalone) make sure that it is exported correctly from it, by checking its presence in the `exports` field. When using custom elements or web components, ensure that you add [`CUSTOM_ELEMENTS_SCHEMA`](api/core/CUSTOM_ELEMENTS_SCHEMA) to the application module. If this does not resolve the error, check the imported libraries for any recent changes to the exports and properties you are using, and restart your server.
006273
# No Provider Found <docs-video src="https://www.youtube.com/embed/lAlOryf1-WU"/> You see this error when you try to inject a service but have not declared a corresponding provider. A provider is a mapping that supplies a value that you can inject into the constructor of a class in your application. Read more on providers in our [Dependency Injection guide](guide/di). ## Debugging the error Work backwards from the object where the error states that a provider is missing: `No provider for ${this}!`. This is commonly thrown in services, which require non-existing providers. To fix the error ensure that your service is registered in the list of providers of an `NgModule` or has the `@Injectable` decorator with a `providedIn` property at top. The most common solution is to add a provider in `@Injectable` using `providedIn`: <docs-code language="typescript"> @Injectable({ providedIn: 'app' }) </docs-code>
006274
# Export Not Found <docs-video src="https://www.youtube.com/embed/fUSAg4kp2WQ"/> Angular can't find a directive with `{{ PLACEHOLDER }}` export name. The export name is specified in the `exportAs` property of the directive decorator. This is common when using FormsModule or Material modules in templates and you've forgotten to import the corresponding modules. HELPFUL: This is the runtime equivalent of a common compiler error [NG8003: No directive found with export](errors/NG8003). ## Debugging the error Use the export name to trace the templates or modules using this export. Ensure that all dependencies are properly imported and declared in your NgModules. For example, if the export not found is `ngForm`, we need to import `FormsModule` and declare it in the list of imports in `*.module.ts` to resolve the error. <docs-code language="typescript"> import { FormsModule } from '@angular/forms'; @NgModule({ … imports: [ FormsModule, … </docs-code> If you recently added an import, you may need to restart your server to see these changes.
006275
# Missing value accessor For all custom form controls, you must register a value accessor. Here's an example of how to provide one: ```typescript providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MyInputField), multi: true, } ] ``` ## Debugging the error As described above, your control was expected to have a value accessor, but was missing one. However, there are many different reasons this can happen in practice. Here's a listing of some known problems leading to this error. 1. If you **defined** a custom form control, did you remember to provide a value accessor? 1. Did you put `ngModel` on an element with no value, or an **invalid element** (e.g. `<div [(ngModel)]="foo">`)? 1. Are you using a custom form control declared inside an `NgModule`? if so, make sure you are **importing** the `NgModule`. 1. Are you using `ngModel` with a third-party custom form control? Check whether that control provides a value accessor. If not, use **`ngDefaultControl`** on the control's element. 1. Are you **testing** a custom form control? Be sure to configure your testbed to know about the control. You can do so with `Testbed.configureTestingModule`. 1. Are you using **Nx and Module Federation** with Webpack? Your `webpack.config.js` may require [extra configuration](https://github.com/angular/angular/issues/43821#issuecomment-1054845431) to ensure the forms package is shared.
006277
# Hydration with unsupported Zone.js instance This warning means that the hydration was enabled for an application that was configured to use an unsupported version of Zone.js: either a custom or a "noop" one (see more info [here](api/core/BootstrapOptions#ngZone)). Hydration relies on a signal from Zone.js when it becomes stable inside an application, so that Angular can start the serialization process on the server or post-hydration cleanup on the client (to remove DOM nodes that remained unclaimed). Providing a custom or a "noop" Zone.js implementation may lead to a different timing of the "stable" event, thus triggering the serialization or the cleanup too early or too late. This is not yet a fully supported configuration. If you use a custom Zone.js implementation, make sure that the "onStable" event is emitted at the right time and does not result in incorrect application behavior with hydration. More information about hydration can be found in the [hydration guide](guide/hydration).
006279
# Missing Reference Target <docs-video src="https://www.youtube.com/embed/fUSAg4kp2WQ"/> Angular can't find a directive with `{{ PLACEHOLDER }}` export name. This is common with a missing import or a missing [`exportAs`](api/core/Directive#exportAs) on a directive. HELPFUL: This is the compiler equivalent of a common runtime error [NG0301: Export Not Found](errors/NG0301). ## Debugging the error Use the string name of the export not found to trace the templates or modules using this export. Ensure that all dependencies are properly imported and declared in our Modules. For example, if the export not found is `ngForm`, we will need to import `FormsModule` and declare it in our list of imports in `*.module.ts` to resolve the missing export error. <docs-code language="typescript"> import { FormsModule } from '@angular/forms'; @NgModule({ … imports: [ FormsModule, … </docs-code> If you recently added an import, you will need to restart your server to see these changes.
006281
# `inject()` must be called from an injection context You see this error when you try to use the [`inject`](api/core/inject) function outside of the allowed [injection context](guide/di/dependency-injection-context). The injection context is available during the class creation and initialization. It is also available to functions used with `runInInjectionContext`. In practice the `inject()` calls are allowed in a constructor, a constructor parameter and a field initializer: ```typescript @Injectable({providedIn: 'root'}) export class Car { radio: Radio|undefined; // OK: field initializer spareTyre = inject(Tyre); constructor() { // OK: constructor body this.radio = inject(Radio); } } ``` It is also legal to call [`inject`](api/core/inject) from a provider's factory: ```typescript providers: [ {provide: Car, useFactory: () => { // OK: a class factory const engine = inject(Engine); return new Car(engine); }} ] ``` Calls to the [`inject`](api/core/inject) function outside of the class creation or `runInInjectionContext` will result in error. Most notably, calls to `inject()` are disallowed after a class instance was created, in methods (including lifecycle hooks): ```typescript @Component({ ... }) export class CarComponent { ngOnInit() { // ERROR: too late, the component instance was already created const engine = inject(Engine); engine.start(); } } ``` ## Debugging the error Work backwards from the stack trace of the error to identify a place where the disallowed call to `inject()` is located. To fix the error move the [`inject`](api/core/inject) call to an allowed place (usually a class constructor or a field initializer). **Note:** If you are running in a test context, `TestBed.runInInjectionContext` will enable `inject()` to succeed. ```typescript TestBed.runInInjectionContext(() => { // ... }); ```
006286
# Missing Iterable Differ `NgFor` could not find an iterable differ for the value passed in. Make sure it's an iterable, like an `Array`. ## Debugging the error When using ngFor in a template, you must use some type of Iterable, like `Array`, `Set`, `Map`, etc. If you're trying to iterate over the keys in an object, you should look at the [KeyValue pipe](/api/common/KeyValuePipe) instead.
006288
# Application remains unstable This warning only appears in the browser during the hydration process when it's enabled on the client but the application remains unstable for an extended period of time (over 10 seconds). Typically that happens when there are some pending microtasks or macrotasks on a page. Angular Hydration relies on a signal from `ApplicationRef.isStable` when it becomes stable inside an application: - during the server-side rendering (SSR) to start the serialization process - in a browser this signal is used to start the post-hydration cleanup to remove DOM nodes that remained unclaimed This warning is displayed when `ApplicationRef.isStable` does not emit `true` within 10 seconds. If this behavior is intentional and your application stabilizes later, you could choose to ignore this warning. ## Applications that use zone.js Applications that use zone.js may have various factors contributing to delays in stability. These may include pending HTTP requests, timers (`setInterval`, `setTimeout`) or some logic that continuously invokes `requestAnimationFrame`. ### Macrotasks Macrotasks include functions like `setInterval`, `setTimeout`, `requestAnimationFrame`, etc. If one of these functions is called during the initialization phase of the application or in bootstrapped components, it may delay the moment when the application becomes stable. ```typescript @Component({ standalone: true, selector: 'app', template: ``, }) class SimpleComponent { constructor() { setInterval(() => { ... }, 1000) // or setTimeout(() => { ... }, 10_000) } } ``` If these functions must be called during the initialization phase, invoking them outside the Angular zone resolves the problem: ```typescript class SimpleComponent { constructor() { const ngZone = inject(NgZone); ngZone.runOutsideAngular(() => { setInterval(() => {}, 1000); }); } } ``` ### Third-party libraries Some third-party libraries can also produce long-running asynchronous tasks, which may delay application stability. The recommendation is to invoke relevant library code outside of the zone as described above. ### Running code after an application becomes stable You can run a code that sets up asynchronous tasks once an application becomes stable: ```typescript class SimpleComponent { constructor() { const applicationRef = inject(ApplicationRef); applicationRef.isStable.pipe( first((isStable) => isStable) ).subscribe(() => { // Note that we don't need to use `runOutsideAngular` because `isStable` // emits events outside of the Angular zone when it's truthy (falsy values // are emitted inside the Angular zone). setTimeout(() => { ... }); }); } } ``` ## Zoneless applications In zoneless scenarios, stability might be delayed by an application code inside of an `effect` running in an infinite loop (potentially because signals used in effect functions keep changing) or a pending HTTP request. Developers may also explicitly contribute to indicating the application's stability by using the [`PendingTasks`](/api/core/PendingTasks) service. If you use the mentioned APIs in your application, make sure you invoke a function to mark the task as completed.
006294
# Tracking expression caused re-creation of the DOM structure. The identity track expression specified in the `@for` loop caused re-creation of the DOM corresponding to _all_ items. This is a very expensive operation that commonly occurs when working with immutable data structures. For example: ```typescript @Component({ template: ` <button (click)="toggleAllDone()">All done!</button> <ul> @for (todo of todos; track todo) { <li>{{todo.task}}</li> } </ul> `, }) export class App { todos = [ { id: 0, task: 'understand trackBy', done: false }, { id: 1, task: 'use proper tracking expression', done: false }, ]; toggleAllDone() { this.todos = this.todos.map(todo => ({ ...todo, done: true })); } } ``` In the provided example, the entire list with all the views (DOM nodes, Angular directives, components, queries, etc.) are re-created (!) after toggling the "done" status of items. Here, a relatively inexpensive binding update to the `done` property would suffice. Apart from having a high performance penalty, re-creating the DOM tree results in loss of state in the DOM elements (ex.: focus, text selection, sites loaded in an iframe, etc.). ## Fixing the error Change the tracking expression such that it uniquely identifies an item in a collection, regardless of its object identity. In the discussed example, the correct track expression would use the unique `id` property (`item.id`): ```typescript @Component({ template: ` <button (click)="toggleAllDone()">All done!</button> <ul> @for (todo of todos; track todo.id) { <li>{{todo.task}}</li> } </ul> `, }) export class App { todos = [ { id: 0, task: 'understand trackBy', done: false }, { id: 1, task: 'use proper tracking expression', done: false }, ]; toggleAllDone() { this.todos = this.todos.map(todo => ({ ...todo, done: true })); } } ```
006305
ro-list.component.ts" path="adev/src/content/examples/styleguide/src/05-17/app/heroes/hero-list/hero-list.component.ts" visibleRegion="example"/> ### Initialize inputs #### Style 05-18 TypeScript's `--strictPropertyInitialization` compiler option ensures that a class initializes its properties during construction. When enabled, this option causes the TypeScript compiler to report an error if the class does not set a value to any property that is not explicitly marked as optional. By design, Angular treats all `@Input` properties as optional. When possible, you should satisfy `--strictPropertyInitialization` by providing a default value. <docs-code header="app/heroes/hero/hero.component.ts" path="adev/src/content/examples/styleguide/src/05-18/app/heroes/hero/hero.component.ts" visibleRegion="example"/> If the property is hard to construct a default value for, use `?` to explicitly mark the property as optional. <docs-code header="app/heroes/hero/hero.component.ts" path="adev/src/content/examples/styleguide/src/05-18/app/heroes/hero/hero.component.optional.ts" visibleRegion="example"/> You may want to have a required `@Input` field, meaning all your component users are required to pass that attribute. In such cases, use a default value. Just suppressing the TypeScript error with `!` is insufficient and should be avoided because it will prevent the type checker from ensuring the input value is provided. <docs-code header="app/heroes/hero/hero.component.ts" path="adev/src/content/examples/styleguide/src/05-18/app/heroes/hero/hero.component.avoid.ts" visibleRegion="example"/> ## Directives ### Use directives to enhance an element #### Style 06-01 **Do** use attribute directives when you have presentation logic without a template. **Why**? <br /> Attribute directives don't have an associated template. **Why**? <br /> An element may have more than one attribute directive applied. <docs-code header="app/shared/highlight.directive.ts" path="adev/src/content/examples/styleguide/src/06-01/app/shared/highlight.directive.ts" visibleRegion="example"/> <docs-code header="app/app.component.html" path="adev/src/content/examples/styleguide/src/06-01/app/app.component.html"/> ### `HostListener`/`HostBinding` decorators versus `host` metadata #### Style 06-03 **Consider** preferring the `@HostListener` and `@HostBinding` to the `host` property of the `@Directive` and `@Component` decorators. **Do** be consistent in your choice. **Why**? <br /> The property associated with `@HostBinding` or the method associated with `@HostListener` can be modified only in a single place —in the directive's class. If you use the `host` metadata property, you must modify both the property/method declaration in the directive's class and the metadata in the decorator associated with the directive. <docs-code header="app/shared/validator.directive.ts" path="adev/src/content/examples/styleguide/src/06-03/app/shared/validator.directive.ts"/> Compare with the less preferred `host` metadata alternative. **Why**? <br /> The `host` metadata is only one term to remember and doesn't require extra ES imports. <docs-code header="app/shared/validator2.directive.ts" path="adev/src/content/examples/styleguide/src/06-03/app/shared/validator2.directive.ts"/> ## Services ### Services are singletons #### Style 07-01 **Do** use services as singletons within the same injector. Use them for sharing data and functionality. **Why**? <br /> Services are ideal for sharing methods across a feature area or an app. **Why**? <br /> Services are ideal for sharing stateful in-memory data. <docs-code header="app/heroes/shared/hero.service.ts" path="adev/src/content/examples/styleguide/src/07-01/app/heroes/shared/hero.service.ts" visibleRegion="example"/> ### Providing a service #### Style 07-03 **Do** provide a service with the application root injector in the `@Injectable` decorator of the service. **Why**? <br /> The Angular injector is hierarchical. **Why**? <br /> When you provide the service to a root injector, that instance of the service is shared and available in every class that needs the service. This is ideal when a service is sharing methods or state. **Why**? <br /> When you register a service in the `@Injectable` decorator of the service, optimization tools such as those used by the [Angular CLI's](cli) production builds can perform tree shaking and remove services that aren't used by your app. **Why**? <br /> This is not ideal when two different components need different instances of a service. In this scenario it would be better to provide the service at the component level that needs the new and separate instance. <docs-code header="src/app/treeshaking/service.ts" path="adev/src/content/examples/dependency-injection/src/app/tree-shaking/service.ts"/> ### Use the @Injectable() class decorator #### Style 07-04 **Do** use the `@Injectable()` class decorator instead of the `@Inject` parameter decorator when using types as tokens for the dependencies of a service. **Why**? <br /> The Angular Dependency Injection \(DI\) mechanism resolves a service's own dependencies based on the declared types of that service's constructor parameters. **Why**? <br /> When a service accepts only dependencies associated with type tokens, the `@Injectable()` syntax is much less verbose compared to using `@Inject()` on each individual constructor parameter. <docs-code header="app/heroes/shared/hero-arena.service.ts" path="adev/src/content/examples/styleguide/src/07-04/app/heroes/shared/hero-arena.service.avoid.ts" visibleRegion="example"/> <docs-code header="app/heroes/shared/hero-arena.service.ts" path="adev/src/content/examples/styleguide/src/07-04/app/heroes/shared/hero-arena.service.ts" visibleRegion="example"/> ## Data Services ### Talk to the server through a service #### Style 08-01 **Do** refactor logic for making data operations and interacting with data to a service. **Do** make data services responsible for XHR calls, local storage, stashing in memory, or any other data operations. **Why**? <br /> The component's responsibility is for the presentation and gathering of information for the view. It should not care how it gets the data, just that it knows who to ask for it. Separating the data services moves the logic on how to get it to the data service, and lets the component be simpler and more focused on the view. **Why**? <br /> This makes it easier to test \(mock or real\) the data calls when testing a component that uses a data service. **Why**? <br /> The details of data management, such as headers, HTTP methods, caching, error handling, and retry logic, are irrelevant to components and other data consumers. A data service encapsulates these details. It's easier to evolve these details inside the service without affecting its consumers. And it's easier to test the consumers with mock service implementations. ## Lifecycle hooks Use Lifecycle hooks to tap into important events exposed by Angular. ### Implement lifecycle hook interfaces #### Style 09-01 **Do** implement the lifecycle hook interfaces. **Why**? <br /> Lifecycle interfaces prescribe typed method signatures. Use those signatures to flag spelling and syntax mistakes. <docs-code header="app/heroes/shared/hero-button/hero-button.component.ts" path="adev/src/content/examples/styleguide/src/09-01/app/heroes/shared/hero-button/hero-button.component.avoid.ts" visibleRegion="example"/> <docs-code header="app/heroes/shared/hero-button/hero-button.component.ts" path="adev/src/content/examples/styleguide/src/09-01/app/heroes/shared/hero-button/hero-button.component.ts" visibleRegion="example"/> ## Appendix Useful tools and tips for Angular. ### File templates and snippets #### Style A-02 **Do** use file templates or snippets to help follow consistent styles and patterns. Here are templates and/or snippets for some of the web development editors and IDEs. **Consider** using [snippets](https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2) for [Visual Studio Code](https://code.visualstudio.com) that follow these styles and guidelines. <a href="https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2"> <img alt="Use Extension" src="assets/images/guide/styleguide/use-extension.gif"> </a> **Consider** using [snippets](https://github.com/orizens/sublime-angular2-snippets) for [Sublime Text](https://www.sublimetext.com) that follow these styles and guidelines. **Consider** using [snippets](https://github.com/mhartington/vim-angular2-snippets) for [Vim](https://www.vim.org) that follow these styles and guidelines.
006307
# Resolving zone pollution **Zone.js** is a signaling mechanism that Angular uses to detect when an application state might have changed. It captures asynchronous operations like `setTimeout`, network requests, and event listeners. Angular schedules change detection based on signals from Zone.js. In some cases scheduled [tasks](https://developer.mozilla.org/docs/Web/API/HTML_DOM_API/Microtask_guide#tasks) or [microtasks](https://developer.mozilla.org/docs/Web/API/HTML_DOM_API/Microtask_guide#microtasks) don’t make any changes in the data model, which makes running change detection unnecessary. Common examples are: * `requestAnimationFrame`, `setTimeout` or `setInterval` * Task or microtask scheduling by third-party libraries This section covers how to identify such conditions, and how to run code outside the Angular zone to avoid unnecessary change detection calls. ## Identifying unnecessary change detection calls You can detect unnecessary change detection calls using Angular DevTools. Often they appear as consecutive bars in the profiler’s timeline with source `setTimeout`, `setInterval`, `requestAnimationFrame`, or an event handler. When you have limited calls within your application of these APIs, the change detection invocation is usually caused by a third-party library. <img alt="Angular DevTools profiler preview showing Zone pollution" src="assets/images/best-practices/runtime-performance/zone-pollution.png"> In the image above, there is a series of change detection calls triggered by event handlers associated with an element. That’s a common challenge when using third-party, non-native Angular components, which do not alter the default behavior of `NgZone`. ## Run tasks outside `NgZone` In such cases, you can instruct Angular to avoid calling change detection for tasks scheduled by a given piece of code using [NgZone](/api/core/NgZone). <docs-code header="Run outside of the Zone" language='ts' linenums> import { Component, NgZone, OnInit } from '@angular/core'; @Component(...) class AppComponent implements OnInit { constructor(private ngZone: NgZone) {} ngOnInit() { this.ngZone.runOutsideAngular(() => setInterval(pollForUpdates), 500); } } </docs-code> The preceding snippet instructs Angular to call `setInterval` outside the Angular Zone and skip running change detection after `pollForUpdates` runs. Third-party libraries commonly trigger unnecessary change detection cycles when their APIs are invoked within the Angular zone. This phenomenon particularly affects libraries that setup event listeners or initiate other tasks (such as timers, XHR requests, etc.). Avoid these extra cycles by calling library APIs outside the Angular zone: <docs-code header="Move the plot initialization outside of the Zone" language='ts' linenums> import { Component, NgZone, OnInit } from '@angular/core'; import * as Plotly from 'plotly.js-dist-min'; @Component(...) class AppComponent implements OnInit { constructor(private ngZone: NgZone) {} ngOnInit() { this.ngZone.runOutsideAngular(() => { Plotly.newPlot('chart', data); }); } } </docs-code> Running `Plotly.newPlot('chart', data);` within `runOutsideAngular` instructs the framework that it shouldn’t run change detection after the execution of tasks scheduled by the initialization logic. For example, if `Plotly.newPlot('chart', data)` adds event listeners to a DOM element, Angular does not run change detection after the execution of their handlers. But sometimes, you may need to listen to events dispatched by third-party APIs. In such cases, it's important to remember that those event listeners will also execute outside of the Angular zone if the initialization logic was done there: <docs-code header="Check whether the handler is called outside of the Zone" language='ts' linenums> import { Component, NgZone, OnInit, output } from '@angular/core'; import * as Plotly from 'plotly.js-dist-min'; @Component(...) class AppComponent implements OnInit { plotlyClick = output<Plotly.PlotMouseEvent>(); constructor(private ngZone: NgZone) {} ngOnInit() { this.ngZone.runOutsideAngular(() => { this.createPlotly(); }); } private async createPlotly() { const plotly = await Plotly.newPlot('chart', data); plotly.on('plotly_click', (event: Plotly.PlotMouseEvent) => { // This handler will be called outside of the Angular zone because // the initialization logic is also called outside of the zone. To check // whether we're in the Angular zone, we can call the following: console.log(NgZone.isInAngularZone()); this.plotlyClick.emit(event); }); } } </docs-code> If you need to dispatch events to parent components and execute specific view update logic, you should consider re-entering the Angular zone to instruct the framework to run change detection or run change detection manually: <docs-code header="Re-enter the Angular zone when dispatching event" language='ts' linenums> import { Component, NgZone, OnInit, output } from '@angular/core'; import * as Plotly from 'plotly.js-dist-min'; @Component(...) class AppComponent implements OnInit { plotlyClick = output<Plotly.PlotMouseEvent>(); constructor(private ngZone: NgZone) {} ngOnInit() { this.ngZone.runOutsideAngular(() => { this.createPlotly(); }); } private async createPlotly() { const plotly = await Plotly.newPlot('chart', data); plotly.on('plotly_click', (event: Plotly.PlotMouseEvent) => { this.ngZone.run(() => { this.plotlyClick.emit(event); }); }); } } </docs-code> The scenario of dispatching events outside of the Angular zone may also arise. It's important to remember that triggering change detection (for example, manually) may result to the creation/update of views outside of the Angular zone.
006310
# Skipping component subtrees JavaScript, by default, uses mutable data structures that you can reference from multiple different components. Angular runs change detection over your entire component tree to make sure that the most up-to-date state of your data structures is reflected in the DOM. Change detection is sufficiently fast for most applications. However, when an application has an especially large component tree, running change detection across the whole application can cause performance issues. You can address this by configuring change detection to only run on a subset of the component tree. If you are confident that a part of the application is not affected by a state change, you can use [OnPush](/api/core/ChangeDetectionStrategy) to skip change detection in an entire component subtree. ## Using `OnPush` OnPush change detection instructs Angular to run change detection for a component subtree **only** when: * The root component of the subtree receives new inputs as the result of a template binding. Angular compares the current and past value of the input with `==`. * Angular handles an event _(for example using event binding, output binding, or `@HostListener` )_ in the subtree's root component or any of its children whether they are using OnPush change detection or not. You can set the change detection strategy of a component to `OnPush` in the `@Component` decorator: ```ts import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, }) export class MyComponent {} ``` ## Common change detection scenarios This section examines several common change detection scenarios to illustrate Angular's behavior. ### An event is handled by a component with default change detection If Angular handles an event within a component without `OnPush` strategy, the framework executes change detection on the entire component tree. Angular will skip descendant component subtrees with roots using `OnPush`, which have not received new inputs. As an example, if we set the change detection strategy of `MainComponent` to `OnPush` and the user interacts with a component outside the subtree with root `MainComponent`, Angular will check all the pink components from the diagram below (`AppComponent`, `HeaderComponent`, `SearchComponent`, `ButtonComponent`) unless `MainComponent` receives new inputs: ```mermaid graph TD; app[AppComponent] --- header[HeaderComponent]; app --- main["MainComponent (OnPush)"]; header --- search[SearchComponent]; header --- button[ButtonComponent]; main --- login["LoginComponent (OnPush)"]; main --- details[DetailsComponent]; event>Event] --- search class app checkedNode class header checkedNode class button checkedNode class search checkedNode class event eventNode ``` ## An event is handled by a component with OnPush If Angular handles an event within a component with OnPush strategy, the framework will execute change detection within the entire component tree. Angular will ignore component subtrees with roots using OnPush, which have not received new inputs and are outside the component which handled the event. As an example, if Angular handles an event within `MainComponent`, the framework will run change detection in the entire component tree. Angular will ignore the subtree with root `LoginComponent` because it has `OnPush` and the event happened outside of its scope. ```mermaid graph TD; app[AppComponent] --- header[HeaderComponent]; app --- main["MainComponent (OnPush)"]; header --- search[SearchComponent]; header --- button[ButtonComponent]; main --- login["LoginComponent (OnPush)"]; main --- details[DetailsComponent]; event>Event] --- main class app checkedNode class header checkedNode class button checkedNode class search checkedNode class main checkedNode class details checkedNode class event eventNode ``` ## An event is handled by a descendant of a component with OnPush If Angular handles an event in a component with OnPush, the framework will execute change detection in the entire component tree, including the component’s ancestors. As an example, in the diagram below, Angular handles an event in `LoginComponent` which uses OnPush. Angular will invoke change detection in the entire component subtree including `MainComponent` (`LoginComponent`’s parent), even though `MainComponent` has `OnPush` as well. Angular checks `MainComponent` as well because `LoginComponent` is part of its view. ```mermaid graph TD; app[AppComponent] --- header[HeaderComponent]; app --- main["MainComponent (OnPush)"]; header --- search[SearchComponent]; header --- button[ButtonComponent]; main --- login["LoginComponent (OnPush)"]; main --- details[DetailsComponent]; event>Event] --- login class app checkedNode class header checkedNode class button checkedNode class search checkedNode class login checkedNode class main checkedNode class details checkedNode class event eventNode ``` ## New inputs to component with OnPush Angular will run change detection within a child component with `OnPush` when setting an input property as result of a template binding. For example, in the diagram below, `AppComponent` passes a new input to `MainComponent`, which has `OnPush`. Angular will run change detection in `MainComponent` but will not run change detection in `LoginComponent`, which also has `OnPush`, unless it receives new inputs as well. ```mermaid graph TD; app[AppComponent] --- header[HeaderComponent]; app --- main["MainComponent (OnPush)"]; header --- search[SearchComponent]; header --- button[ButtonComponent]; main --- login["LoginComponent (OnPush)"]; main --- details[DetailsComponent]; event>Parent passes new input to MainComponent] class app checkedNode class header checkedNode class button checkedNode class search checkedNode class main checkedNode class details checkedNode class event eventNode ``` ## Edge cases * **Modifying input properties in TypeScript code**. When you use an API like `@ViewChild` or `@ContentChild` to get a reference to a component in TypeScript and manually modify an `@Input` property, Angular will not automatically run change detection for OnPush components. If you need Angular to run change detection, you can inject `ChangeDetectorRef` in your component and call `changeDetectorRef.markForCheck()` to tell Angular to schedule a change detection. * **Modifying object references**. In case an input receives a mutable object as value and you modify the object but preserve the reference, Angular will not invoke change detection. That’s the expected behavior because the previous and the current value of the input point to the same reference.
006372
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg width="100%" height="100%" viewBox="0 0 600 445" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;stroke-linejoin:round;stroke-miterlimit:1.5;"><g id="NullInjector"><rect x="11.864" y="16.952" width="575.424" height="114.429" style="fill:#fff;stroke:#0159d3;stroke-width:3.81px;"/><text x="208.488px" y="67.96px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:30.514px;">NullInjector()</text><g transform="matrix(0.847458,0,0,0.847619,-81.3559,-80.5238)"><text x="286.27px" y="212px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:24px;">always throws an error unless</text><text x="334.768px" y="236.785px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:24px;">you use @Optional()</text></g></g><path d="M286.822,144.941l-7.161,0l11.017,-11.017l11.017,11.017l-7.161,0l0,38.992l-7.712,0l0,-38.992Z" style="fill:#0159d3;stroke:#0159d3;stroke-width:3.81px;"/><path d="M286.822,297.512l-7.161,0l11.017,-11.017l11.017,11.017l-7.161,0l0,38.993l-7.712,0l0,-38.993Z" style="fill:#0159d3;stroke:#0159d3;stroke-width:3.81px;"/><g id="Moduleinjector"><rect x="11.864" y="168.913" width="575.424" height="114.429" style="fill:#fff;stroke:#0159d3;stroke-width:3.81px;"/><text x="215.313px" y="211.956px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:25.429px;">ModuleInjector</text><g transform="matrix(0.847458,0,0,0.847619,-24.5763,-79.6762)"><text x="215.592px" y="385px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:24px;">(configured by PlatformModule)</text><text x="74.879px" y="409.785px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:24px;">has special things like DomSanitizer =&gt; platformBrowser()</text></g></g><g id="root"><rect x="10.599" y="320.428" width="577.966" height="113.581" style="fill:#fff;stroke:#0159d3;stroke-width:3.81px;"/><g transform="matrix(0.847458,0,0,0.847619,-59.3163,262.743)"><text x="280.144px" y="115px" style="font-family:'Courier';font-size:30px;">root</text><text x="370.158px" y="115px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:30px;">ModuleInjector</text></g><g transform="matrix(0.847458,0,0,0.847619,15.5593,-82.219)"><text x="165.889px" y="559px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:24px;">(configured by <tspan x="324.209px 338.014px 351.361px " y="559px 559px 559px ">You</tspan>rAppModule)</text><text x="5.57px" y="583.785px" style="font-family:'ArialMT', 'Arial', sans-serif;font-size:24px;">has things for your app  =&gt; bootstrapModule(Y<tspan x="498.332px 511.68px " y="583.785px 583.785px ">ou</tspan>rAppModule)</text></g></g></svg>
006380
@use 'sass:map'; @use 'external/npm/node_modules/@angular/material/index' as mat; @include mat.all-component-typographies(); @include mat.core(); html, body { padding: 0; margin: 0; } // Light theme $light-primary: mat.m2-define-palette(mat.$m2-grey-palette, 700, 200); $light-accent: mat.m2-define-palette(mat.$m2-blue-palette, 800); $light-theme: mat.m2-define-light-theme($light-primary, $light-accent); // Dark theme $dark-primary: mat.m2-define-palette(mat.$m2-blue-grey-palette, 50); $dark-accent: mat.m2-define-palette(mat.$m2-blue-palette, 200); $dark-theme: map.deep-merge( mat.m2-define-dark-theme($dark-primary, $dark-accent), ( 'color': ( 'background': ( background: #202124, card: #202124, ), 'foreground': ( text: #bcc5ce, ), ), 'background': ( background: #202124, card: #202124, ), 'foreground': ( 'text': #bcc5ce, ), ) ); .light-theme { @include mat.all-component-themes($light-theme); .mat-mdc-chip.mat-mdc-standard-chip { --mdc-chip-container-height: 24px; } } .dark-theme { color-scheme: dark; background: #202124; @include mat.all-component-themes($dark-theme); .mat-mdc-chip.mat-mdc-standard-chip { --mdc-chip-container-height: 24px; } } ng-devtools { .mdc-card { padding: 4px; } } .mat-mdc-menu-content { padding: 0 !important; }
006467
/** * @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, Component} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', standalone: false, }) export class AppComponent { counter = 0; constructor(private _cd: ChangeDetectorRef) {} increment(): void { this.counter++; this._cd.detectChanges(); } }
006471
/** * @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 {bootstrapApplication} from '@angular/platform-browser'; import {provideAnimations} from '@angular/platform-browser/animations'; import {provideRouter} from '@angular/router'; import {ApplicationEnvironment, ApplicationOperations} from 'ng-devtools'; import {DemoApplicationEnvironment} from '../../../src/demo-application-environment'; import {DemoApplicationOperations} from '../../../src/demo-application-operations'; import {AppComponent} from './app/app.component'; bootstrapApplication(AppComponent, { providers: [ provideAnimations(), provideRouter([ { path: '', loadComponent: () => import('./app/devtools-app/devtools-app.component').then((m) => m.DemoDevToolsComponent), pathMatch: 'full', }, { path: 'demo-app', loadChildren: () => import('./app/demo-app/demo-app.component').then((m) => m.ROUTES), }, ]), { provide: ApplicationOperations, useClass: DemoApplicationOperations, }, { provide: ApplicationEnvironment, useClass: DemoApplicationEnvironment, }, ], });
006486
/** * @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} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {MatDialog, MatDialogModule} from '@angular/material/dialog'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatInputModule} from '@angular/material/input'; import {RouterLink, RouterOutlet} from '@angular/router'; import {DialogComponent} from './dialog.component'; @Component({ selector: 'app-todo-demo', standalone: true, imports: [RouterLink, RouterOutlet, MatDialogModule, FormsModule], styles: [ ` nav { padding-top: 20px; padding-bottom: 10px; a { margin-right: 15px; text-decoration: none; } } .dialog-open-button { border: 1px solid #ccc; padding: 10px; margin-right: 20px; } `, ], template: ` <nav> <a routerLink="/demo-app/todos/app">Todos</a> <a routerLink="/demo-app/todos/about">About</a> </nav> <button class="dialog-open-button" (click)="openDialog()">Open dialog</button> <router-outlet></router-outlet> `, }) export class TodoAppComponent { name!: string; animal!: string; constructor(public dialog: MatDialog) {} openDialog(): void { const dialogRef = this.dialog.open(DialogComponent, { width: '250px', data: {name: this.name, animal: this.animal}, }); dialogRef.afterClosed().subscribe((result) => { // tslint:disable-next-line:no-console console.log('The dialog was closed'); this.animal = result; }); } } export const ROUTES = [ { path: 'todos', component: TodoAppComponent, children: [ { path: 'app', loadComponent: () => import('./home/todos.component').then((m) => m.TodosComponent), }, { path: 'about', loadComponent: () => import('./about/about.component').then((m) => m.AboutComponent), }, { path: '**', redirectTo: 'app', }, ], }, { path: '**', redirectTo: 'todos', }, ];
006491
/** * @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 {NgForOf} from '@angular/common'; import { ChangeDetectorRef, Component, EventEmitter, OnDestroy, OnInit, Output, Pipe, PipeTransform, } from '@angular/core'; import {RouterLink} from '@angular/router'; import {SamplePipe} from './sample.pipe'; import {Todo, TodoComponent} from './todo.component'; import {TooltipDirective} from './tooltip.directive'; export const enum TodoFilter { All = 'all', Completed = 'completed', Active = 'active', } @Pipe({pure: false, name: 'todosFilter', standalone: true}) export class TodosFilter implements PipeTransform { transform(todos: Todo[], filter: TodoFilter): Todo[] { return (todos || []).filter((t) => { if (filter === TodoFilter.All) { return true; } if (filter === TodoFilter.Active && !t.completed) { return true; } if (filter === TodoFilter.Completed && t.completed) { return true; } return false; }); } } const fib = (n: number): number => { if (n === 1 || n === 2) { return 1; } return fib(n - 1) + fib(n - 2); }; @Component({ selector: 'app-todos', imports: [RouterLink, TodoComponent, SamplePipe, TodosFilter, TooltipDirective], standalone: true, template: ` <a [routerLink]="">Home</a> <a [routerLink]="">Home</a> <a [routerLink]="">Home</a> <p>{{ 'Sample text processed by a pipe' | sample }}</p> <section class="todoapp"> <header class="header"> <h1>todos</h1> <input (keydown.enter)="addTodo(input)" #input class="new-todo" placeholder="What needs to be done?" autofocus /> </header> <section class="main"> <input id="toggle-all" class="toggle-all" type="checkbox" /> <label for="toggle-all">Mark all as complete</label> <ul class="todo-list"> @for (todo of todos | todosFilter: filterValue; track todo) { <app-todo appTooltip [todo]="todo" (delete)="onDelete($event)" (update)="onChange($event)" /> } </ul> </section> <footer class="footer"> <span class="todo-count"> <strong>{{ itemsLeft }}</strong> item left </span> <button class="clear-completed" (click)="clearCompleted()">Clear completed</button> </footer> </section> `, }) export class TodosComponent implements OnInit, OnDestroy { todos: Todo[] = [ { label: 'Buy milk', completed: false, id: '42', }, { label: 'Build something fun!', completed: false, id: '43', }, ]; @Output() update = new EventEmitter(); @Output() delete = new EventEmitter(); @Output() add = new EventEmitter(); private hashListener!: EventListenerOrEventListenerObject; constructor(private cdRef: ChangeDetectorRef) {} ngOnInit(): void { if (typeof window !== 'undefined') { window.addEventListener('hashchange', (this.hashListener = () => this.cdRef.markForCheck())); } } ngOnDestroy(): void { fib(40); if (typeof window !== 'undefined') { window.removeEventListener('hashchange', this.hashListener); } } get filterValue(): TodoFilter { if (typeof window !== 'undefined') { return (window.location.hash.replace(/^#\//, '') as TodoFilter) || TodoFilter.All; } return TodoFilter.All; } get itemsLeft(): number { return (this.todos || []).filter((t) => !t.completed).length; } clearCompleted(): void { (this.todos || []).filter((t) => t.completed).forEach((t) => this.delete.emit(t)); } addTodo(input: HTMLInputElement): void { const todo = { completed: false, label: input.value, }; const result: Todo = {...todo, id: Math.random().toString()}; this.todos.push(result); input.value = ''; } onChange(todo: Todo): void { if (!todo.id) { return; } } onDelete(todo: Todo): void { if (!todo.id) { return; } const idx = this.todos.findIndex((t) => t.id === todo.id); if (idx < 0) { return; } // tslint:disable-next-line:no-console console.log('Deleting', idx); this.todos.splice(idx, 1); } }
006516
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>ShellChrome</title> <base href="/" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" type="image/x-icon" href="assets/icon16.png" /> <link rel="stylesheet" href="./third_party/github.com/google/material-design-icons/material-icons.css"> <link rel="stylesheet" href="./styles.css"></head> </head> <body> <app-root></app-root> <script src="./packages/zone.js/bundles/zone.umd.js"></script> <script type="module" src="./bundle/main.js"></script> </body> </html>
006579
/** * @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, computed, inject, input, signal} from '@angular/core'; import {MatOption} from '@angular/material/core'; import {MatFormField, MatLabel} from '@angular/material/form-field'; import {MatIcon} from '@angular/material/icon'; import {MatInput} from '@angular/material/input'; import {MatSelect} from '@angular/material/select'; import {MatTableModule} from '@angular/material/table'; import {MatTooltip} from '@angular/material/tooltip'; import {Events, MessageBus, SerializedInjector, SerializedProviderRecord} from 'protocol'; @Component({ selector: 'ng-injector-providers', template: ` <h1>Providers for {{ injector()?.name }}</h1> @if (injector()) { <div class="injector-providers"> <mat-form-field appearance="fill" class="form-field-spacer"> <mat-label>Search by token</mat-label> <input type="text" matInput placeholder="Provider token" (input)="searchToken.set($event.target.value)" [value]="searchToken()" /> <mat-icon matSuffix (click)="searchToken.set('')">close</mat-icon> </mat-form-field> <mat-form-field class="form-field-spacer"> <mat-label>Search by type</mat-label> <mat-select [value]="searchType()" (selectionChange)="searchType.set($event.value)"> <mat-option>None</mat-option> @for (type of providerTypes; track type) { <mat-option [value]="type">{{ $any(providerTypeToLabel)[type] }}</mat-option> } </mat-select> </mat-form-field> @if (visibleProviders().length > 0) { <table mat-table [dataSource]="visibleProviders()" class="mat-elevation-z4"> <ng-container matColumnDef="token"> <th mat-header-cell *matHeaderCellDef><h3 class="column-title">Token</h3></th> <td mat-cell *matCellDef="let provider">{{ provider.token }}</td> </ng-container> <ng-container matColumnDef="type"> <th mat-header-cell *matHeaderCellDef><h3 class="column-title">Type</h3></th> <td mat-cell *matCellDef="let provider"> @if (provider.type === 'multi') { multi (x{{ provider.index.length }}) } @else { {{ $any(providerTypeToLabel)[provider.type] }} } </td> </ng-container> <ng-container matColumnDef="isViewProvider"> <th mat-header-cell *matHeaderCellDef><h3 class="column-title">Is View Provider</h3></th> <td mat-cell *matCellDef="let provider"> <mat-icon>{{ provider.isViewProvider ? 'check_circle' : 'cancel' }}</mat-icon> </td> </ng-container> <ng-container matColumnDef="log"> <th mat-header-cell *matHeaderCellDef><h3 class="column-title"></h3></th> <td mat-cell *matCellDef="let provider"> <mat-icon matTooltipPosition="left" matTooltip="Log provider in console" class="select" (click)="select(provider)" >send</mat-icon > </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr> </table> } </div> } `, styles: [ ` .select { cursor: pointer; } :host { display: block; padding: 16px; } .form-field-spacer { margin: 0 4px 0 4px; } table { width: 100%; } .column-title { margin: 0; } tr.example-detail-row { height: 0; } .example-element-row td { border-bottom-width: 0; cursor: pointer; } .example-element-detail { overflow: hidden; display: flex; } .example-element-diagram { min-width: 80px; border: 2px solid black; padding: 8px; font-weight: lighter; margin: 8px 0; height: 104px; } .example-element-symbol { font-weight: bold; font-size: 40px; line-height: normal; } .example-element-description { padding: 16px; } .example-element-description-attribution { opacity: 0.5; } `, ], standalone: true, imports: [ MatTableModule, MatIcon, MatTooltip, MatInput, MatSelect, MatFormField, MatLabel, MatOption, ], }) export class InjectorProvidersComponent { readonly injector = input.required<SerializedInjector>(); readonly providers = input<SerializedProviderRecord[]>([]); readonly searchToken = signal(''); readonly searchType = signal(''); readonly visibleProviders = computed(() => { const searchToken = this.searchToken().toLowerCase(); const searchType = this.searchType(); const predicates: ((provider: SerializedProviderRecord) => boolean)[] = []; searchToken && predicates.push((provider) => provider.token.toLowerCase().includes(searchToken)); searchType && predicates.push((provider) => provider.type === searchType); return this.providers().filter((provider) => predicates.every((predicate) => predicate(provider)), ); }); providerTypeToLabel = { type: 'Type', existing: 'useExisting', factory: 'useFactory', class: 'useClass', value: 'useValue', }; providerTypes = Object.keys(this.providerTypeToLabel); messageBus = inject<MessageBus<Events>>(MessageBus); select(row: SerializedProviderRecord) { const {id, type, name} = this.injector(); this.messageBus.emit('logProvider', [{id, type, name}, row]); } get displayedColumns(): string[] { if (this.injector()?.type === 'element') { return ['token', 'type', 'isViewProvider', 'log']; } return ['token', 'type', 'log']; } }
006885
/** * @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} from '@angular/core'; import {MatDialog} from '@angular/material/dialog'; import {DialogComponent} from './dialog.component'; @Injectable() export class MyServiceA {} @Component({ selector: 'app-todo-demo', templateUrl: './app-todo.component.html', styleUrls: ['./app-todo.component.scss'], viewProviders: [MyServiceA], standalone: false, }) export class AppTodoComponent { name!: string; animal!: string; constructor(public dialog: MatDialog) {} openDialog(): void { const dialogRef = this.dialog.open(DialogComponent, { width: '250px', data: {name: this.name, animal: this.animal}, }); dialogRef.afterClosed().subscribe((result) => { // tslint:disable-next-line:no-console console.log('The dialog was closed'); this.animal = result; }); } }
006897
/** * @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 {Pipe, PipeTransform} from '@angular/core'; import {Todo} from './todo'; export const enum TodoFilter { All = 'all', Completed = 'completed', Active = 'active', } @Pipe({ pure: false, name: 'todosFilter', standalone: true, }) export class TodosFilter implements PipeTransform { transform(todos: Todo[], filter: TodoFilter): Todo[] { return (todos || []).filter((t) => { if (filter === TodoFilter.All) { return true; } if (filter === TodoFilter.Active && !t.completed) { return true; } if (filter === TodoFilter.Completed && t.completed) { return true; } return false; }); } }
006966
import {Component} from '@angular/core'; @Component({ template: ` @for (item of items; track item.name[0].toUpperCase()) { {{item.name}} } @for (otherItem of otherItems; track otherItem.name[0].toUpperCase()) { {{otherItem.name}} } `, standalone: false }) export class MyApp { items = [{name: 'one'}, {name: 'two'}, {name: 'three'}]; otherItems = [{name: 'four'}, {name: 'five'}, {name: 'six'}]; }
006967
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item; let ev = $even) { <div (click)="log($index, ev, $first, $count)"></div> } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = []; log(..._: any[]) {} }
006972
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track trackFn($index)) {} </div> `, standalone: false }) export class MyApp { message = 'hello'; items = [{name: 'one'}, {name: 'two'}, {name: 'three'}]; trackFn(index: number) { return index; } }
006975
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item.name[0].toUpperCase()) { {{item.name}} } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = [{name: 'one'}, {name: 'two'}, {name: 'three'}]; }
006981
import {Component, Directive, Input} from '@angular/core'; @Directive({selector: '[binding]'}) export class Binding { @Input() binding = 0; } @Component({ template: ` @for (item of items; track item) { <div foo="1" bar="2" [binding]="3">{{item}}</div> } @empty { <span empty-foo="1" empty-bar="2" [binding]="3">Empty!</span> } `, imports: [Binding], }) export class MyApp { items = [1, 2, 3]; }
006982
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item) { Index: {{$index}} First: {{$first}} Last: {{$last}} Even: {{$even}} Odd: {{$odd}} Count: {{$count}} } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = []; }
006991
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item) { {{item.name}} @for (subitem of item.subItems; track $index) { {{subitem}} from {{item.name}} } } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = [ {name: 'one', subItems: ['sub one', 'sub two', 'sub three']}, {name: 'two', subItems: ['sub one', 'sub two', 'sub three']}, {name: 'three', subItems: ['sub one', 'sub two', 'sub three']}, ]; }
007004
type: Component, args: [{ template: ` <div> {{message}} @if (value() === 1) { one } @else if (otherValue() === 2) { two } @else if (message) { three } @else { four } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: basic_if_else_if.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; value: () => number; otherValue: () => number; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: nested_if.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.val = 1; this.innerVal = 2; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @if (val === 0) { zero } @else if (val === 1) { one } @else if (val === 2) { @if (innerVal === 0) { inner zero } @else if (innerVal === 1) { inner one } @else if (innerVal === 2) { inner two } @else { inner three } } @else { three } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @if (val === 0) { zero } @else if (val === 1) { one } @else if (val === 2) { @if (innerVal === 0) { inner zero } @else if (innerVal === 1) { inner one } @else if (innerVal === 2) { inner two } @else { inner three } } @else { three } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: nested_if.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; val: number; innerVal: number; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: if_with_pipe.js ****************************************************************************************************/ import { Component, Pipe } from '@angular/core'; import * as i0 from "@angular/core"; export class TestPipe { transform(value) { return value; } } TestPipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: TestPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); TestPipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: TestPipe, isStandalone: true, name: "test" }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: TestPipe, decorators: [{ type: Pipe, args: [{ name: 'test' }] }] }); export class MyApp { constructor() { this.message = 'hello'; this.val = 1; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: true, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @if ((val | test) === 1) { one } @else if ((val | test) === 2) { two } @else { three } </div> `, isInline: true, dependencies: [{ kind: "pipe", type: TestPipe, name: "test" }] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @if ((val | test) === 1) { one } @else if ((val | test) === 2) { two } @else { three } </div> `, imports: [TestPipe], }] }] }); /**************************************************************************************************** * PARTIAL FILE: if_with_pipe.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class TestPipe { transform(value: unknown): unknown; static ɵfac: i0.ɵɵFactoryDeclaration<TestPipe, never>; static ɵpipe: i0.ɵɵPipeDeclaration<TestPipe, "test", true>; } export declare class MyApp { message: string; val: number; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: if_with_alias.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.value = () => 1; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @if (value(); as alias) { {{value()}} as {{alias}} } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @if (value(); as alias) { {{value()}} as {{alias}} } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: if_with_alias.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; value: () => number; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDe
007005
laration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: if_nested_alias.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.value = () => 1; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` @if (value(); as root) { Root: {{value()}}/{{root}} @if (value(); as inner) { Inner: {{value()}}/{{root}}/{{inner}} @if (value(); as innermost) { Innermost: {{value()}}/{{root}}/{{inner}}/{{innermost}} } } } `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` @if (value(); as root) { Root: {{value()}}/{{root}} @if (value(); as inner) { Inner: {{value()}}/{{root}}/{{inner}} @if (value(); as innermost) { Innermost: {{value()}}/{{root}}/{{inner}}/{{innermost}} } } } `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: if_nested_alias.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { value: () => number; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: if_nested_alias_listeners.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.value = () => 1; } log(..._) { } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` @if (value(); as root) { <button (click)="log(value(), root)"></button> @if (value(); as inner) { <button (click)="log(value(), root, inner)"></button> @if (value(); as innermost) { <button (click)="log(value(), root, inner, innermost)"></button> } } } `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` @if (value(); as root) { <button (click)="log(value(), root)"></button> @if (value(); as inner) { <button (click)="log(value(), root, inner)"></button> @if (value(); as innermost) { <button (click)="log(value(), root, inner, innermost)"></button> } } } `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: if_nested_alias_listeners.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { value: () => number; log(..._: any[]): void; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: basic_for.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = [{ name: 'one' }, { name: 'two' }, { name: 'three' }]; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track item) { {{item.name}} } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items; track item) { {{item.name}} } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: basic_for.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: { name: string; }[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_with_empty.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = [{ name: 'one' }, { name: 'two' }, { name: 'three' }]; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track item) { {{item.name}} } @empty { No items! } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items; track item) { {{item.name}} } @empty { No items! } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_with_empty.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: { name: string; }[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /***********************************************************************************************
007006
* PARTIAL FILE: for_track_by_index.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = [{ name: 'one' }, { name: 'two' }, { name: 'three' }]; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track $index) { {{item.name}} } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items; track $index) { {{item.name}} } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_track_by_index.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: { name: string; }[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_track_by_field.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = [{ name: 'one' }, { name: 'two' }, { name: 'three' }]; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track item.name[0].toUpperCase()) { {{item.name}} } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items; track item.name[0].toUpperCase()) { {{item.name}} } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_track_by_field.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: { name: string; }[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: nested_for.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = [ { name: 'one', subItems: ['sub one', 'sub two', 'sub three'] }, { name: 'two', subItems: ['sub one', 'sub two', 'sub three'] }, { name: 'three', subItems: ['sub one', 'sub two', 'sub three'] }, ]; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track item) { {{item.name}} @for (subitem of item.subItems; track $index) { {{subitem}} from {{item.name}} } } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items; track item) { {{item.name}} @for (subitem of item.subItems; track $index) { {{subitem}} from {{item.name}} } } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: nested_for.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: { name: string; subItems: string[]; }[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_template_variables.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = []; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track item) { Index: {{$index}} First: {{$first}} Last: {{$last}} Even: {{$even}} Odd: {{$odd}} Count: {{$count}} } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items; track item) { Index: {{$index}} First: {{$first}} Last: {{$last}} Even: {{$even}} Odd: {{$odd}} Count: {{$count}} } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_template_variables.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: never[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_aliased_template_variables.js ******
007007
*****************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = []; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track item; let idx = $index, f = $first; let l = $last, ev = $even, o = $odd; let co = $count) { Index: {{idx}} First: {{f}} Last: {{l}} Even: {{ev}} Odd: {{o}} Count: {{co}} } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items; track item; let idx = $index, f = $first; let l = $last, ev = $even, o = $odd; let co = $count) { Index: {{idx}} First: {{f}} Last: {{l}} Even: {{ev}} Odd: {{o}} Count: {{co}} } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_aliased_template_variables.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: never[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_both_aliased_and_original_variables.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = []; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track item; let idx = $index, f = $first; let l = $last, ev = $even, o = $odd; let co = $count) { Original index: {{$index}} Original first: {{$first}} Original last: {{$last}} Original even: {{$even}} Original odd: {{$odd}} Original count: {{$count}} <hr> Aliased index: {{idx}} Aliased first: {{f}} Aliased last: {{l}} Aliased even: {{ev}} Aliased odd: {{o}} Aliased count: {{co}} } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items; track item; let idx = $index, f = $first; let l = $last, ev = $even, o = $odd; let co = $count) { Original index: {{$index}} Original first: {{$first}} Original last: {{$last}} Original even: {{$even}} Original odd: {{$odd}} Original count: {{$count}} <hr> Aliased index: {{idx}} Aliased first: {{f}} Aliased last: {{l}} Aliased even: {{ev}} Aliased odd: {{o}} Aliased count: {{co}} } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_both_aliased_and_original_variables.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: never[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: nested_for_template_variables.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = [ { name: 'one', subItems: ['sub one', 'sub two', 'sub three'] }, { name: 'two', subItems: ['sub one', 'sub two', 'sub three'] }, { name: 'three', subItems: ['sub one', 'sub two', 'sub three'] }, ]; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track item; let outerCount = $count) { {{item.name}} @for (subitem of item.subItems; track subitem) { Outer: {{outerCount}} Inner: {{$count}} } } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items; track item; let outerCount = $count) { {{item.name}} @for (subitem of item.subItems; track subitem) { Outer: {{outerCount}} Inner: {{$count}} } } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: nested_for_template_variables.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: { name: string; subItems: string[]; }[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_template_variables_listener.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = []; } log(..._) { } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", t
007008
pe: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track item; let ev = $even) { <div (click)="log($index, ev, $first, $count)"></div> } </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items; track item; let ev = $even) { <div (click)="log($index, ev, $first, $count)"></div> } </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_template_variables_listener.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: never[]; log(..._: any[]): void; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_variables_expression.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.items = []; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: `@for (item of items; track item) { {{$odd + ''}} }`, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: `@for (item of items; track item) { {{$odd + ''}} }`, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_variables_expression.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { items: never[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_data_slots.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; // We verify the data slots by defining templates before/after // and checking that the indexes are sequential. export class MyApp { constructor() { this.items = ['one', 'two', 'three']; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <ng-template/> @for (item of items; track item) { {{item}} } @empty { Empty } <ng-template/> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <ng-template/> @for (item of items; track item) { {{item}} } @empty { Empty } <ng-template/> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_data_slots.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { items: string[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_template_variables_scope.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = []; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` {{$index}} {{$count}} {{$first}} {{$last}} @for (item of items; track item) { {{$index}} {{$count}} {{$first}} {{$last}} } {{$index}} {{$count}} {{$first}} {{$last}} `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` {{$index}} {{$count}} {{$first}} {{$last}} @for (item of items; track item) { {{$index}} {{$count}} {{$first}} {{$last}} } {{$index}} {{$count}} {{$first}} {{$last}} `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_template_variables_scope.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: never[]; $index: any; $count: any; $first: any; $last: any; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_template_track_method_root.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.items = [{ name: 'one' }, { name: 'two' }, { name: 'three' }]; } trackFn(_index, item) { return item; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items; track trackFn($index, item)) {} </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component,
007010
rItem.name}} } `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` @for (item of items; track trackFn(item, message)) { {{item.name}} } @for (otherItem of otherItems; track trackFn(otherItem, message)) { {{otherItem.name}} } `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_impure_track_reuse.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; items: { name: string; }[]; otherItems: { name: string; }[]; trackFn(item: any, message: string): string; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_track_literals.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.items = []; } trackFn(obj, arr) { return null; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` @for (item of items; track trackFn({foo: item, bar: item}, [item, item])) { {{item.name}} } `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` @for (item of items; track trackFn({foo: item, bar: item}, [item, item])) { {{item.name}} } `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_track_literals.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { items: { name: string; }[]; trackFn(obj: any, arr: any[]): null; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: for_with_pipe.js ****************************************************************************************************/ import { Component, Pipe } from '@angular/core'; import * as i0 from "@angular/core"; export class TestPipe { transform(value) { return value; } } TestPipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: TestPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); TestPipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: TestPipe, isStandalone: true, name: "test" }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: TestPipe, decorators: [{ type: Pipe, args: [{ name: 'test' }] }] }); export class MyApp { constructor() { this.message = 'hello'; this.items = [1, 2, 3]; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: true, selector: "ng-component", ngImport: i0, template: ` <div> {{message}} @for (item of items | test; track item) { {{item}} } </div> `, isInline: true, dependencies: [{ kind: "pipe", type: TestPipe, name: "test" }] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> {{message}} @for (item of items | test; track item) { {{item}} } </div> `, imports: [TestPipe], }] }] }); /**************************************************************************************************** * PARTIAL FILE: for_with_pipe.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class TestPipe { transform(value: unknown): unknown; static ɵfac: i0.ɵɵFactoryDeclaration<TestPipe, never>; static ɵpipe: i0.ɵɵPipeDeclaration<TestPipe, "test", true>; } export declare class MyApp { message: string; items: number[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: if_element_root_node.js ****************************************************************************************************/ import { Component, Directive, Input } from '@angular/core'; import * as i0 from "@angular/core"; export class Binding { constructor() { this.binding = 0; } } Binding.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: Binding, deps: [], target: i0.ɵɵFactoryTarget.Directive }); Binding.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: Binding, isStandalone: true, selector: "[binding]", inputs: { binding: "binding" }, ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: Binding, decorators: [{ type: Directive, args: [{ selector: '[binding]' }] }], propDecorators: { binding: [{ type: Input }] } }); export class MyApp { constructor() { this.expr = 0; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: true, selector: "ng-component", ngImport: i0, template: ` @if (expr === 0) { <div foo="1" bar="2" [binding]="3">{{expr}}</div> } @else if (expr === 1) { <div foo="4" bar="5" [binding]="6">{{expr}}</div> } @else { <div foo="7" bar="8" [binding]="9">{{expr}}</div> } `, isInline: true, dependencies: [{ kind: "directive", type: Binding, selector: "[binding]", inputs: ["binding"] }] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0",
007027
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item) { {{item.name}} } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = [{name: 'one'}, {name: 'two'}, {name: 'three'}]; }
007046
import {Component} from '@angular/core'; @Component({ template: ` <div> {{message}} @for (item of items; track item; let idx = $index, f = $first; let l = $last, ev = $even, o = $odd; let co = $count) { Original index: {{$index}} Original first: {{$first}} Original last: {{$last}} Original even: {{$even}} Original odd: {{$odd}} Original count: {{$count}} <hr> Aliased index: {{idx}} Aliased first: {{f}} Aliased last: {{l}} Aliased even: {{ev}} Aliased odd: {{o}} Aliased count: {{co}} } </div> `, standalone: false }) export class MyApp { message = 'hello'; items = []; }
007047
import {Component, Directive, Input} from '@angular/core'; @Directive({selector: '[binding]'}) export class Binding { @Input() binding = 0; } @Component({ template: ` @for (item of items; track item) { <ng-template foo="1" bar="2" [binding]="3">{{item}}</ng-template> } @empty { <ng-template empty-foo="1" empty-bar="2" [binding]="3">Empty!</ng-template> } `, imports: [Binding], }) export class MyApp { items = [1, 2, 3]; }
007062
import {Component} from '@angular/core'; function it(_desc: string, fn: () => void) {} it('case 1', () => { @Component({ template: ` @if (true) { First } @else { Second } `, standalone: false }) class TestComponent { } }); it('case 2', () => { @Component({ template: ` @if (true) { First } @else { Second } `, standalone: false }) class TestComponent { } });
007154
import {Component, Directive, EventEmitter, Input, NgModule, Output} from '@angular/core'; @Component({ selector: 'test-cmp', template: 'Name: <input bindon-ngModel="name">', standalone: false }) export class TestCmp { name: string = ''; } @Directive({ selector: '[ngModel]', standalone: false }) export class NgModelDirective { @Input() ngModel: string = ''; @Output() ngModelChanges: EventEmitter<string> = new EventEmitter(); } @NgModule({declarations: [TestCmp, NgModelDirective]}) export class AppModule { }
007161
import {Component, Directive, EventEmitter, Input, NgModule, Output} from '@angular/core'; @Component({ selector: 'test-cmp', template: 'Name: <input [(ngModel)]="name">', standalone: false }) export class TestCmp { name: string = ''; } @Directive({ selector: '[ngModel]', standalone: false }) export class NgModelDirective { @Input() ngModel: string = ''; @Output() ngModelChanges: EventEmitter<string> = new EventEmitter(); } @NgModule({declarations: [TestCmp, NgModelDirective]}) export class AppModule { }
007174
import {Component} from '@angular/core'; @Component({ template: ` <div i18n> Content: @for (item of items; track item) { before<span>middle</span>after } @empty { before<div>empty</div>after }! </div> `, standalone: false }) export class MyApp { items = [1, 2, 3]; }
007386
import {Injectable, NgModule} from '@angular/core'; @Injectable() export class Service { } @NgModule({providers: [Service]}) export class BaseModule { constructor(private service: Service) {} } @NgModule({}) export class BasicModule extends BaseModule { }
007488
/**************************************************************************************************** * PARTIAL FILE: root_template.js ****************************************************************************************************/ import { Component, NgModule } from '@angular/core'; import * as i0 from "@angular/core"; export class SimpleComponent { } SimpleComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: SimpleComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); SimpleComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: SimpleComponent, isStandalone: false, selector: "simple", ngImport: i0, template: '<div><ng-content></ng-content></div>', isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: SimpleComponent, decorators: [{ type: Component, args: [{ selector: 'simple', template: '<div><ng-content></ng-content></div>', standalone: false }] }] }); export class ComplexComponent { } ComplexComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: ComplexComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); ComplexComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: ComplexComponent, isStandalone: false, selector: "complex", ngImport: i0, template: ` <div id="first"><ng-content select="span[title=toFirst]"></ng-content></div> <div id="second"><ng-content SELECT="span[title=toSecond]"></ng-content></div>`, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: ComplexComponent, decorators: [{ type: Component, args: [{ selector: 'complex', template: ` <div id="first"><ng-content select="span[title=toFirst]"></ng-content></div> <div id="second"><ng-content SELECT="span[title=toSecond]"></ng-content></div>`, standalone: false }] }] }); export class MyApp { } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "my-app", ngImport: i0, template: '<simple>content</simple> <complex></complex>', isInline: true, dependencies: [{ kind: "component", type: SimpleComponent, selector: "simple" }, { kind: "component", type: ComplexComponent, selector: "complex" }] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ selector: 'my-app', template: '<simple>content</simple> <complex></complex>', standalone: false }] }] }); export class MyModule { } MyModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); MyModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, declarations: [SimpleComponent, ComplexComponent, MyApp] }); MyModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, decorators: [{ type: NgModule, args: [{ declarations: [SimpleComponent, ComplexComponent, MyApp] }] }] }); /**************************************************************************************************** * PARTIAL FILE: root_template.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class SimpleComponent { static ɵfac: i0.ɵɵFactoryDeclaration<SimpleComponent, never>; static ɵcmp: i0.ɵɵComponentDeclaration<SimpleComponent, "simple", never, {}, {}, never, ["*"], false, never>; } export declare class ComplexComponent { static ɵfac: i0.ɵɵFactoryDeclaration<ComplexComponent, never>; static ɵcmp: i0.ɵɵComponentDeclaration<ComplexComponent, "complex", never, {}, {}, never, ["span[title=toFirst]", "span[title=toSecond]"], false, never>; } export declare class MyApp { static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "my-app", never, {}, {}, never, never, false, never>; } export declare class MyModule { static ɵfac: i0.ɵɵFactoryDeclaration<MyModule, never>; static ɵmod: i0.ɵɵNgModuleDeclaration<MyModule, [typeof SimpleComponent, typeof ComplexComponent, typeof MyApp], never, never>; static ɵinj: i0.ɵɵInjectorDeclaration<MyModule>; } /**************************************************************************************************** * PARTIAL FILE: multiple_wildcards.js ****************************************************************************************************/ import { Component, NgModule } from '@angular/core'; import * as i0 from "@angular/core"; class Cmp { } Cmp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: Cmp, deps: [], target: i0.ɵɵFactoryTarget.Component }); Cmp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: Cmp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <ng-content></ng-content> <ng-content select="[spacer]"></ng-content> <ng-content></ng-content> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: Cmp, decorators: [{ type: Component, args: [{ template: ` <ng-content></ng-content> <ng-content select="[spacer]"></ng-content> <ng-content></ng-content> `, standalone: false }] }] }); class Module { } Module.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: Module, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); Module.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: Module, declarations: [Cmp] }); Module.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: Module }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: Module, decorators: [{ type: NgModule, args: [{ declarations: [Cmp] }] }] }); /**************************************************************************************************** * PARTIAL FILE: multiple_wildcards.d.ts ****************************************************************************************************/ export {}; /******************************************************************************************
007512
/**************************************************************************************************** * PARTIAL FILE: component.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class OtherCmp { } OtherCmp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: OtherCmp, deps: [], target: i0.ɵɵFactoryTarget.Component }); OtherCmp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: OtherCmp, isStandalone: true, selector: "other-cmp", ngImport: i0, template: '', isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: OtherCmp, decorators: [{ type: Component, args: [{ selector: 'other-cmp', template: '', }] }] }); export class StandaloneCmp { } StandaloneCmp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: StandaloneCmp, deps: [], target: i0.ɵɵFactoryTarget.Component }); StandaloneCmp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: StandaloneCmp, isStandalone: true, selector: "ng-component", ngImport: i0, template: '<other-cmp></other-cmp>', isInline: true, dependencies: [{ kind: "component", type: OtherCmp, selector: "other-cmp" }] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: StandaloneCmp, decorators: [{ type: Component, args: [{ template: '<other-cmp></other-cmp>', imports: [OtherCmp], }] }] }); /**************************************************************************************************** * PARTIAL FILE: component.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class OtherCmp { static ɵfac: i0.ɵɵFactoryDeclaration<OtherCmp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<OtherCmp, "other-cmp", never, {}, {}, never, never, true, never>; } export declare class StandaloneCmp { static ɵfac: i0.ɵɵFactoryDeclaration<StandaloneCmp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<StandaloneCmp, "ng-component", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: directive.js ****************************************************************************************************/ import { Directive } from '@angular/core'; import * as i0 from "@angular/core"; export class StandaloneDir { } StandaloneDir.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: StandaloneDir, deps: [], target: i0.ɵɵFactoryTarget.Directive }); StandaloneDir.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: StandaloneDir, isStandalone: true, ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: StandaloneDir, decorators: [{ type: Directive, args: [{}] }] }); /**************************************************************************************************** * PARTIAL FILE: directive.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class StandaloneDir { static ɵfac: i0.ɵɵFactoryDeclaration<StandaloneDir, never>; static ɵdir: i0.ɵɵDirectiveDeclaration<StandaloneDir, never, never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: pipe.js ****************************************************************************************************/ import { Pipe } from '@angular/core'; import * as i0 from "@angular/core"; export class StandalonePipe { transform(value) { } } StandalonePipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: StandalonePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); StandalonePipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: StandalonePipe, isStandalone: true, name: "stpipe" }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: StandalonePipe, decorators: [{ type: Pipe, args: [{ name: 'stpipe', }] }] }); /**************************************************************************************************** * PARTIAL FILE: pipe.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class StandalonePipe { transform(value: any): any; static ɵfac: i0.ɵɵFactoryDeclaration<StandalonePipe, never>; static ɵpipe: i0.ɵɵPipeDeclaration<StandalonePipe, "stpipe", true>; } /**************************************************************************************************** * PARTIAL FILE: imports.js ****************************************************************************************************/ import { Component, Directive, NgModule, Pipe } from '@angular/core'; import * as i0 from "@angular/core"; export class NotStandaloneDir { } NotStandaloneDir.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: NotStandaloneDir, deps: [], target: i0.ɵɵFactoryTarget.Directive }); NotStandaloneDir.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: NotStandaloneDir, isStandalone: false, selector: "[not-standalone]", ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: NotStandaloneDir, decorators: [{ type: Directive, args: [{ selector: '[not-standalone]', standalone: false }] }] }); export class NotStandalonePipe { transform(value) { } } NotStandalonePipe.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: NotStandalonePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); NotStandalonePipe.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: NotStandalonePipe, isStandalone: false, name: "nspipe" }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: NotStandalonePipe, decorators: [{ type: Pipe, args: [{ name: 'nspipe', standalone: false }] }] }); export class NotStandaloneStuffModule { } NotStandaloneStuffModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: NotStandaloneStuffModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); NotStandaloneStuffModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version:
007530
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: '<input #user>Hello {{user.value}}!', standalone: false }) export class MyComponent { } @NgModule({declarations: [MyComponent]}) export class MyModule { }
007540
nt, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: MyComponent, isStandalone: false, selector: "my-component", ngImport: i0, template: ` <ul> <li *for="let item of items"> <div>{{item.name}}</div> <ul> <li *for="let info of item.infos"> {{item.name}}: {{info.description}} </li> </ul> </li> </ul>`, isInline: true, dependencies: [{ kind: "directive", type: i0.forwardRef(() => ForOfDirective), selector: "[forOf]", inputs: ["forOf"] }] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyComponent, decorators: [{ type: Component, args: [{ selector: 'my-component', template: ` <ul> <li *for="let item of items"> <div>{{item.name}}</div> <ul> <li *for="let info of item.infos"> {{item.name}}: {{info.description}} </li> </ul> </li> </ul>`, standalone: false }] }] }); export class MyModule { } MyModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); MyModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, declarations: [MyComponent, ForOfDirective] }); MyModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, decorators: [{ type: NgModule, args: [{ declarations: [MyComponent, ForOfDirective] }] }] }); /**************************************************************************************************** * PARTIAL FILE: parent_template_variable.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; import * as i1 from "./for_of"; export declare class MyComponent { items: { name: string; infos: { description: string; }[]; }[]; static ɵfac: i0.ɵɵFactoryDeclaration<MyComponent, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyComponent, "my-component", never, {}, {}, never, never, false, never>; } export declare class MyModule { static ɵfac: i0.ɵɵFactoryDeclaration<MyModule, never>; static ɵmod: i0.ɵɵNgModuleDeclaration<MyModule, [typeof MyComponent, typeof i1.ForOfDirective], never, never>; static ɵinj: i0.ɵɵInjectorDeclaration<MyModule>; } /**************************************************************************************************** * PARTIAL FILE: for_of.js ****************************************************************************************************/ import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; import * as i0 from "@angular/core"; export class ForOfDirective { constructor(view, template) { this.view = view; this.template = template; } ngOnChanges(simpleChanges) { } } ForOfDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: ForOfDirective, deps: [{ token: i0.ViewContainerRef }, { token: i0.TemplateRef }], target: i0.ɵɵFactoryTarget.Directive }); ForOfDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: ForOfDirective, isStandalone: false, selector: "[forOf]", inputs: { forOf: "forOf" }, usesOnChanges: true, ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: ForOfDirective, decorators: [{ type: Directive, args: [{ selector: '[forOf]', standalone: false }] }], ctorParameters: () => [{ type: i0.ViewContainerRef }, { type: i0.TemplateRef }], propDecorators: { forOf: [{ type: Input }] } }); /**************************************************************************************************** * PARTIAL FILE: for_of.d.ts ****************************************************************************************************/ import { SimpleChanges, TemplateRef, ViewContainerRef } from '@angular/core'; import * as i0 from "@angular/core"; export interface ForOfContext { $implicit: any; index: number; even: boolean; odd: boolean; } export declare class ForOfDirective { private view; private template; private previous; constructor(view: ViewContainerRef, template: TemplateRef<any>); forOf: any[]; ngOnChanges(simpleChanges: SimpleChanges): void; static ɵfac: i0.ɵɵFactoryDeclaration<ForOfDirective, never>; static ɵdir: i0.ɵɵDirectiveDeclaration<ForOfDirective, "[forOf]", never, { "forOf": { "alias": "forOf"; "required": false; }; }, {}, never, never, false, never>; }
007891
import {Component, Directive, EventEmitter, Input, NgModule, Output} from '@angular/core'; @Component({ selector: 'test-cmp', template: 'Name: <ng-template><input [(ngModel)]="name"></ng-template>', standalone: false }) export class TestCmp { name: string = ''; } @Directive({ selector: '[ngModel]', standalone: false }) export class NgModelDirective { @Input() ngModel: string = ''; @Output() ngModelChanges: EventEmitter<string> = new EventEmitter(); } @NgModule({declarations: [TestCmp, NgModelDirective]}) export class AppModule { }
007912
import {Component, Directive, EventEmitter, Input, NgModule, Output} from '@angular/core'; @Component({ selector: 'test-cmp', template: 'Name: <input [(ngModel)]="name">', standalone: false }) export class TestCmp { name: string = ''; } @Directive({ selector: '[ngModel]', standalone: false }) export class NgModelDirective { @Input() ngModel: string = ''; @Output() ngModelChanges: EventEmitter<string> = new EventEmitter(); } @NgModule({declarations: [TestCmp, NgModelDirective]}) export class AppModule { }
007922
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: `<div [style.color]></div>`, standalone: false }) export class MyComponent { } @NgModule({declarations: [MyComponent]}) export class MyModule { }
007961
import {Component} from '@angular/core'; @Component({ selector: 'my-component', template: ` <div *ngIf="true" [class.bar]="field"></div> ` }) export class MyComponent { field!: any; }
007967
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: `<div [class]="myClassExp"></div>`, standalone: false }) export class MyComponent { myClassExp = {'foo': true} } @NgModule({declarations: [MyComponent]}) export class MyModule { }
008060
/**************************************************************************************************** * PARTIAL FILE: safe_keyed_read.js ****************************************************************************************************/ import { Component, NgModule } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.unknownNames = null; this.knownNames = [['Frodo', 'Bilbo']]; this.species = null; this.keys = null; this.speciesMap = { key: 'unknown' }; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <span [title]="'Your last name is ' + (unknownNames?.[0] || 'unknown')"> Hello, {{ knownNames?.[0]?.[1] }}! You are a Balrog: {{ species?.[0]?.[1]?.[2]?.[3]?.[4]?.[5] || 'unknown' }} You are an Elf: {{ speciesMap?.[keys?.[0] ?? 'key'] }} You are an Orc: {{ speciesMap?.['key'] }} </span> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <span [title]="'Your last name is ' + (unknownNames?.[0] || 'unknown')"> Hello, {{ knownNames?.[0]?.[1] }}! You are a Balrog: {{ species?.[0]?.[1]?.[2]?.[3]?.[4]?.[5] || 'unknown' }} You are an Elf: {{ speciesMap?.[keys?.[0] ?? 'key'] }} You are an Orc: {{ speciesMap?.['key'] }} </span> `, standalone: false }] }] }); export class MyModule { } MyModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); MyModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, declarations: [MyApp] }); MyModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, decorators: [{ type: NgModule, args: [{ declarations: [MyApp] }] }] }); /**************************************************************************************************** * PARTIAL FILE: safe_keyed_read.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { unknownNames: string[] | null; knownNames: string[][]; species: null; keys: null; speciesMap: Record<string, string>; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } export declare class MyModule { static ɵfac: i0.ɵɵFactoryDeclaration<MyModule, never>; static ɵmod: i0.ɵɵNgModuleDeclaration<MyModule, [typeof MyApp], never, never>; static ɵinj: i0.ɵɵInjectorDeclaration<MyModule>; } /**************************************************************************************************** * PARTIAL FILE: safe_access_deep.js ****************************************************************************************************/ import { Component, NgModule } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.p = null; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <span>Safe Property: {{ p?.a?.b?.c?.d }}</span> <span>Safe Keyed: {{ p?.['a']?.['b']?.['c']?.['d'] }}</span> <span>Mixed Property: {{ p?.a?.b.c.d?.e?.f?.g.h }}</span> <span>Mixed Property and Keyed: {{ p.a['b'].c.d?.['e']?.['f']?.g['h']['i']?.j.k }}</span> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <span>Safe Property: {{ p?.a?.b?.c?.d }}</span> <span>Safe Keyed: {{ p?.['a']?.['b']?.['c']?.['d'] }}</span> <span>Mixed Property: {{ p?.a?.b.c.d?.e?.f?.g.h }}</span> <span>Mixed Property and Keyed: {{ p.a['b'].c.d?.['e']?.['f']?.g['h']['i']?.j.k }}</span> `, standalone: false }] }] }); export class MyModule { } MyModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); MyModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, declarations: [MyApp] }); MyModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, decorators: [{ type: NgModule, args: [{ declarations: [MyApp] }] }] }); /**************************************************************************************************** * PARTIAL FILE: safe_access_deep.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { p: any; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } export declare class MyModule { static ɵfac: i0.ɵɵFactoryDeclaration<MyModule, never>; static ɵmod: i0.ɵɵNgModuleDeclaration<MyModule, [typeof MyApp], never, never>; static ɵinj: i0.ɵɵInjectorDeclaration<MyModule>; } /**************************************************************************************************** * PARTIAL FILE: safe_access_temporaries.js ****************************************************************************************************/ import { Component, NgModule } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.p = null; } f1() { } f2() { } f3() { } f4() { } f5() { } f6() { } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-
008061
LACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <span>Safe Property with Calls: {{ p()?.a()?.b()?.c()?.d() }}</span> <span>Safe and Unsafe Property with Calls: {{ p?.a()?.b().c().d()?.e()?.f?.g.h?.i()?.j()?.k().l }}</span> <span>Nested Safe with Calls: {{ f1()?.[f2()?.a]?.b }}</span> <span>Deep Nested Safe with Calls: {{ f1()?.[f2()?.f3()?.[f4()?.f5()]]?.f6() }}</span> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <span>Safe Property with Calls: {{ p()?.a()?.b()?.c()?.d() }}</span> <span>Safe and Unsafe Property with Calls: {{ p?.a()?.b().c().d()?.e()?.f?.g.h?.i()?.j()?.k().l }}</span> <span>Nested Safe with Calls: {{ f1()?.[f2()?.a]?.b }}</span> <span>Deep Nested Safe with Calls: {{ f1()?.[f2()?.f3()?.[f4()?.f5()]]?.f6() }}</span> `, standalone: false }] }] }); export class MyModule { } MyModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); MyModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, declarations: [MyApp] }); MyModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, decorators: [{ type: NgModule, args: [{ declarations: [MyApp] }] }] }); /**************************************************************************************************** * PARTIAL FILE: safe_access_temporaries.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { p: any; f1(): any; f2(): any; f3(): any; f4(): any; f5(): any; f6(): any; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } export declare class MyModule { static ɵfac: i0.ɵɵFactoryDeclaration<MyModule, never>; static ɵmod: i0.ɵɵNgModuleDeclaration<MyModule, [typeof MyApp], never, never>; static ɵinj: i0.ɵɵInjectorDeclaration<MyModule>; } /**************************************************************************************************** * PARTIAL FILE: safe_method_call.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <span [title]="person?.getName(false)"></span> <span [title]="person?.getName(false) || ''"></span> <span [title]="person?.getName(false)?.toLowerCase()"></span> <span [title]="person?.getName(config.get('title')?.enabled)"></span> <span [title]="person?.getName(config.get('title')?.enabled ?? true)"></span> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <span [title]="person?.getName(false)"></span> <span [title]="person?.getName(false) || ''"></span> <span [title]="person?.getName(false)?.toLowerCase()"></span> <span [title]="person?.getName(config.get('title')?.enabled)"></span> <span [title]="person?.getName(config.get('title')?.enabled ?? true)"></span> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: safe_method_call.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { person?: { getName: (includeTitle: boolean | undefined) => string; }; config: { get: (name: string) => { enabled: boolean; } | undefined; }; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: safe_call.js ****************************************************************************************************/ import { Component, NgModule } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.person = { getName: () => 'Bilbo' }; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <span [title]="'Your last name is ' + (person.getLastName?.() ?? 'unknown')"> Hello, {{ person.getName?.() }}! You are a Balrog: {{ person.getSpecies?.()?.()?.()?.()?.() || 'unknown' }} </span> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <span [title]="'Your last name is ' + (person.getLastName?.() ?? 'unknown')"> Hello, {{ person.getName?.() }}! You are a Balrog: {{ person.getSpecies?.()?.()?.()?.()?.() || 'unknown' }} </span> `, standalone: false }] }] }); export class MyModule { } MyModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); MyModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule, declarations: [MyApp] }); MyModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyModule }); i0.ɵɵngDeclareClassMe
008067
import {Component, NgModule} from '@angular/core'; @Component({ template: ` <span>Safe Property: {{ p?.a?.b?.c?.d }}</span> <span>Safe Keyed: {{ p?.['a']?.['b']?.['c']?.['d'] }}</span> <span>Mixed Property: {{ p?.a?.b.c.d?.e?.f?.g.h }}</span> <span>Mixed Property and Keyed: {{ p.a['b'].c.d?.['e']?.['f']?.g['h']['i']?.j.k }}</span> `, standalone: false }) export class MyApp { p: any = null; } @NgModule({declarations: [MyApp]}) export class MyModule { }
008110
import {Component} from '@angular/core'; @Component({ template: ` @for (item of items; track item) { @let outerFirst = $first; @for (subitem of item.children; track subitem) { @let innerFirst = $first; {{outerFirst || innerFirst}} } } `, }) export class MyApp { items: {children: any[]}[] = []; }
008195
import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-component', template: '<div></div>', standalone: false }) export class MyComponent { } @NgModule({declarations: [MyComponent]}) export class MyModule { }
008211
.0-PLACEHOLDER", ngImport: i0, type: LazyDep, deps: [], target: i0.ɵɵFactoryTarget.Directive }); LazyDep.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: LazyDep, isStandalone: true, selector: "lazy-dep", ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: LazyDep, decorators: [{ type: Directive, args: [{ selector: 'lazy-dep' }] }] }); export class LoadingDep { } LoadingDep.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: LoadingDep, deps: [], target: i0.ɵɵFactoryTarget.Directive }); LoadingDep.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: LoadingDep, isStandalone: true, selector: "loading-dep", ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: LoadingDep, decorators: [{ type: Directive, args: [{ selector: 'loading-dep' }] }] }); export class MyApp { } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: true, selector: "ng-component", ngImport: i0, template: ` <div> <eager-dep/> @defer { <lazy-dep/> } @loading { <loading-dep/> } </div> `, isInline: true, dependencies: [{ kind: "directive", type: EagerDep, selector: "eager-dep" }, { kind: "directive", type: LoadingDep, selector: "loading-dep" }], deferBlockDependencies: [() => [LazyDep]] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> <eager-dep/> @defer { <lazy-dep/> } @loading { <loading-dep/> } </div> `, imports: [EagerDep, LazyDep, LoadingDep], }] }] }); /**************************************************************************************************** * PARTIAL FILE: deferred_with_local_deps.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class EagerDep { static ɵfac: i0.ɵɵFactoryDeclaration<EagerDep, never>; static ɵdir: i0.ɵɵDirectiveDeclaration<EagerDep, "eager-dep", never, {}, {}, never, never, true, never>; } export declare class LazyDep { static ɵfac: i0.ɵɵFactoryDeclaration<LazyDep, never>; static ɵdir: i0.ɵɵDirectiveDeclaration<LazyDep, "lazy-dep", never, {}, {}, never, never, true, never>; } export declare class LoadingDep { static ɵfac: i0.ɵɵFactoryDeclaration<LoadingDep, never>; static ɵdir: i0.ɵɵDirectiveDeclaration<LoadingDep, "loading-dep", never, {}, {}, never, never, true, never>; } export declare class MyApp { static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_without_deps_followed_by_one_with.js ****************************************************************************************************/ import { Component, Directive } from '@angular/core'; import * as i0 from "@angular/core"; export class LazyDep { } LazyDep.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: LazyDep, deps: [], target: i0.ɵɵFactoryTarget.Directive }); LazyDep.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: LazyDep, isStandalone: true, selector: "lazy-dep", ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: LazyDep, decorators: [{ type: Directive, args: [{ selector: 'lazy-dep', }] }] }); export class MyApp { } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: true, selector: "ng-component", ngImport: i0, template: ` <div> @defer { I'm so independent! } @defer { <lazy-dep/> } </div> `, isInline: true, deferBlockDependencies: [null, () => [LazyDep]] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <div> @defer { I'm so independent! } @defer { <lazy-dep/> } </div> `, imports: [LazyDep], }] }] }); /**************************************************************************************************** * PARTIAL FILE: deferred_without_deps_followed_by_one_with.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class LazyDep { static ɵfac: i0.ɵɵFactoryDeclaration<LazyDep, never>; static ɵdir: i0.ɵɵDirectiveDeclaration<LazyDep, "lazy-dep", never, {}, {}, never, never, true, never>; } export declare class MyApp { static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_with_external_deps_eager.js ****************************************************************************************************/ import { Directive } from '@angular/core'; import * as i0 from "@angular/core"; export class EagerDep { } EagerDep.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: EagerDep, deps: [], target: i0.ɵɵFactoryTarget.Directive }); EagerDep.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: EagerDep, isStandalone: true, selector: "eager-dep", ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: EagerDep, decorators: [{ type: Directive, args: [{ selector: 'eager-dep' }] }] }); /**************************************************************************************************** * PARTIAL FILE: deferred_with_external_deps_eager.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class EagerDep { static ɵfac: i0.ɵɵFactoryDeclaration<EagerDep, never>; static ɵdir: i0.ɵɵDirectiveDeclaratio
008212
<EagerDep, "eager-dep", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_with_external_deps_lazy.js ****************************************************************************************************/ import { Directive } from '@angular/core'; import * as i0 from "@angular/core"; export class LazyDep { } LazyDep.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: LazyDep, deps: [], target: i0.ɵɵFactoryTarget.Directive }); LazyDep.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: LazyDep, isStandalone: true, selector: "lazy-dep", ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: LazyDep, decorators: [{ type: Directive, args: [{ selector: 'lazy-dep', }] }] }); /**************************************************************************************************** * PARTIAL FILE: deferred_with_external_deps_lazy.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class LazyDep { static ɵfac: i0.ɵɵFactoryDeclaration<LazyDep, never>; static ɵdir: i0.ɵɵDirectiveDeclaration<LazyDep, "lazy-dep", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_with_external_deps_loading.js ****************************************************************************************************/ import { Directive } from '@angular/core'; import * as i0 from "@angular/core"; export class LoadingDep { } LoadingDep.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: LoadingDep, deps: [], target: i0.ɵɵFactoryTarget.Directive }); LoadingDep.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: LoadingDep, isStandalone: true, selector: "loading-dep", ngImport: i0 }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: LoadingDep, decorators: [{ type: Directive, args: [{ selector: 'loading-dep' }] }] }); /**************************************************************************************************** * PARTIAL FILE: deferred_with_external_deps_loading.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class LoadingDep { static ɵfac: i0.ɵɵFactoryDeclaration<LoadingDep, never>; static ɵdir: i0.ɵɵDirectiveDeclaration<LoadingDep, "loading-dep", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_with_external_deps.js ****************************************************************************************************/ import { Component } from '@angular/core'; import { EagerDep } from './deferred_with_external_deps_eager'; import { LoadingDep } from './deferred_with_external_deps_loading'; import * as i0 from "@angular/core"; export class MyApp { } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: true, selector: "ng-component", ngImport: i0, template: ` <div> <eager-dep/> @defer { <lazy-dep/> } @loading { <loading-dep/> } </div> `, isInline: true, dependencies: [{ kind: "directive", type: EagerDep, selector: "eager-dep" }, { kind: "directive", type: LoadingDep, selector: "loading-dep" }], deferBlockDependencies: [() => [import("./deferred_with_external_deps_lazy").then(m => m.LazyDep)]] }); i0.ɵɵngDeclareClassMetadataAsync({ minVersion: "18.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, resolveDeferredDeps: () => [import("./deferred_with_external_deps_lazy").then(m => m.LazyDep)], resolveMetadata: LazyDep => ({ decorators: [{ type: Component, args: [{ template: ` <div> <eager-dep/> @defer { <lazy-dep/> } @loading { <loading-dep/> } </div> `, imports: [EagerDep, LazyDep, LoadingDep], }] }], ctorParameters: null, propDecorators: null }) }); /**************************************************************************************************** * PARTIAL FILE: deferred_with_external_deps.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_with_triggers.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.isReady = true; } isVisible() { return false; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` {{message}} @defer ( when isVisible() || isReady; on idle, timer(1337); on immediate, hover(button); on interaction(button); on viewport(button)) { {{message}} } @placeholder { <button #button>Click me</button> } `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` {{message}} @defer ( when isVisible() || isReady; on idle, timer(1337); on immediate, hover(button); on interaction(button); on viewport(button)) { {{message}} } @placeholder { <button #button>Click me</button> } `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: deferred_with_triggers.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; isReady: boolean; isVisible(): boolean; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_with_prefetch_triggers.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; this.isReady = true; } isVisible() { return false; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` {{message}} @defer ( prefetch when isVisible() || isR
008214
ntDeclaration<MyApp, "ng-component", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_interaction_same_view_trigger.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` {{message}} @defer (on interaction(button); prefetch on interaction(button)) {} <div> <div> <div> <button #button>Click me</button> </div> </div> </div> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` {{message}} @defer (on interaction(button); prefetch on interaction(button)) {} <div> <div> <div> <button #button>Click me</button> </div> </div> </div> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: deferred_interaction_same_view_trigger.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_interaction_parent_view_trigger.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` <ng-template> {{message}} <button #button>Click me</button> <ng-template> <ng-template> @defer (on interaction(button); prefetch on interaction(button)) {} </ng-template> </ng-template> </ng-template> `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` <ng-template> {{message}} <button #button>Click me</button> <ng-template> <ng-template> @defer (on interaction(button); prefetch on interaction(button)) {} </ng-template> </ng-template> </ng-template> `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: deferred_interaction_parent_view_trigger.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_interaction_placeholder_trigger.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` {{message}} @defer (on interaction(button); prefetch on interaction(button)) { Main } @placeholder { <div> <div> <button #button>Click me</button> </div> </div> } `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` {{message}} @defer (on interaction(button); prefetch on interaction(button)) { Main } @placeholder { <div> <div> <button #button>Click me</button> </div> </div> } `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: deferred_interaction_placeholder_trigger.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: deferred_with_implicit_triggers.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; export class MyApp { constructor() { this.message = 'hello'; } } MyApp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyApp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: MyApp, isStandalone: false, selector: "ng-component", ngImport: i0, template: ` @defer (on hover, interaction, viewport; prefetch on hover, interaction, viewport) { {{message}} } @placeholder { <button>Click me</button> } `, isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyApp, decorators: [{ type: Component, args: [{ template: ` @defer (on hover, interaction, viewport; prefetch on hover, interaction, viewport) { {{message}} } @placeholder { <button>Click me</button> } `, standalone: false }] }] }); /**************************************************************************************************** * PARTIAL FILE: deferred_with_implicit_triggers.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class MyApp { message: string; static ɵfac: i0.ɵɵFactoryDeclaration<MyApp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<MyApp, "ng-component", never, {}, {}, never, never, false, never>; } /**************************************************************************************************** * PARTIAL FILE: defer_deps_ext.js **********************************************************************
008216
ferredDeps: () => [import("./defer_default_deps_ext").then(m => m.default)], resolveMetadata: CmpA => ({ decorators: [{ type: Component, args: [{ selector: 'test-cmp', imports: [CmpA, LocalDep], template: ` @defer { <cmp-a /> <local-dep /> } `, }] }], ctorParameters: null, propDecorators: null }) }); /**************************************************************************************************** * PARTIAL FILE: defer_default_deps.d.ts ****************************************************************************************************/ import * as i0 from "@angular/core"; export declare class LocalDep { static ɵfac: i0.ɵɵFactoryDeclaration<LocalDep, never>; static ɵcmp: i0.ɵɵComponentDeclaration<LocalDep, "local-dep", never, {}, {}, never, never, true, never>; } export declare class TestCmp { static ɵfac: i0.ɵɵFactoryDeclaration<TestCmp, never>; static ɵcmp: i0.ɵɵComponentDeclaration<TestCmp, "test-cmp", never, {}, {}, never, never, true, never>; } /**************************************************************************************************** * PARTIAL FILE: lazy_with_blocks.js ****************************************************************************************************/ import { Component } from '@angular/core'; import * as i0 from "@angular/core"; class MyLazyCmp { } MyLazyCmp.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyLazyCmp, deps: [], target: i0.ɵɵFactoryTarget.Component }); MyLazyCmp.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "14.0.0", version: "0.0.0-PLACEHOLDER", type: MyLazyCmp, isStandalone: true, selector: "my-lazy-cmp", ngImport: i0, template: 'Hi!', isInline: true }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: MyLazyCmp, decorators: [{ type: Component, args: [{ selector: 'my-lazy-cmp', template: 'Hi!', }] }] }); class SimpleComponent { constructor() { this.isVisible = false; } ngOnInit() { setTimeout(() => { // This changes the triggering condition of the defer block, // but it should be ignored and the placeholder content should be visible. this.isVisible = true; }); } } SimpleComponent.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: SimpleComponent, deps: [], target: i0.ɵɵFactoryTarget.Component }); SimpleComponent.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "0.0.0-PLACEHOLDER", type: SimpleComponent, isStandalone: true, selector: "app", ngImport: i0, template: ` Visible: {{ isVisible }}. @defer (when isVisible) { <my-lazy-cmp /> } @loading { Loading... } @placeholder { Placeholder! } @error { Failed to load dependencies :( } `, isInline: true, deferBlockDependencies: [() => [MyLazyCmp]] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "0.0.0-PLACEHOLDER", ngImport: i0, type: SimpleComponent, decorators: [{ type: Component, args: [{ selector: 'app', imports: [MyLazyCmp], template: ` Visible: {{ isVisible }}. @defer (when isVisible) { <my-lazy-cmp /> } @loading { Loading... } @placeholder { Placeholder! } @error { Failed to load dependencies :( } ` }] }] }); /**************************************************************************************************** * PARTIAL FILE: lazy_with_blocks.d.ts ****************************************************************************************************/ export {};
008409
mbol identity', () => { it('should recompile components when their declaration name changes', () => { // Testing setup: component Cmp depends on component Dep, which is directly exported. // // During the test, Dep's name is changed while keeping its public API the same. The test // verifies that Cmp is re-emitted. env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<dep></dep>', standalone: false, }) export class Cmp {} `, ); env.write( 'dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', standalone: false, }) export class Dep {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep] }) export class Mod {} `, ); env.driveMain(); env.write( 'dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', standalone: false, }) export class ChangedDep {} // Dep renamed to ChangedDep. `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {ChangedDep} from './dep'; @NgModule({ declarations: [Cmp, ChangedDep] }) export class Mod {} `, ); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep and Mod were directly updated. '/dep.js', '/mod.js', // Cmp required a re-emit because the name of Dep changed. '/cmp.js', ]); }); it('should not recompile components that use a local directive', () => { // Testing setup: a single source file 'cmp.ts' declares components `Cmp` and `Dir`, where // `Cmp` uses `Dir` in its template. This test verifies that the local reference of `Cmp` // that is emitted into `Dir` does not inadvertently cause `cmp.ts` to be emitted even when // nothing changed. env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', standalone: false, }) export class Dep {} @Component({ selector: 'cmp', template: '<dep></dep>', standalone: false, }) export class Cmp {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp, Dep} from './cmp'; @NgModule({ declarations: [Cmp, Dep] }) export class Mod {} `, ); env.driveMain(); env.invalidateCachedFile('mod.ts'); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Only `mod.js` should be written because it was invalidated. '/mod.js', ]); }); it('should recompile components when the name by which they are exported changes', () => { // Testing setup: component Cmp depends on component Dep, which is directly exported. // // During the test, Dep's exported name is changed while keeping its declaration name the // same. The test verifies that Cmp is re-emitted. env.write( 'cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp', template: '<dep></dep>', standalone: false, }) export class Cmp {} `, ); env.write( 'dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', standalone: false, }) export class Dep {} `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {Dep} from './dep'; @NgModule({ declarations: [Cmp, Dep] }) export class Mod {} `, ); env.driveMain(); env.write( 'dep.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'dep', template: 'Dep', standalone: false, }) class Dep {} export {Dep as ChangedDep}; // the export name of Dep is changed. `, ); env.write( 'mod.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {ChangedDep} from './dep'; @NgModule({ declarations: [Cmp, ChangedDep] }) export class Mod {} `, ); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // Dep and Mod were directly updated. '/dep.js', '/mod.js', // Cmp required a re-emit because the exported name of Dep changed. '/cmp.js', ]); }); it('should recompile components when a re-export is renamed', () => { // Testing setup: CmpUser uses CmpDep in its template. CmpDep is both directly and // indirectly exported, and the compiler is guided into using the indirect export. // // During the test, the indirect export name is changed, and the test verifies that CmpUser // is re-emitted. env.write( 'cmp-user.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'cmp-user', template: '<cmp-dep></cmp-dep>', standalone: false, }) export class CmpUser {} `, ); env.write( 'cmp-dep.ts', ` import {Component} from '@angular/core'; export {CmpDep as CmpDepExport}; @Component({ selector: 'cmp-dep', template: 'Dep', standalone: false, }) class CmpDep {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {CmpDepExport} from './cmp-dep'; @NgModule({ declarations: [CmpUser, CmpDepExport] }) export class Module {} `, ); env.driveMain(); // Verify that the reference emitter used the export of `CmpDep` that appeared first in // the source, i.e. `CmpDepExport`. const userCmpJs = env.getContents('cmp-user.js'); expect(userCmpJs).toContain('CmpDepExport'); env.write( 'cmp-dep.ts', ` import {Component} from '@angular/core'; export {CmpDep as CmpDepExport2}; @Component({ selector: 'cmp-dep', template: 'Dep', standalone: false, }) class CmpDep {} `, ); env.write( 'module.ts', ` import {NgModule} from '@angular/core'; import {CmpUser} from './cmp-user'; import {CmpDepExport2} from './cmp-dep'; @NgModule({ declarations: [CmpUser, CmpDepExport2] }) export class Module {} `, ); env.flushWrittenFileTracking(); env.driveMain(); expectToHaveWritten([ // CmpDep and its module were directly updated. '/cmp-dep.js', '/module.js', // CmpUser required a re-emit because it was previous emitted as `CmpDepExport`, but // that export has since been renamed. '/cmp-user.js', ]); // Verify that `CmpUser` now correctly imports `CmpDep` using its renamed // re-export `CmpDepExport2`. const userCmp2Js = env.getContents('cmp-user.js'); expect(userCmp2Js).toContain('CmpDepExport2'); }); it('
008424
compile a standalone component that imports an NgModule', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class TestDir {} @NgModule({ declarations: [TestDir], exports: [TestDir], }) export class TestModule {} @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [TestModule], }) export class TestCmp {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('dependencies: [TestModule, TestDir]'); }); it('should allow nested arrays in standalone component imports', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir {} export const DIRECTIVES = [TestDir]; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [DIRECTIVES], }) export class TestCmp {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('dependencies: [TestDir]'); }); it('should deduplicate standalone component imports', () => { env.write( 'test.ts', ` import {Component, Directive} from '@angular/core'; @Directive({ selector: '[dir]', standalone: true, }) export class TestDir {} export const DIRECTIVES = [TestDir]; @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [TestDir, DIRECTIVES], }) export class TestCmp {} `, ); env.driveMain(); expect(env.getContents('test.js')).toContain('dependencies: [TestDir]'); }); it('should error when a standalone component imports a non-standalone entity', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class TestDir {} @NgModule({ declarations: [TestDir], exports: [TestDir], }) export class TestModule {} @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [TestDir], }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_IMPORT_NOT_STANDALONE)); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('TestDir'); // The diagnostic produced here should suggest that the directive be imported via its // NgModule instead. expect(diags[0].relatedInformation).not.toBeUndefined(); expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![0])).toEqual('TestModule'); expect(diags[0].relatedInformation![0].messageText).toMatch( /It can be imported using its '.*' NgModule instead./, ); }); it('should error when a standalone component imports a ModuleWithProviders using a foreign function', () => { env.write( 'test.ts', ` import {Component, ModuleWithProviders, NgModule} from '@angular/core'; @NgModule({}) export class TestModule {} declare function moduleWithProviders(): ModuleWithProviders<TestModule>; @Component({ selector: 'test-cmp', template: '<div></div>', standalone: true, // @ts-ignore imports: [moduleWithProviders()], }) export class TestCmpWithLiteralImports {} const IMPORTS = [moduleWithProviders()]; @Component({ selector: 'test-cmp', template: '<div></div>', standalone: true, // @ts-ignore imports: IMPORTS, }) export class TestCmpWithReferencedImports {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_UNKNOWN_IMPORT)); // The import occurs within the array literal, such that the error can be reported for // the specific import that is rejected. expect(getSourceCodeForDiagnostic(diags[0])).toEqual('moduleWithProviders()'); expect(diags[1].code).toBe(ngErrorCode(ErrorCode.COMPONENT_UNKNOWN_IMPORT)); // The import occurs in a referenced variable, which reports the error on the full // `imports` expression. expect(getSourceCodeForDiagnostic(diags[1])).toEqual('IMPORTS'); }); it('should error when a standalone component imports a ModuleWithProviders', () => { env.write( 'test.ts', ` import {Component, ModuleWithProviders, NgModule} from '@angular/core'; @NgModule({}) export class TestModule { static forRoot(): ModuleWithProviders<TestModule> { return {ngModule: TestModule}; } } @Component({ selector: 'test-cmp', template: '<div></div>', standalone: true, // @ts-ignore imports: [TestModule.forRoot()], }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_UNKNOWN_IMPORT)); // The static interpreter does not track source locations for locally evaluated functions, // so the error is reported on the full `imports` expression. expect(getSourceCodeForDiagnostic(diags[0])).toEqual('[TestModule.forRoot()]'); }); it('should error when a standalone component imports a non-standalone entity, with a specific error when that entity is not exported', () => { env.write( 'test.ts', ` import {Component, Directive, NgModule} from '@angular/core'; @Directive({ selector: '[dir]', standalone: false, }) export class TestDir {} @NgModule({ declarations: [TestDir], }) export class TestModule {} @Component({ selector: 'test-cmp', template: '<div dir></div>', standalone: true, imports: [TestDir], }) export class TestCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].code).toBe(ngErrorCode(ErrorCode.COMPONENT_IMPORT_NOT_STANDALONE)); expect(getSourceCodeForDiagnostic(diags[0])).toEqual('TestDir'); expect(diags[0].relatedInformation).not.toBeUndefined(); expect(getSourceCodeForDiagnostic(diags[0].relatedInformation![0])).toEqual('TestModule'); expect(diags[0].relatedInformation![0].messageText).toEqual( `It's declared in the 'TestModule' NgModule, but is not exported. Consider exporting it and importing the NgModule instead.`, ); }); it('should type-check standalone component templates', () => { env.write( 'test.ts', ` import {Component, Input, NgModule} from '@angular/core'; @Component({ selector: 'not-standalone', template: '', standalone: false, }) export class NotStandaloneCmp { @Input() value!: string; } @NgModule({ declarations: [NotStandaloneCmp], exports: [NotStandaloneCmp], }) export class NotStandaloneModule {} @Component({ standalone: true, selector: 'is-standalone', template: '', }) export class IsStandaloneCmp { @Input() value!: string; } @Component({ standalone: true, selector: 'test-cmp', imports: [NotStandaloneModule, IsStandaloneCmp], template: '<not-standalone [value]="3"></not-standalone><is-standalone [value]="true"></is-standalone>', }) export class TestCmp {} `, ); const diags = env.driveDiagnostics().map((diag) => diag.messageText); expect(diags.length).toBe(2); expect(diags).toContain(`Type 'number' is not assignable to type 'string'.`); expect(diags).toContain(`Type 'boolean' is not assignable to type 'string'.`); }); it
008462
ng with the DOM schema', () => { beforeEach(() => { env.tsconfig({fullTemplateTypeCheck: false}); }); it('should check for unknown elements', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<foo>test</foo>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`'foo' is not a known element: 1. If 'foo' is an Angular component, then verify that it is part of this module. 2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`); }); it('should check for unknown elements in standalone components', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<foo>test</foo>', standalone: true, }) export class FooCmp {} @NgModule({ imports: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`'foo' is not a known element: 1. If 'foo' is an Angular component, then verify that it is included in the '@Component.imports' of this component. 2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@Component.schemas' of this component.`); }); it('should check for unknown properties in standalone components', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'my-comp', template: '...', standalone: true, }) export class MyComp {} @Component({ selector: 'blah', imports: [MyComp], template: '<my-comp [foo]="true"></my-comp>', standalone: true, }) export class FooCmp {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText) .toMatch(`Can't bind to 'foo' since it isn't a known property of 'my-comp'. 1. If 'my-comp' is an Angular component and it has 'foo' input, then verify that it is included in the '@Component.imports' of this component. 2. If 'my-comp' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@Component.schemas' of this component to suppress this message. 3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@Component.schemas' of this component.`); }); it('should have a descriptive error for unknown elements that contain a dash', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<my-foo>test</my-foo>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`'my-foo' is not a known element: 1. If 'my-foo' is an Angular component, then verify that it is part of this module. 2. If 'my-foo' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`); }); it('should have a descriptive error for unknown elements that contain a dash in standalone components', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<my-foo>test</my-foo>', standalone: true, }) export class FooCmp {} @NgModule({ imports: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe(`'my-foo' is not a known element: 1. If 'my-foo' is an Angular component, then verify that it is included in the '@Component.imports' of this component. 2. If 'my-foo' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@Component.schemas' of this component to suppress this message.`); }); it('should check for unknown properties', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<div [foo]="1">test</div>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Can't bind to 'foo' since it isn't a known property of 'div'.`, ); }); it('should have a descriptive error for unknown properties with an "ng-" prefix', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<div [foo]="1">test</div>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText).toBe( `Can't bind to 'foo' since it isn't a known property of 'div'.`, ); }); it('should convert property names when binding special properties', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<label [for]="test">', standalone: false, }) export class FooCmp { test: string = 'test'; } @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); // Should not be an error to bind [for] of <label>, even though the actual property in the // DOM schema. expect(diags.length).toBe(0); }); it('should produce diagnostics for custom-elements-style elements when not using the CUSTOM_ELEMENTS_SCHEMA', () => { env.write( 'test.ts', ` import {Component, NgModule} from '@angular/core'; @Component({ selector: 'blah', template: '<custom-element [foo]="1">test</custom-element>', standalone: false, }) export class FooCmp {} @NgModule({ declarations: [FooCmp], }) export class FooModule {} `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(2); expect(diags[0].messageText).toBe(`'custom-element' is not a known element: 1. If 'custom-element' is an Angular component, then verify that it is part of this module. 2. If 'custom-element' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`); expect(diags[1].messageText) .toBe(`Can't bind to 'foo' since it isn't a known property of 'custom-element'. 1. If 'custom-element' is an Angular component and it has 'foo' input, then verify that it is part of this module. 2. If 'custom-element' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. 3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`); }); it('should not produce
008468
it('should check bindings inside if blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (expr) { {{does_not_exist_main}} } @else if (expr1) { {{does_not_exist_one}} } @else if (expr2) { {{does_not_exist_two}} } @else { {{does_not_exist_else}} } \`, standalone: true, }) export class Main { expr = false; expr1 = false; expr2 = false; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist_main' does not exist on type 'Main'.`, `Property 'does_not_exist_one' does not exist on type 'Main'.`, `Property 'does_not_exist_two' does not exist on type 'Main'.`, `Property 'does_not_exist_else' does not exist on type 'Main'.`, ]); }); it('should check bindings of if block expressions', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (does_not_exist_main) { main } @else if (does_not_exist_one) { one } @else if (does_not_exist_two) { two } \`, standalone: true, }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist_main' does not exist on type 'Main'.`, `Property 'does_not_exist_one' does not exist on type 'Main'.`, `Property 'does_not_exist_two' does not exist on type 'Main'.`, ]); }); it('should check aliased if block expression', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`@if (value === 1; as alias) { {{acceptsNumber(alias)}} }\`, standalone: true, }) export class Main { value = 1; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'boolean' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type of the if alias', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`@if (value; as alias) { {{acceptsNumber(alias)}} }\`, standalone: true, }) export class Main { value: 'one' | 0 = 0; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type of the if alias used in a listener', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`@if (value; as alias) { <button (click)="acceptsNumber(alias)"></button> }\`, standalone: true, }) export class Main { value: 'one' | 0 = 0; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow types inside the expression, even if aliased', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`@if (value; as alias) { {{ value.length }} }\`, standalone: true, }) export class Main { value!: string|undefined; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should narrow signal reads when aliased', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \`@if (value(); as alias) { {{ alias.length }} }\`, standalone: true, }) export class Main { value!: () => string|undefined; } `, ); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should not expose the aliased expression outside of the main block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (value === 0; as alias) { main block } @else { {{alias}} } \`, standalone: true, }) export class Main { value = 1; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'alias' does not exist on type 'Main'.`, ]); }); it('should expose alias to nested if blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (value === 1; as alias) { @if (alias) { {{acceptsNumber(alias)}} } } \`, standalone: true, }) export class Main { value = 1; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'boolean' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type inside if blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (expr === 1) { main block } @else { {{acceptsNumber(expr)}} } \`, standalone: true, }) export class Main { expr: 'hello' | 1 = 'hello'; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type in listeners inside if blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @if (expr === 'hello') { <button (click)="acceptsNumber(expr)"></button> } \`, standalone: true, }) export class Main { expr: 'hello' | 1 = 'hello'; acceptsNumber(value: number) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'string' is not assignable to parameter of type 'number'.`, ]); }); it('should narrow the type in list
008471
beforeEach(() => { // `fullTemplateTypeCheck: true` is necessary so content inside `ng-template` is checked. env.tsconfig({fullTemplateTypeCheck: true}); }); it('should check bindings inside of for loop blocks', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item) { {{does_not_exist_main}} } @empty { {{does_not_exist_empty}} } \`, }) export class Main { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist_main' does not exist on type 'Main'.`, `Property 'does_not_exist_empty' does not exist on type 'Main'.`, ]); }); it('should check the expression of a for loop block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '@for (item of does_not_exist; track item) {hello}', }) export class Main {} `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'does_not_exist' does not exist on type 'Main'.`, ]); }); it('should check the type of the item of a for loop block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '@for (item of items; track item) { {{acceptsString(item)}} }', }) export class Main { items = [1, 2, 3]; acceptsString(value: string) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should check the type of implicit variables for loop block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item) { {{acceptsString($index)}} {{acceptsString($first)}} {{acceptsString($last)}} {{acceptsString($even)}} {{acceptsString($odd)}} {{acceptsString($count)}} } \`, }) export class Main { items = []; acceptsString(value: string) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should check the type of aliased implicit variables for loop block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item; let i = $index, f = $first, l = $last, e = $even, o = $odd, c = $count) { {{acceptsString(i)}} {{acceptsString(f)}} {{acceptsString(l)}} {{acceptsString(e)}} {{acceptsString(o)}} {{acceptsString(c)}} } \`, }) export class Main { items = []; acceptsString(value: string) { return value; } } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'boolean' is not assignable to parameter of type 'string'.`, `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should not expose variables from the main block to the empty block', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item) { Hello } @empty { {{item}} {{$index}} } \`, }) export class Main { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Property 'item' does not exist on type 'Main'. Did you mean 'items'?`, `Property '$index' does not exist on type 'Main'.`, ]); }); it('should continue exposing implicit loop variables under their old names when they are aliased', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: '@for (item of items; track item; let alias = $index) { {{acceptsString($index)}} }', }) export class Main { items = []; acceptsString(str: string) {} } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Argument of type 'number' is not assignable to parameter of type 'string'.`, ]); }); it('should not be able to write to loop template variables', () => { env.write( 'test.ts', ` import {Component} from '@angular/core'; @Component({ template: \` @for (item of items; track item) { <button (click)="$index = 1"></button> } \`, }) export class Main { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot use variable '$index' as the left-hand side of an assignment expression. Template variables are read-only.`, ]); }); it('should not be able to write to loop template variables in a two-way binding', () => { env.write( 'test.ts', ` import {Component, Directive, Input, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[twoWayDir]', standalone: true }) export class TwoWayDir { @Input() value: number = 0; @Output() valueChange: EventEmitter<number> = new EventEmitter(); } @Component({ template: \` @for (item of items; track item) { <button twoWayDir [(value)]="$index"></button> } \`, standalone: true, imports: [TwoWayDir] }) export class Main { items = []; } `, ); const diags = env.driveDiagnostics(); expect(diags.map((d) => ts.flattenDiagnosticMessageText(d.messageText, ''))).toEqual([ `Cannot use a non-signal variable '$index' in a two-way binding expression. Template variables are read-only.`, ]); }); it('should allow writes to signal-
008624
/** * @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 {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root', }) export class Service {}
008627
/** * @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, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {ServerModule} from '@angular/platform-server'; import {RouterModule} from '@angular/router'; import {LazyModule} from './root_lazy'; @Component({ selector: 'root-app', template: '<router-outlet></router-outlet>', standalone: false, }) export class AppComponent {} export function children(): any { console.error('children', LazyModule); return LazyModule; } @NgModule({ imports: [ BrowserModule, ServerModule, RouterModule.forRoot([{path: '', pathMatch: 'prefix', loadChildren: children}], { initialNavigation: 'enabledBlocking', }), ], declarations: [AppComponent], bootstrap: [AppComponent], }) export class RootAppModule {}
009070
('for loop blocks', () => { it('should generate a for block', () => { const TEMPLATE = ` @for (item of items; track item) { {{main(item)}} } @empty { {{empty()}} } `; const result = tcb(TEMPLATE); expect(result).toContain('for (const _t1 of ((this).items)!) {'); expect(result).toContain('"" + ((this).main(_t1))'); expect(result).toContain('"" + ((this).empty())'); }); it('should generate a for block with implicit variables', () => { const TEMPLATE = ` @for (item of items; track item) { {{$index}} {{$first}} {{$last}} {{$even}} {{$odd}} {{$count}} } `; const result = tcb(TEMPLATE); expect(result).toContain('for (const _t1 of ((this).items)!) {'); expect(result).toContain('var _t2 = null! as number;'); expect(result).toContain('var _t3 = null! as boolean;'); expect(result).toContain('var _t4 = null! as boolean;'); expect(result).toContain('var _t5 = null! as boolean;'); expect(result).toContain('var _t6 = null! as boolean;'); expect(result).toContain('var _t7 = null! as number;'); expect(result).toContain('"" + (_t2) + (_t3) + (_t4) + (_t5) + (_t6) + (_t7)'); }); it('should generate a for block with aliased variables', () => { const TEMPLATE = ` @for (item of items; track item; let i = $index, f = $first, l = $last, e = $even, o = $odd, c = $count) { {{i}} {{f}} {{l}} {{e}} {{o}} {{c}} } `; const result = tcb(TEMPLATE); expect(result).toContain('for (const _t1 of ((this).items)!) {'); expect(result).toContain('var _t2 = null! as number;'); expect(result).toContain('var _t3 = null! as boolean;'); expect(result).toContain('var _t4 = null! as boolean;'); expect(result).toContain('var _t5 = null! as boolean;'); expect(result).toContain('var _t6 = null! as boolean;'); expect(result).toContain('var _t7 = null! as number;'); expect(result).toContain('"" + (_t2) + (_t3) + (_t4) + (_t5) + (_t6) + (_t7)'); }); it('should read both implicit variables and their alias at the same time', () => { const TEMPLATE = ` @for (item of items; track item; let i = $index) { {{$index}} {{i}} } `; const result = tcb(TEMPLATE); expect(result).toContain('for (const _t1 of ((this).items)!) {'); expect(result).toContain('var _t2 = null! as number;'); expect(result).toContain('var _t3 = null! as number;'); expect(result).toContain('"" + (_t2) + (_t3)'); }); it('should read variable from a parent for loop', () => { const TEMPLATE = ` @for (item of items; track item; let indexAlias = $index) { {{item}} {{indexAlias}} @for (inner of item.items; track inner) { {{item}} {{indexAlias}} {{inner}} {{$index}} } } `; const result = tcb(TEMPLATE); expect(result).toContain('for (const _t1 of ((this).items)!) { var _t2 = null! as number;'); expect(result).toContain('"" + (_t1) + (_t2)'); expect(result).toContain('for (const _t3 of ((_t1).items)!) { var _t4 = null! as number;'); expect(result).toContain('"" + (_t1) + (_t2) + (_t3) + (_t4)'); }); it('should generate the tracking expression of a for loop', () => { const result = tcb(`@for (item of items; track trackingFn($index, item, prop)) {}`); expect(result).toContain('for (const _t1 of ((this).items)!) { var _t2 = null! as number;'); expect(result).toContain('(this).trackingFn(_t2, _t1, ((this).prop));'); }); it('should not generate the body of a for block when checkControlFlowBodies is disabled', () => { const TEMPLATE = ` @for (item of items; track item) { {{main(item)}} } @empty { {{empty()}} } `; const result = tcb(TEMPLATE, undefined, {checkControlFlowBodies: false}); expect(result).toContain('for (const _t1 of ((this).items)!) {'); expect(result).not.toContain('.main'); expect(result).not.toContain('.empty'); }); }); describe('let declarations', () => { it('should generate let declarations as constants', () => { const result = tcb(` @let one = 1; @let two = 2; @let sum = one + two; {{sum}} `); expect(result).toContain('const _t1 = (1);'); expect(result).toContain('const _t2 = (2);'); expect(result).toContain('const _t3 = ((_t1) + (_t2));'); expect(result).toContain('"" + (_t3);'); }); it('should rewrite references to let declarations inside event listeners', () => { const result = tcb(` @let value = 1; <button (click)="doStuff(value)"></button> `); expect(result).toContain('const _t1 = (1);'); expect(result).toContain('var _t2 = document.createElement("button");'); expect(result).toContain( '_t2.addEventListener("click", ($event): any => { (this).doStuff(_t1); });', ); }); }); describe('import generation', () => { const TEMPLATE = `<div dir [test]="null"></div>`; const DIRECTIVE: TestDeclaration = { type: 'directive', name: 'Dir', selector: '[dir]', inputs: { test: { isSignal: true, bindingPropertyName: 'test', classPropertyName: 'test', required: true, transform: null, }, }, }; it('should prefer namespace imports in type check files for new imports', () => { const result = tcb(TEMPLATE, [DIRECTIVE]); expect(result).toContain(`import * as i1 from '@angular/core';`); expect(result).toContain(`[i1.ɵINPUT_SIGNAL_BRAND_WRITE_TYPE]`); }); it('should re-use existing imports from original source files', () => { // This is especially important for inline type check blocks. // See: https://github.com/angular/angular/pull/53521#pullrequestreview-1778130879. const {templateTypeChecker, program, programStrategy} = setup([ { fileName: absoluteFrom('/test.ts'), templates: {'AppComponent': TEMPLATE}, declarations: [DIRECTIVE], source: ` import {Component} from '@angular/core'; // should be re-used class AppComponent {} export class Dir {} `, }, ]); // Trigger type check block generation. templateTypeChecker.getDiagnosticsForFile( getSourceFileOrError(program, absoluteFrom('/test.ts')), OptimizeFor.SingleFile, ); const testSf = getSourceFileOrError(programStrategy.getProgram(), absoluteFrom('/test.ts')); expect(testSf.text).toContain( `import { Component, ɵINPUT_SIGNAL_BRAND_WRITE_TYPE } from '@angular/core'; // should be re-used`, ); expect(testSf.text).toContain(`[ɵINPUT_SIGNAL_BRAND_WRITE_TYPE]`); }); }); });
009169
/** * @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 {AST, TmplAstNode, TmplAstTemplate} from '@angular/compiler'; import ts from 'typescript'; import {NgCompilerOptions} from '../../../../core/api'; import {ErrorCode, ExtendedTemplateDiagnosticName} from '../../../../diagnostics'; import {NgTemplateDiagnostic} from '../../../api'; import {TemplateCheckFactory, TemplateCheckWithVisitor, TemplateContext} from '../../api'; /** * The list of known control flow directives present in the `CommonModule`, * and their corresponding imports. * * Note: there is no `ngSwitch` here since it's typically used as a regular * binding (e.g. `[ngSwitch]`), however the `ngSwitchCase` and `ngSwitchDefault` * are used as structural directives and a warning would be generated. Once the * `CommonModule` is included, the `ngSwitch` would also be covered. */ export const KNOWN_CONTROL_FLOW_DIRECTIVES = new Map([ ['ngIf', {directive: 'NgIf', builtIn: '@if'}], ['ngFor', {directive: 'NgFor', builtIn: '@for'}], ['ngSwitchCase', {directive: 'NgSwitchCase', builtIn: '@switch with @case'}], ['ngSwitchDefault', {directive: 'NgSwitchDefault', builtIn: '@switch with @default'}], ]); /** * Ensures that there are no known control flow directives (such as *ngIf and *ngFor) * used in a template of a *standalone* component without importing a `CommonModule`. Returns * diagnostics in case such a directive is detected. * * Note: this check only handles the cases when structural directive syntax is used (e.g. `*ngIf`). * Regular binding syntax (e.g. `[ngIf]`) is handled separately in type checker and treated as a * hard error instead of a warning. */ class MissingControlFlowDirectiveCheck extends TemplateCheckWithVisitor<ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE> { override code = ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE as const; override run( ctx: TemplateContext<ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE>, component: ts.ClassDeclaration, template: TmplAstNode[], ) { const componentMetadata = ctx.templateTypeChecker.getDirectiveMetadata(component); // Avoid running this check for non-standalone components. if (!componentMetadata || !componentMetadata.isStandalone) { return []; } return super.run(ctx, component, template); } override visitNode( ctx: TemplateContext<ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE>, component: ts.ClassDeclaration, node: TmplAstNode | AST, ): NgTemplateDiagnostic<ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE>[] { if (!(node instanceof TmplAstTemplate)) return []; const controlFlowAttr = node.templateAttrs.find((attr) => KNOWN_CONTROL_FLOW_DIRECTIVES.has(attr.name), ); if (!controlFlowAttr) return []; const symbol = ctx.templateTypeChecker.getSymbolOfNode(node, component); if (symbol === null || symbol.directives.length > 0) { return []; } const sourceSpan = controlFlowAttr.keySpan || controlFlowAttr.sourceSpan; const directiveAndBuiltIn = KNOWN_CONTROL_FLOW_DIRECTIVES.get(controlFlowAttr.name); const errorMessage = `The \`*${controlFlowAttr.name}\` directive was used in the template, ` + `but neither the \`${directiveAndBuiltIn?.directive}\` directive nor the \`CommonModule\` was imported. ` + `Use Angular's built-in control flow ${directiveAndBuiltIn?.builtIn} or ` + `make sure that either the \`${directiveAndBuiltIn?.directive}\` directive or the \`CommonModule\` ` + `is included in the \`@Component.imports\` array of this component.`; const diagnostic = ctx.makeTemplateDiagnostic(sourceSpan, errorMessage); return [diagnostic]; } } export const factory: TemplateCheckFactory< ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE, ExtendedTemplateDiagnosticName.MISSING_CONTROL_FLOW_DIRECTIVE > = { code: ErrorCode.MISSING_CONTROL_FLOW_DIRECTIVE, name: ExtendedTemplateDiagnosticName.MISSING_CONTROL_FLOW_DIRECTIVE, create: (options: NgCompilerOptions) => { return new MissingControlFlowDirectiveCheck(); }, };
009386
/** * @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 'jasmine-ajax'; import { FetchBackend, HTTP_INTERCEPTORS, HttpBackend, HttpClient, HttpClientModule, HttpEvent, HttpEventType, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse, provideHttpClient, withFetch, } from '@angular/common/http'; import {importProvidersFrom, Injectable} from '@angular/core'; import {TestBed, waitForAsync} from '@angular/core/testing'; import {HttpClientBackendService, HttpClientInMemoryWebApiModule} from 'angular-in-memory-web-api'; import {Observable, zip} from 'rxjs'; import {concatMap, map, tap} from 'rxjs/operators'; import {Hero} from './fixtures/hero'; import {HeroInMemDataOverrideService} from './fixtures/hero-in-mem-data-override-service'; import {HeroInMemDataService} from './fixtures/hero-in-mem-data-service'; import {HeroService} from './fixtures/hero-service'; import {HttpClientHeroService} from './fixtures/http-client-hero-service';
009389
describe('HttpClient interceptor', () => { let http: HttpClient; let interceptors: HttpInterceptor[]; let httpBackend: HttpClientBackendService; /** * Test interceptor adds a request header and a response header */ @Injectable() class TestHeaderInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const reqClone = req.clone({setHeaders: {'x-test-req': 'req-test-header'}}); return next.handle(reqClone).pipe( map((event) => { if (event instanceof HttpResponse) { event = event.clone({headers: event.headers.set('x-test-res', 'res-test-header')}); } return event; }), ); } } beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientModule, HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}), ], providers: [ // Add test interceptor just for this test suite {provide: HTTP_INTERCEPTORS, useClass: TestHeaderInterceptor, multi: true}, ], }); http = TestBed.get(HttpClient); httpBackend = TestBed.get(HttpBackend); interceptors = TestBed.get(HTTP_INTERCEPTORS); }); // sanity test it('TestingModule should provide the test interceptor', () => { const ti = interceptors.find((i) => i instanceof TestHeaderInterceptor); expect(ti).toBeDefined(); }); it('should have GET request header from test interceptor', waitForAsync(() => { const handle = spyOn(httpBackend, 'handle').and.callThrough(); http.get<Hero[]>('api/heroes').subscribe((heroes) => { // HttpRequest is first arg of the first call to in-mem backend `handle` const req: HttpRequest<Hero[]> = handle.calls.argsFor(0)[0]; const reqHeader = req.headers.get('x-test-req'); expect(reqHeader).toBe('req-test-header'); expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); }, failRequest); })); it('should have GET response header from test interceptor', waitForAsync(() => { let gotResponse = false; const req = new HttpRequest<any>('GET', 'api/heroes'); http.request<Hero[]>(req).subscribe( (event) => { if (event.type === HttpEventType.Response) { gotResponse = true; const resHeader = event.headers.get('x-test-res'); expect(resHeader).toBe('res-test-header'); const heroes = event.body as Hero[]; expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); } }, failRequest, () => expect(gotResponse).toBe(true, 'should have seen Response event'), ); })); }); describe('HttpClient passThru', () => { let http: HttpClient; let httpBackend: HttpClientBackendService; let createPassThruBackend: jasmine.Spy; beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientModule, HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, { delay, passThruUnknownUrl: true, }), ], }); http = TestBed.get(HttpClient); httpBackend = TestBed.get(HttpBackend); createPassThruBackend = spyOn(<any>httpBackend, 'createPassThruBackend').and.callThrough(); }); beforeEach(() => { jasmine.Ajax.install(); }); afterEach(() => { jasmine.Ajax.uninstall(); }); it('can get heroes (no passthru)', waitForAsync(() => { http.get<Hero[]>('api/heroes').subscribe((heroes) => { expect(createPassThruBackend).not.toHaveBeenCalled(); expect(heroes.length).toBeGreaterThan(0, 'should have heroes'); }, failRequest); })); // `passthru` is NOT a collection in the data store // so requests for it should pass thru to the "real" server it('can GET passthru', waitForAsync(() => { jasmine.Ajax.stubRequest('api/passthru').andReturn({ 'status': 200, 'contentType': 'application/json', 'response': JSON.stringify([{id: 42, name: 'Dude'}]), }); http.get<any[]>('api/passthru').subscribe((passthru) => { expect(passthru.length).toBeGreaterThan(0, 'should have passthru data'); }, failRequest); })); it('can ADD to passthru', waitForAsync(() => { jasmine.Ajax.stubRequest('api/passthru').andReturn({ 'status': 200, 'contentType': 'application/json', 'response': JSON.stringify({id: 42, name: 'Dude'}), }); http.post<any>('api/passthru', {name: 'Dude'}).subscribe((passthru) => { expect(passthru).toBeDefined('should have passthru data'); expect(passthru.id).toBe(42, 'passthru object should have id 42'); }, failRequest); })); }); describe('Http dataEncapsulation = true', () => { let http: HttpClient; beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientModule, HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, { delay, dataEncapsulation: true, }), ], }); http = TestBed.get(HttpClient); }); it('can get heroes (encapsulated)', waitForAsync(() => { http .get<{data: any}>('api/heroes') .pipe(map((data) => data.data as Hero[])) .subscribe( (heroes) => expect(heroes.length).toBeGreaterThan(0, 'should have data.heroes'), failRequest, ); })); }); describe('when using the FetchBackend', () => { it('should be the an InMemory Service', () => { TestBed.configureTestingModule({ providers: [ provideHttpClient(withFetch()), importProvidersFrom( HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}), ), {provide: HeroService, useClass: HttpClientHeroService}, ], }); expect(TestBed.inject(HttpBackend)).toBeInstanceOf(HttpClientBackendService); }); it('should be a FetchBackend', () => { // In this test, providers order matters TestBed.configureTestingModule({ providers: [ importProvidersFrom( HttpClientInMemoryWebApiModule.forRoot(HeroInMemDataService, {delay}), ), provideHttpClient(withFetch()), {provide: HeroService, useClass: HttpClientHeroService}, ], }); expect(TestBed.inject(HttpBackend)).toBeInstanceOf(FetchBackend); }); }); }); /** * Fail a Jasmine test such that it displays the error object, * typically passed in the error path of an Observable.subscribe() */ function failRequest(err: any) { fail(JSON.stringify(err)); }
009566
t('should not emit valueChanges or statusChanges until blur', () => { const fixture = initTest(FormControlComp); const control: FormControl = new FormControl('', { validators: Validators.required, updateOn: 'blur', }); fixture.componentInstance.control = control; fixture.detectChanges(); const values: string[] = []; const sub = merge(control.valueChanges, control.statusChanges).subscribe((val) => values.push(val), ); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(values) .withContext('Expected no valueChanges or statusChanges on input.') .toEqual([]); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values) .withContext('Expected valueChanges and statusChanges on blur.') .toEqual(['Nancy', 'VALID']); sub.unsubscribe(); }); it('should not emit valueChanges or statusChanges on blur if value unchanged', () => { const fixture = initTest(FormControlComp); const control: FormControl = new FormControl('', { validators: Validators.required, updateOn: 'blur', }); fixture.componentInstance.control = control; fixture.detectChanges(); const values: string[] = []; const sub = merge(control.valueChanges, control.statusChanges).subscribe((val) => values.push(val), ); const input = fixture.debugElement.query(By.css('input')).nativeElement; dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values) .withContext('Expected no valueChanges or statusChanges if value unchanged.') .toEqual([]); input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(values) .withContext('Expected no valueChanges or statusChanges on input.') .toEqual([]); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID'], 'Expected valueChanges and statusChanges on blur if value changed.', ); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID'], 'Expected valueChanges and statusChanges not to fire again on blur unless value changed.', ); input.value = 'Bess'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID'], 'Expected valueChanges and statusChanges not to fire on input after blur.', ); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(values).toEqual( ['Nancy', 'VALID', 'Bess', 'VALID'], 'Expected valueChanges and statusChanges to fire again on blur if value changed.', ); sub.unsubscribe(); }); it('should mark as pristine properly if pending dirty', () => { const fixture = initTest(FormControlComp); const control = new FormControl('', {updateOn: 'blur'}); fixture.componentInstance.control = control; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'aa'; dispatchEvent(input, 'input'); fixture.detectChanges(); dispatchEvent(input, 'blur'); fixture.detectChanges(); control.markAsPristine(); expect(control.dirty).withContext('Expected control to become pristine.').toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.dirty).withContext('Expected pending dirty value to reset.').toBe(false); }); it('should update on blur with group updateOn', () => { const fixture = initTest(FormGroupComp); const control = new FormControl('', Validators.required); const formGroup = new FormGroup({login: control}, {updateOn: 'blur'}); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to remain unchanged until blur.') .toEqual(''); expect(control.valid) .withContext('Expected no validation to occur until blur.') .toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to change once control is blurred.') .toEqual('Nancy'); expect(control.valid) .withContext('Expected validation to run once control is blurred.') .toBe(true); }); it('should update on blur with array updateOn', () => { const fixture = initTest(FormArrayComp); const control = new FormControl('', Validators.required); const cityArray = new FormArray([control], {updateOn: 'blur'}); const formGroup = new FormGroup({cities: cityArray}); fixture.componentInstance.form = formGroup; fixture.componentInstance.cityArray = cityArray; fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input')).nativeElement; input.value = 'Nancy'; dispatchEvent(input, 'input'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to remain unchanged until blur.') .toEqual(''); expect(control.valid) .withContext('Expected no validation to occur until blur.') .toBe(false); dispatchEvent(input, 'blur'); fixture.detectChanges(); expect(control.value) .withContext('Expected value to change once control is blurred.') .toEqual('Nancy'); expect(control.valid) .withContext('Expected validation to run once control is blurred.') .toBe(true); }); it('should allow child control updateOn blur to override group updateOn', () => { const fixture = initTest(NestedFormGroupNameComp); const loginControl = new FormControl('', { validators: Validators.required, updateOn: 'change', }); const passwordControl = new FormControl('', Validators.required); const formGroup = new FormGroup( {signin: new FormGroup({login: loginControl, password: passwordControl})}, {updateOn: 'blur'}, ); fixture.componentInstance.form = formGroup; fixture.detectChanges(); const [loginInput, passwordInput] = fixture.debugElement.queryAll(By.css('input')); loginInput.nativeElement.value = 'Nancy'; dispatchEvent(loginInput.nativeElement, 'input'); fixture.detectChanges(); expect(loginControl.value).withContext('Expected value change on input.').toEqual('Nancy'); expect(loginControl.valid).withContext('Expected validation to run on input.').toBe(true); passwordInput.nativeElement.value = 'Carson'; dispatchEvent(passwordInput.nativeElement, 'input'); fixture.detectChanges(); expect(passwordControl.value) .withContext('Expected value to remain unchanged until blur.') .toEqual(''); expect(passwordControl.valid) .withContext('Expected no validation to occur until blur.') .toBe(false); dispatchEvent(passwordInput.nativeElement, 'blur'); fixture.detectChanges(); expect(passwordControl.value) .withContext('Expected value to change once control is blurred.') .toEqual('Carson'); expect(passwordControl.valid) .withContext('Expected validation to run once control is blurred.') .toBe(true); }); });
009571
t('should support rebound controls with rebound validators', () => { const fixture = initTest(ValidationBindingsForm); const form = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl(''), }); fixture.componentInstance.form = form; fixture.componentInstance.required = true; fixture.componentInstance.minLen = 3; fixture.componentInstance.maxLen = 3; fixture.componentInstance.pattern = '.{3,}'; fixture.detectChanges(); const newForm = new FormGroup({ 'login': new FormControl(''), 'min': new FormControl(''), 'max': new FormControl(''), 'pattern': new FormControl(''), }); fixture.componentInstance.form = newForm; fixture.detectChanges(); fixture.componentInstance.required = false; fixture.componentInstance.minLen = null!; fixture.componentInstance.maxLen = null!; fixture.componentInstance.pattern = null!; fixture.detectChanges(); expect(newForm.hasError('required', ['login'])).toEqual(false); expect(newForm.hasError('minlength', ['min'])).toEqual(false); expect(newForm.hasError('maxlength', ['max'])).toEqual(false); expect(newForm.hasError('pattern', ['pattern'])).toEqual(false); expect(newForm.valid).toEqual(true); }); it('should use async validators defined in the html', fakeAsync(() => { const fixture = initTest(UniqLoginWrapper, UniqLoginValidator); const form = new FormGroup({'login': new FormControl('')}); tick(); fixture.componentInstance.form = form; fixture.detectChanges(); expect(form.pending).toEqual(true); tick(100); expect(form.hasError('uniqLogin', ['login'])).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'expected'; dispatchEvent(input.nativeElement, 'input'); tick(100); expect(form.valid).toEqual(true); })); it('should use sync validators defined in the model', () => { const fixture = initTest(FormGroupComp); const form = new FormGroup({'login': new FormControl('aa', Validators.required)}); fixture.componentInstance.form = form; fixture.detectChanges(); expect(form.valid).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = ''; dispatchEvent(input.nativeElement, 'input'); expect(form.valid).toEqual(false); }); it('should use async validators defined in the model', fakeAsync(() => { const fixture = initTest(FormGroupComp); const control = new FormControl('', Validators.required, uniqLoginAsyncValidator('expected')); const form = new FormGroup({'login': control}); fixture.componentInstance.form = form; fixture.detectChanges(); tick(); expect(form.hasError('required', ['login'])).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'wrong value'; dispatchEvent(input.nativeElement, 'input'); expect(form.pending).toEqual(true); tick(); expect(form.hasError('uniqLogin', ['login'])).toEqual(true); input.nativeElement.value = 'expected'; dispatchEvent(input.nativeElement, 'input'); tick(); expect(form.valid).toEqual(true); })); it('async validator should not override result of sync validator', fakeAsync(() => { const fixture = initTest(FormGroupComp); const control = new FormControl( '', Validators.required, uniqLoginAsyncValidator('expected', 100), ); fixture.componentInstance.form = new FormGroup({'login': control}); fixture.detectChanges(); tick(); expect(control.hasError('required')).toEqual(true); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'expected'; dispatchEvent(input.nativeElement, 'input'); expect(control.pending).toEqual(true); input.nativeElement.value = ''; dispatchEvent(input.nativeElement, 'input'); tick(110); expect(control.valid).toEqual(false); })); it('should handle async validation changes in parent and child controls', fakeAsync(() => { const fixture = initTest(FormGroupComp); const control = new FormControl( '', Validators.required, asyncValidator((c) => !!c.value && c.value.length > 3, 100), ); const form = new FormGroup( {'login': control}, null, asyncValidator((c) => c.get('login')!.value.includes('angular'), 200), ); fixture.componentInstance.form = form; fixture.detectChanges(); tick(); // Initially, the form is invalid because the nested mandatory control is empty expect(control.hasError('required')).toEqual(true); expect(form.value).toEqual({'login': ''}); expect(form.invalid).toEqual(true); // Setting a value in the form control that will trigger the registered asynchronous // validation const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'angul'; dispatchEvent(input.nativeElement, 'input'); // The form control asynchronous validation is in progress (for 100 ms) expect(control.pending).toEqual(true); tick(100); // Now the asynchronous validation has resolved, and since the form control value // (`angul`) has a length > 3, the validation is successful expect(control.invalid).toEqual(false); // Even if the child control is valid, the form control is pending because it is still // waiting for its own validation expect(form.pending).toEqual(true); tick(100); // Login form control is valid. However, the form control is invalid because `angul` does // not include `angular` expect(control.invalid).toEqual(false); expect(form.pending).toEqual(false); expect(form.invalid).toEqual(true); // Setting a value that would be trigger "VALID" form state input.nativeElement.value = 'angular!'; dispatchEvent(input.nativeElement, 'input'); // Since the form control value changed, its asynchronous validation runs for 100ms expect(control.pending).toEqual(true); tick(100); // Even if the child control is valid, the form control is pending because it is still // waiting for its own validation expect(control.invalid).toEqual(false); expect(form.pending).toEqual(true); tick(100); // Now, the form is valid because its own asynchronous validation has resolved // successfully, because the form control value `angular` includes the `angular` string expect(control.invalid).toEqual(false); expect(form.pending).toEqual(false); expect(form.invalid).toEqual(false); })); it('should cancel observable properly between validation runs', fakeAsync(() => { const fixture = initTest(FormControlComp); const resultArr: number[] = []; fixture.componentInstance.control = new FormControl( '', null!, observableValidator(resultArr), ); fixture.detectChanges(); tick(100); expect(resultArr.length) .withContext(`Expected source observable to emit once on init.`) .toEqual(1); const input = fixture.debugElement.query(By.css('input')); input.nativeElement.value = 'a'; dispatchEvent(input.nativeElement, 'input'); fixture.detectChanges(); input.nativeElement.value = 'aa'; dispatchEvent(input.nativeElement, 'input'); fixture.detectChanges(); tick(100); expect(resultArr.length) .withContext(`Expected original observable to be canceled on the next value change.`) .toEqual(2); }));
009578
'should cleanup validators on a control used for multiple `formControlName` directives', () => { const fixture = initTest(NgForFormControlWithValidators, ViewValidatorA, AsyncViewValidatorA); fixture.detectChanges(); const newControl = new FormControl('b')!; const oldControl = fixture.componentInstance.form.get('login')!; const validatorSpy = validatorSpyOn(ViewValidatorA); const asyncValidatorSpy = validatorSpyOn(AsyncViewValidatorA); // Case 1: replace `login` form control with a new `FormControl` instance. fixture.componentInstance.form.removeControl('login'); fixture.componentInstance.form.addControl('login', newControl); fixture.detectChanges(); // Check that validators were called with a new control as a context // and each validator function was called for each control (so 3 times each). expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: newControl, count: 3}); validatorSpy.calls.reset(); asyncValidatorSpy.calls.reset(); // Calling `setValue` for the OLD control should NOT trigger validator calls. oldControl.setValue('SOME-OLD-VALUE'); expect(validatorSpy).not.toHaveBeenCalled(); expect(asyncValidatorSpy).not.toHaveBeenCalled(); // Calling `setValue` for the NEW (active) control should trigger validator calls. newControl.setValue('SOME-NEW-VALUE'); // Check that setting a value on a new control triggers validator calls. expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: newControl, count: 3}); // Case 2: update `logins` to render a new list of elements. fixture.componentInstance.logins = ['a', 'b', 'c', 'd', 'e', 'f']; fixture.detectChanges(); validatorSpy.calls.reset(); asyncValidatorSpy.calls.reset(); // Calling `setValue` for the NEW (active) control should trigger validator calls. newControl.setValue('SOME-NEW-VALUE-2'); // Check that setting a value on a new control triggers validator calls for updated set // of controls (one for each element in the `logins` array). expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: newControl, count: 6}); }); it('should cleanup directive-specific callbacks only', () => { const fixture = initTest(MultipleFormControls, ViewValidatorA, AsyncViewValidatorA); fixture.detectChanges(); const sharedControl = fixture.componentInstance.control; const validatorSpy = validatorSpyOn(ViewValidatorA); const asyncValidatorSpy = validatorSpyOn(AsyncViewValidatorA); sharedControl.setValue('b'); fixture.detectChanges(); // Check that validators were called for each `formControlName` directive instance // (2 times total). expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: sharedControl, count: 2}); // Replace formA with a new instance. This will trigger destroy operation for the // `formControlName` directive that is bound to the `control` FormControl instance. const newFormA = new FormGroup({login: new FormControl('new-a')}); fixture.componentInstance.formA = newFormA; fixture.detectChanges(); validatorSpy.calls.reset(); asyncValidatorSpy.calls.reset(); // Update control with a new value. sharedControl.setValue('d'); fixture.detectChanges(); // We should still see an update to the second <input>. expect(fixture.nativeElement.querySelector('#login').value).toBe('d'); expectValidatorsToBeCalled(validatorSpy, asyncValidatorSpy, {ctx: sharedControl, count: 1}); }); it('should clean up callbacks when FormControlDirective is destroyed (simple)', () => { // Scenario: // --------- // [formControl] *ngIf const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); @Component({ selector: 'app', template: ` <input *ngIf="visible" type="text" [formControl]="control" cva-a validators-a> `, standalone: false, }) class App { visible = true; control = control; } const fixture = initCleanupTest(App); resetSpies(control); // Case 1: update control value and verify all spies were called. control.setValue('Initial value'); fixture.detectChanges(); verifySpies(control, { ownValidators: control, viewValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); // Case 2: hide form control and verify no directive-related callbacks // (validators, value accessors) were invoked. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(control); control.setValue('Updated Value'); // Expectation: // - FormControlDirective was destroyed and connection to default value accessor and view // validators should also be destroyed. verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated Value', }); // Case 3: make the form control visible again and verify all callbacks are correctly // attached. fixture.componentInstance.visible = true; fixture.detectChanges(); // Reset all spies again, prepare for next check. resetSpies(control); control.setValue('Updated Value (v2)'); verifySpies(control, { viewValidators: control, ownValidators: control, valueAccessor: 'Updated Value (v2)', valueChanges: 'Updated Value (v2)', }); }); it('should clean up when FormControlDirective is destroyed (multiple instances)', () => { // Scenario: // --------- // [formControl] *ngIf // [formControl] const control = new FormControl(); addOwnValidatorsAndAttachSpies(control, { viewValidators: [ViewValidatorA, AsyncViewValidatorA], valueAccessor: ValueAccessorA, }); @Component({ selector: 'app', template: ` <input type="text" [formControl]="control" cva-a validators-a *ngIf="visible"> <input type="text" [formControl]="control" cva-b> `, standalone: false, }) class App { visible = true; control = control; } const fixture = initCleanupTest(App); // Value accessor for the second <input> without *ngIf. const valueAccessorBSpy = spyOn(ValueAccessorB.prototype, 'writeValue'); // Reset all spies. valueAccessorBSpy.calls.reset(); resetSpies(control); // Case 1: update control value and verify all spies were called. control.setValue('Initial value'); fixture.detectChanges(); expect(valueAccessorBSpy).toHaveBeenCalledWith('Initial value'); verifySpies(control, { ownValidators: control, viewValidators: control, valueAccessor: 'Initial value', valueChanges: 'Initial value', }); // Case 2: hide form control and verify no directive-related callbacks // (validators, value accessors) were invoked. fixture.componentInstance.visible = false; fixture.detectChanges(); // Reset all spies again, prepare for next check. valueAccessorBSpy.calls.reset(); resetSpies(control); control.setValue('Updated Value'); // Expectation: // - FormControlDirective was destroyed and connection to a value accessor and view // validators should also be destroyed. // - Since there is a second instance of the FormControlDirective directive present in the // template, we expect to see calls to value accessor B (since it's applied to // that directive instance) and validators applied on a control instance itself (not a // part of a view setup). expect(valueAccessorBSpy).toHaveBeenCalledWith('Updated Value'); verifySpies(control, { viewValidators: SHOULD_NOT_BE_CALLED, ownValidators: control, valueAccessor: SHOULD_NOT_BE_CALLED, valueChanges: 'Updated Value', }); });