id
stringlengths
6
6
text
stringlengths
20
17.2k
title
stringclasses
1 value
004691
# Deploy multiple locales If `myapp` is the directory that contains the distributable files of your project, you typically make different versions available for different locales in locale directories. For example, your French version is located in the `myapp/fr` directory and the Spanish version is located in the `myapp/es` directory. The HTML `base` tag with the `href` attribute specifies the base URI, or URL, for relative links. If you set the `"localize"` option in [`angular.json`][GuideWorkspaceConfig] workspace build configuration file to `true` or to an array of locale IDs, the CLI adjusts the base `href` for each version of the application. To adjust the base `href` for each version of the application, the CLI adds the locale to the configured `"baseHref"`. Specify the `"baseHref"` for each locale in your [`angular.json`][GuideWorkspaceConfig] workspace build configuration file. The following example displays `"baseHref"` set to an empty string. <docs-code header="angular.json" path="adev/src/content/examples/i18n/angular.json" visibleRegion="i18n-baseHref"/> Also, to declare the base `href` at compile time, use the CLI `--baseHref` option with [`ng build`][CliBuild]. ## Configure a server Typical deployment of multiple languages serve each language from a different subdirectory. Users are redirected to the preferred language defined in the browser using the `Accept-Language` HTTP header. If the user has not defined a preferred language, or if the preferred language is not available, then the server falls back to the default language. To change the language, change your current location to another subdirectory. The change of subdirectory often occurs using a menu implemented in the application. HELPFUL: For more information on how to deploy apps to a remote server, see [Deployment][GuideDeployment]. ### Nginx example The following example displays an Nginx configuration. <docs-code path="adev/src/content/examples/i18n/doc-files/nginx.conf" language="nginx"/> ### Apache example The following example displays an Apache configuration. <docs-code path="adev/src/content/examples/i18n/doc-files/apache2.conf" language="apache"/> [CliBuild]: cli/build "ng build | CLI | Angular" [GuideDeployment]: tools/cli/deployment "Deployment | Angular" [GuideWorkspaceConfig]: reference/configs/workspace-config "Angular workspace configuration | Angular"
004693
# Merge translations into the application To merge the completed translations into your project, complete the following actions 1. Use the [Angular CLI][CliMain] to build a copy of the distributable files of your project 1. Use the `"localize"` option to replace all of the i18n messages with the valid translations and build a localized variant application. A variant application is a complete a copy of the distributable files of your application translated for a single locale. After you merge the translations, serve each distributable copy of the application using server-side language detection or different subdirectories. HELPFUL: For more information about how to serve each distributable copy of the application, see [deploying multiple locales](guide/i18n/deploy). For a compile-time translation of the application, the build process uses ahead-of-time (AOT) compilation to produce a small, fast, ready-to-run application. HELPFUL: For a detailed explanation of the build process, see [Building and serving Angular apps][GuideBuild]. The build process works for translation files in the `.xlf` format or in another format that Angular understands, such as `.xtb`. For more information about translation file formats used by Angular, see [Change the source language file format][GuideI18nCommonTranslationFilesChangeTheSourceLanguageFileFormat] To build a separate distributable copy of the application for each locale, [define the locales in the build configuration][GuideI18nCommonMergeDefineLocalesInTheBuildConfiguration] in the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file of your project. This method shortens the build process by removing the requirement to perform a full application build for each locale. To [generate application variants for each locale][GuideI18nCommonMergeGenerateApplicationVariantsForEachLocale], use the `"localize"` option in the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file. Also, to [build from the command line][GuideI18nCommonMergeBuildFromTheCommandLine], use the [`build`][CliBuild] [Angular CLI][CliMain] command with the `--localize` option. HELPFUL: Optionally, [apply specific build options for just one locale][GuideI18nCommonMergeApplySpecificBuildOptionsForJustOneLocale] for a custom locale configuration. ## Define locales in the build configuration Use the `i18n` project option in the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file of your project to define locales for a project. The following sub-options identify the source language and tell the compiler where to find supported translations for the project. | Suboption | Details | |:--- |:--- | | `sourceLocale` | The locale you use within the application source code \(`en-US` by default\) | | `locales` | A map of locale identifiers to translation files | ### `angular.json` for `en-US` and `fr` example For example, the following excerpt of an [`angular.json`][GuideWorkspaceConfig] workspace build configuration file sets the source locale to `en-US` and provides the path to the French \(`fr`\) locale translation file. <docs-code header="angular.json" path="adev/src/content/examples/i18n/angular.json" visibleRegion="locale-config"/> ## Generate application variants for each locale To use your locale definition in the build configuration, use the `"localize"` option in the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file to tell the CLI which locales to generate for the build configuration. * Set `"localize"` to `true` for all the locales previously defined in the build configuration. * Set `"localize"` to an array of a subset of the previously defined locale identifiers to build only those locale versions. * Set `"localize"` to `false` to disable localization and not generate any locale-specific versions. HELPFUL: Ahead-of-time (AOT) compilation is required to localize component templates. If you changed this setting, set `"aot"` to `true` in order to use AOT. HELPFUL: Due to the deployment complexities of i18n and the need to minimize rebuild time, the development server only supports localizing a single locale at a time. If you set the `"localize"` option to `true`, define more than one locale, and use `ng serve`; then an error occurs. If you want to develop against a specific locale, set the `"localize"` option to a specific locale. For example, for French \(`fr`\), specify `"localize": ["fr"]`. The CLI loads and registers the locale data, places each generated version in a locale-specific directory to keep it separate from other locale versions, and puts the directories within the configured `outputPath` for the project. For each application variant the `lang` attribute of the `html` element is set to the locale. The CLI also adjusts the HTML base HREF for each version of the application by adding the locale to the configured `baseHref`. Set the `"localize"` property as a shared configuration to effectively inherit for all the configurations. Also, set the property to override other configurations. ### `angular.json` include all locales from build example The following example displays the `"localize"` option set to `true` in the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file, so that all locales defined in the build configuration are built. <docs-code header="angular.json" path="adev/src/content/examples/i18n/angular.json" visibleRegion="build-localize-true"/> ## Build from the command line Also, use the `--localize` option with the [`ng build`][CliBuild] command and your existing `production` configuration. The CLI builds all locales defined in the build configuration. If you set the locales in build configuration, it is similar to when you set the `"localize"` option to `true`. HELPFUL: For more information about how to set the locales, see [Generate application variants for each locale][GuideI18nCommonMergeGenerateApplicationVariantsForEachLocale]. <docs-code path="adev/src/content/examples/i18n/doc-files/commands.sh" visibleRegion="build-localize"/> ## Apply specific build options for just one locale To apply specific build options to only one locale, specify a single locale to create a custom locale-specific configuration. IMPORTANT: Use the [Angular CLI][CliMain] development server \(`ng serve`\) with only a single locale. ### build for French example The following example displays a custom locale-specific configuration using a single locale. <docs-code header="angular.json" path="adev/src/content/examples/i18n/angular.json" visibleRegion="build-single-locale"/> Pass this configuration to the `ng serve` or `ng build` commands. The following code example displays how to serve the French language file. <docs-code path="adev/src/content/examples/i18n/doc-files/commands.sh" visibleRegion="serve-french"/> For production builds, use configuration composition to run both configurations. <docs-code path="adev/src/content/examples/i18n/doc-files/commands.sh" visibleRegion="build-production-french"/> <docs-code header="angular.json" path="adev/src/content/examples/i18n/angular.json" visibleRegion="build-production-french" /> ## Report missing translations When a translation is missing, the build succeeds but generates a warning such as `Missing translation for message "{translation_text}"`. To configure the level of warning that is generated by the Angular compiler, specify one of the following levels. | Warning level | Details | Output | |:--- |:--- |:--- | | `error` | Throw an error and the build fails | n/a | | `ignore` | Do nothing | n/a | | `warning` | Displays the default warning in the console or shell | `Missing translation for message "{translation_text}"` | Specify the warning level in the `options` section for the `build` target of your [`angular.json`][GuideWorkspaceConfig] workspace build configuration file. ### `angular.json` `error` warning example The following example displays how to set the warning level to `error`. <docs-code header="angular.json" path="adev/src/content/examples/i18n/angular.json" visibleRegion="missing-translation-error" /> HELPFUL: When you compile your Angular project into an Angular application, the instances of the `i18n` attribute are replaced with instances of the [`$localize`][ApiLocalizeInitLocalize] tagged message string. This means that your Angular application is translated after compilation. This also means that you can create localized versions of your Angular application without re-compiling your entire Angular project for each locale. When you translate your Angular application, the *translation transformation* replaces and reorders the parts \(static strings and expressions\) of the template literal string with strings from a collection of translations. For more information, see [`$localize`][ApiLocalizeInitLocalize]. TLDR: Compile once, then translate for each locale.
004697
# Introduction to Angular animations Animation provides the illusion of motion: HTML elements change styling over time. Well-designed animations can make your application more fun and straightforward to use, but they aren't just cosmetic. Animations can improve your application and user experience in a number of ways: * Without animations, web page transitions can seem abrupt and jarring * Motion greatly enhances the user experience, so animations give users a chance to detect the application's response to their actions * Good animations intuitively call the user's attention to where it is needed Typically, animations involve multiple style *transformations* over time. An HTML element can move, change color, grow or shrink, fade, or slide off the page. These changes can occur simultaneously or sequentially. You can control the timing of each transformation. Angular's animation system is built on CSS functionality, which means you can animate any property that the browser considers animatable. This includes positions, sizes, transforms, colors, borders, and more. The W3C maintains a list of animatable properties on its [CSS Transitions](https://www.w3.org/TR/css-transitions-1) page. ## About this guide This guide covers the basic Angular animation features to get you started on adding Angular animations to your project. ## Getting started The main Angular modules for animations are `@angular/animations` and `@angular/platform-browser`. To get started with adding Angular animations to your project, import the animation-specific modules along with standard Angular functionality. <docs-workflow> <docs-step title="Enabling the animations module"> Import `provideAnimationsAsync` from `@angular/platform-browser/animations/async` and add it to the providers list in the `bootstrapApplication` function call. <docs-code header="Enabling Animations" language="ts" linenums> bootstrapApplication(AppComponent, { providers: [ provideAnimationsAsync(), ] }); </docs-code> <docs-callout important title="If you need immediate animations in your application"> If you need to have an animation happen immediately when your application is loaded, you will want to switch to the eagerly loaded animations module. Import `provideAnimations` from `@angular/platform-browser/animations` instead, and use `provideAnimations` **in place of** `provideAnimationsAsync` in the `bootstrapApplication` function call. </docs-callout> For `NgModule` based applications import `BrowserAnimationsModule`, which introduces the animation capabilities into your Angular root application module. <docs-code header="src/app/app.module.ts" path="adev/src/content/examples/animations/src/app/app.module.1.ts"/> </docs-step> <docs-step title="Importing animation functions into component files"> If you plan to use specific animation functions in component files, import those functions from `@angular/animations`. <docs-code header="src/app/app.component.ts" path="adev/src/content/examples/animations/src/app/app.component.ts" visibleRegion="imports"/> See all [available animation functions](guide/animations#animations-api-summary) at the end of this guide. </docs-step> <docs-step title="Adding the animation metadata property"> In the component file, add a metadata property called `animations:` within the `@Component()` decorator. You put the trigger that defines an animation within the `animations` metadata property. <docs-code header="src/app/app.component.ts" path="adev/src/content/examples/animations/src/app/app.component.ts" visibleRegion="decorator"/> </docs-step> </docs-workflow>
004699
efining animations and attaching them to the HTML template Animations are defined in the metadata of the component that controls the HTML element to be animated. Put the code that defines your animations under the `animations:` property within the `@Component()` decorator. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="component"/> When you've defined an animation trigger for a component, attach it to an element in that component's template by wrapping the trigger name in brackets and preceding it with an `@` symbol. Then, you can bind the trigger to a template expression using standard Angular property binding syntax as shown below, where `triggerName` is the name of the trigger, and `expression` evaluates to a defined animation state. <docs-code language="typescript"> <div [@triggerName]="expression">…</div>; </docs-code> The animation is executed or triggered when the expression value changes to a new state. The following code snippet binds the trigger to the value of the `isOpen` property. <docs-code header="src/app/open-close.component.html" path="adev/src/content/examples/animations/src/app/open-close.component.1.html" visibleRegion="trigger"/> In this example, when the `isOpen` expression evaluates to a defined state of `open` or `closed`, it notifies the trigger `openClose` of a state change. Then it's up to the `openClose` code to handle the state change and kick off a state change animation. For elements entering or leaving a page \(inserted or removed from the DOM\), you can make the animations conditional. For example, use `*ngIf` with the animation trigger in the HTML template. HELPFUL: In the component file, set the trigger that defines the animations as the value of the `animations:` property in the `@Component()` decorator. In the HTML template file, use the trigger name to attach the defined animations to the HTML element to be animated. ### Code review Here are the code files discussed in the transition example. <docs-code-multifile> <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="component"/> <docs-code header="src/app/open-close.component.html" path="adev/src/content/examples/animations/src/app/open-close.component.1.html" visibleRegion="trigger"/> <docs-code header="src/app/open-close.component.css" path="adev/src/content/examples/animations/src/app/open-close.component.css"/> </docs-code-multifile> ### Summary You learned to add animation to a transition between two states, using `style()` and [`state()`](api/animations/state) along with `animate()` for the timing. Learn about more advanced features in Angular animations under the Animation section, beginning with advanced techniques in [transition and triggers](guide/animations/transition-and-triggers). ## Animations API summary The functional API provided by the `@angular/animations` module provides a domain-specific language \(DSL\) for creating and controlling animations in Angular applications. See the [API reference](api#animations) for a complete listing and syntax details of the core functions and related data structures. | Function name | What it does | |:--- |:--- | | `trigger()` | Kicks off the animation and serves as a container for all other animation function calls. HTML template binds to `triggerName`. Use the first argument to declare a unique trigger name. Uses array syntax. | | `style()` | Defines one or more CSS styles to use in animations. Controls the visual appearance of HTML elements during animations. Uses object syntax. | | [`state()`](api/animations/state) | Creates a named set of CSS styles that should be applied on successful transition to a given state. The state can then be referenced by name within other animation functions. | | `animate()` | Specifies the timing information for a transition. Optional values for `delay` and `easing`. Can contain `style()` calls within. | | `transition()` | Defines the animation sequence between two named states. Uses array syntax. | | `keyframes()` | Allows a sequential change between styles within a specified time interval. Use within `animate()`. Can include multiple `style()` calls within each `keyframe()`. Uses array syntax. | | [`group()`](api/animations/group) | Specifies a group of animation steps \(*inner animations*\) to be run in parallel. Animation continues only after all inner animation steps have completed. Used within `sequence()` or `transition()`. | | `query()` | Finds one or more inner HTML elements within the current element. | | `sequence()` | Specifies a list of animation steps that are run sequentially, one by one. | | `stagger()` | Staggers the starting time for animations for multiple elements. | | `animation()` | Produces a reusable animation that can be invoked from elsewhere. Used together with `useAnimation()`. | | `useAnimation()` | Activates a reusable animation. Used with `animation()`. | | `animateChild()` | Allows animations on child components to be run within the same timeframe as the parent. | </table> ## More on Angular animations HELPFUL: Check out this [presentation](https://www.youtube.com/watch?v=rnTK9meY5us), shown at the AngularConnect conference in November 2017, and the accompanying [source code](https://github.com/matsko/animationsftw.in). You might also be interested in the following: <docs-pill-row> <docs-pill href="guide/animations/transition-and-triggers" title="Transition and triggers"/> <docs-pill href="guide/animations/complex-sequences" title="Complex animation sequences"/> <docs-pill href="guide/animations/reusable-animations" title="Reusable animations"/> <docs-pill href="guide/animations/route-animations" title="Route transition animations"/> </docs-pill-row>
004711
# Communicating with the Service Worker Enabling service worker support does more than just register the service worker; it also provides services you can use to interact with the service worker and control the caching of your application. ## `SwUpdate` service The `SwUpdate` service gives you access to events that indicate when the service worker discovers and installs an available update for your application. The `SwUpdate` service supports three separate operations: * Receiving notifications when an updated version is *detected* on the server, *installed and ready* to be used locally or when an *installation fails*. * Asking the service worker to check the server for new updates. * Asking the service worker to activate the latest version of the application for the current tab. ### Version updates The `versionUpdates` is an `Observable` property of `SwUpdate` and emits four event types: | Event types | Details | |:--- |:--- | | `VersionDetectedEvent` | Emitted when the service worker has detected a new version of the app on the server and is about to start downloading it. | | `NoNewVersionDetectedEvent` | Emitted when the service worker has checked the version of the app on the server and did not find a new version. | | `VersionReadyEvent` | Emitted when a new version of the app is available to be activated by clients. It may be used to notify the user of an available update or prompt them to refresh the page. | | `VersionInstallationFailedEvent` | Emitted when the installation of a new version failed. It may be used for logging/monitoring purposes. | <docs-code header="log-update.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/log-update.service.ts" visibleRegion="sw-update"/> ### Checking for updates It's possible to ask the service worker to check if any updates have been deployed to the server. The service worker checks for updates during initialization and on each navigation request —that is, when the user navigates from a different address to your application. However, you might choose to manually check for updates if you have a site that changes frequently or want updates to happen on a schedule. Do this with the `checkForUpdate()` method: <docs-code header="check-for-update.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/check-for-update.service.ts"/> This method returns a `Promise<boolean>` which indicates if an update is available for activation. The check might fail, which will cause a rejection of the `Promise`. <docs-callout important title="Stabilization and service worker registration"> In order to avoid negatively affecting the initial rendering of the page, by default the Angular service worker service waits for up to 30 seconds for the application to stabilize before registering the ServiceWorker script. Constantly polling for updates, for example, with [setInterval()](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) or RxJS' [interval()](https://rxjs.dev/api/index/function/interval), prevents the application from stabilizing and the ServiceWorker script is not registered with the browser until the 30 seconds upper limit is reached. This is true for any kind of polling done by your application. Check the [isStable](api/core/ApplicationRef#isStable) documentation for more information. Avoid that delay by waiting for the application to stabilize first, before starting to poll for updates, as shown in the preceding example. Alternatively, you might want to define a different [registration strategy](api/service-worker/SwRegistrationOptions#registrationStrategy) for the ServiceWorker. </docs-callout> ### Updating to the latest version You can update an existing tab to the latest version by reloading the page as soon as a new version is ready. To avoid disrupting the user's progress, it is generally a good idea to prompt the user and let them confirm that it is OK to reload the page and update to the latest version: <docs-code header="prompt-update.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/prompt-update.service.ts" visibleRegion="sw-version-ready"/> <docs-callout important title="Safety of updating without reloading"> Calling `activateUpdate()` updates a tab to the latest version without reloading the page, but this could break the application. Updating without reloading can create a version mismatch between the application shell and other page resources, such as lazy-loaded chunks, whose filenames may change between versions. You should only use `activateUpdate()`, if you are certain it is safe for your specific use case. </docs-callout> ### Handling an unrecoverable state In some cases, the version of the application used by the service worker to serve a client might be in a broken state that cannot be recovered from without a full page reload. For example, imagine the following scenario: 1. A user opens the application for the first time and the service worker caches the latest version of the application. Assume the application's cached assets include `index.html`, `main.<main-hash-1>.js` and `lazy-chunk.<lazy-hash-1>.js`. 1. The user closes the application and does not open it for a while. 1. After some time, a new version of the application is deployed to the server. This newer version includes the files `index.html`, `main.<main-hash-2>.js` and `lazy-chunk.<lazy-hash-2>.js`. IMPORTANT: The hashes are different now, because the content of the files changed. The old version is no longer available on the server. 1. In the meantime, the user's browser decides to evict `lazy-chunk.<lazy-hash-1>.js` from its cache. Browsers might decide to evict specific (or all) resources from a cache in order to reclaim disk space. 1. The user opens the application again. The service worker serves the latest version known to it at this point, namely the old version (`index.html` and `main.<main-hash-1>.js`). 1. At some later point, the application requests the lazy bundle, `lazy-chunk.<lazy-hash-1>.js`. 1. The service worker is unable to find the asset in the cache (remember that the browser evicted it). Nor is it able to retrieve it from the server (because the server now only has `lazy-chunk.<lazy-hash-2>.js` from the newer version). In the preceding scenario, the service worker is not able to serve an asset that would normally be cached. That particular application version is broken and there is no way to fix the state of the client without reloading the page. In such cases, the service worker notifies the client by sending an `UnrecoverableStateEvent` event. Subscribe to `SwUpdate#unrecoverable` to be notified and handle these errors. <docs-code header="handle-unrecoverable-state.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/handle-unrecoverable-state.service.ts" visibleRegion="sw-unrecoverable-state"/> ## More on Angular service workers You might also be interested in the following: <docs-pill-row> <docs-pill href="ecosystem/service-workers/push-notifications" title="Push notifications"/> <docs-pill href="ecosystem/service-workers/devops" title="Service Worker devops"/> </docs-pill-row>
004727
# Creating libraries This page provides a conceptual overview of how to create and publish new libraries to extend Angular functionality. If you find that you need to solve the same problem in more than one application \(or want to share your solution with other developers\), you have a candidate for a library. A simple example might be a button that sends users to your company website, that would be included in all applications that your company builds. ## Getting started Use the Angular CLI to generate a new library skeleton in a new workspace with the following commands. <docs-code language="shell"> ng new my-workspace --no-create-application cd my-workspace ng generate library my-lib </docs-code> <docs-callout title="Naming your library"> You should be very careful when choosing the name of your library if you want to publish it later in a public package registry such as npm. See [Publishing your library](tools/libraries/creating-libraries#publishing-your-library). Avoid using a name that is prefixed with `ng-`, such as `ng-library`. The `ng-` prefix is a reserved keyword used from the Angular framework and its libraries. The `ngx-` prefix is preferred as a convention used to denote that the library is suitable for use with Angular. It is also an excellent indication to consumers of the registry to differentiate between libraries of different JavaScript frameworks. </docs-callout> The `ng generate` command creates the `projects/my-lib` folder in your workspace, which contains a component and a service inside an NgModule. HELPFUL: For more details on how a library project is structured, refer to the [Library project files](reference/configs/file-structure#library-project-files) section of the [Project File Structure guide](reference/configs/file-structure). Use the monorepo model to use the same workspace for multiple projects. See [Setting up for a multi-project workspace](reference/configs/file-structure#multiple-projects). When you generate a new library, the workspace configuration file, `angular.json`, is updated with a project of type `library`. <docs-code language="json"> "projects": { … "my-lib": { "root": "projects/my-lib", "sourceRoot": "projects/my-lib/src", "projectType": "library", "prefix": "lib", "architect": { "build": { "builder": "@angular-devkit/build-angular:ng-packagr", … </docs-code> Build, test, and lint the project with CLI commands: <docs-code language="shell"> ng build my-lib --configuration development ng test my-lib ng lint my-lib </docs-code> Notice that the configured builder for the project is different from the default builder for application projects. This builder, among other things, ensures that the library is always built with the [AOT compiler](tools/cli/aot-compiler). To make library code reusable you must define a public API for it. This "user layer" defines what is available to consumers of your library. A user of your library should be able to access public functionality \(such as NgModules, service providers and general utility functions\) through a single import path. The public API for your library is maintained in the `public-api.ts` file in your library folder. Anything exported from this file is made public when your library is imported into an application. Use an NgModule to expose services and components. Your library should supply documentation \(typically a README file\) for installation and maintenance. ## Refactoring parts of an application into a library To make your solution reusable, you need to adjust it so that it does not depend on application-specific code. Here are some things to consider in migrating application functionality to a library. * Declarations such as components and pipes should be designed as stateless, meaning they don't rely on or alter external variables. If you do rely on state, you need to evaluate every case and decide whether it is application state or state that the library would manage. * Any observables that the components subscribe to internally should be cleaned up and disposed of during the lifecycle of those components * Components should expose their interactions through inputs for providing context, and outputs for communicating events to other components * Check all internal dependencies. * For custom classes or interfaces used in components or service, check whether they depend on additional classes or interfaces that also need to be migrated * Similarly, if your library code depends on a service, that service needs to be migrated * If your library code or its templates depend on other libraries \(such as Angular Material, for instance\), you must configure your library with those dependencies * Consider how you provide services to client applications. * Services should declare their own providers, rather than declaring providers in the NgModule or a component. Declaring a provider makes that service *tree-shakable*. This practice lets the compiler leave the service out of the bundle if it never gets injected into the application that imports the library. For more about this, see [Tree-shakable providers](guide/di/lightweight-injection-tokens). * If you register global service providers or share providers across multiple NgModules, use the [`forRoot()` and `forChild()` design patterns](guide/ngmodules/singleton-services) provided by the [RouterModule](api/router/RouterModule) * If your library provides optional services that might not be used by all client applications, support proper tree-shaking for that case by using the [lightweight token design pattern](guide/di/lightweight-injection-tokens) ## Integrating with the CLI using code-generation schematics A library typically includes *reusable code* that defines components, services, and other Angular artifacts \(pipes, directives\) that you import into a project. A library is packaged into an npm package for publishing and sharing. This package can also include schematics that provide instructions for generating or transforming code directly in your project, in the same way that the CLI creates a generic new component with `ng generate component`. A schematic that is packaged with a library can, for example, provide the Angular CLI with the information it needs to generate a component that configures and uses a particular feature, or set of features, defined in that library. One example of this is [Angular Material's navigation schematic](https://material.angular.io/guide/schematics#navigation-schematic) which configures the CDK's [BreakpointObserver](https://material.angular.io/cdk/layout/overview#breakpointobserver) and uses it with Material's [MatSideNav](https://material.angular.io/components/sidenav/overview) and [MatToolbar](https://material.angular.io/components/toolbar/overview) components. Create and include the following kinds of schematics: * Include an installation schematic so that `ng add` can add your library to a project * Include generation schematics in your library so that `ng generate` can scaffold your defined artifacts \(components, services, tests\) in a project * Include an update schematic so that `ng update` can update your library's dependencies and provide migrations for breaking changes in new releases What you include in your library depends on your task. For example, you could define a schematic to create a dropdown that is pre-populated with canned data to show how to add it to an application. If you want a dropdown that would contain different passed-in values each time, your library could define a schematic to create it with a given configuration. Developers could then use `ng generate` to configure an instance for their own application. Suppose you want to read a configuration file and then generate a form based on that configuration. If that form needs additional customization by the developer who is using your library, it might work best as a schematic. However, if the form will always be the same and not need much customization by developers, then you could create a dynamic component that takes the configuration and generates the form. In general, the more complex the customization, the more useful the schematic approach. For more information, see [Schematics Overview](tools/cli/schematics) and [Schematics for Libraries](tools/cli/schematics-for-libraries). ## Publishing your library Use the Angular CLI and the npm package manager to build and publish your library as an npm package. Angular CLI uses a tool called [ng-packagr](https://github.com/ng-packagr/ng-packagr/blob/master/README.md) to create packages from your compiled code that can be published to npm. See [Building libraries with Ivy](tools/libraries/creating-libraries#publishing-libraries) for information on the distribution formats supported by `ng-packagr` and guidance on how to choose the right format for your library. You should always build libraries for distribution using the `production` configuration. This ensures that generated output uses the appropriate optimizations and the correct package format for npm. <docs-code language="shell"> ng build my-lib cd dist/my-lib npm publish </docs-code> ## M
004728
anaging assets in a library In your Angular library, the distributable can include additional assets like theming files, Sass mixins, or documentation \(like a changelog\). For more information [copy assets into your library as part of the build](https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md) and [embed assets in component styles](https://github.com/ng-packagr/ng-packagr/blob/master/docs/embed-assets-css.md). IMPORTANT: When including additional assets like Sass mixins or pre-compiled CSS. You need to add these manually to the conditional ["exports"](tools/libraries/angular-package-format#quotexportsquot) in the `package.json` of the primary entrypoint. `ng-packagr` will merge handwritten `"exports"` with the auto-generated ones, allowing for library authors to configure additional export subpaths, or custom conditions. <docs-code language="json"> "exports": { ".": { "sass": "./_index.scss", }, "./theming": { "sass": "./_theming.scss" }, "./prebuilt-themes/indigo-pink.css": { "style": "./prebuilt-themes/indigo-pink.css" } } </docs-code> The above is an extract from the [@angular/material](https://unpkg.com/browse/@angular/material/package.json) distributable. ## Peer dependencies Angular libraries should list any `@angular/*` dependencies the library depends on as peer dependencies. This ensures that when modules ask for Angular, they all get the exact same module. If a library lists `@angular/core` in `dependencies` instead of `peerDependencies`, it might get a different Angular module instead, which would cause your application to break. ## Using your own library in applications You don't have to publish your library to the npm package manager to use it in the same workspace, but you do have to build it first. To use your own library in an application: * Build the library. You cannot use a library before it is built. <docs-code language="shell"> ng build my-lib </docs-code> * In your applications, import from the library by name: <docs-code language="typescript"> import { myExport } from 'my-lib'; </docs-code> ### Building and rebuilding your library The build step is important if you haven't published your library as an npm package and then installed the package back into your application from npm. For instance, if you clone your git repository and run `npm install`, your editor shows the `my-lib` imports as missing if you haven't yet built your library. HELPFUL: When you import something from a library in an Angular application, Angular looks for a mapping between the library name and a location on disk. When you install a library package, the mapping is in the `node_modules` folder. When you build your own library, it has to find the mapping in your `tsconfig` paths. Generating a library with the Angular CLI automatically adds its path to the `tsconfig` file. The Angular CLI uses the `tsconfig` paths to tell the build system where to find the library. For more information, see [Path mapping overview](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping). If you find that changes to your library are not reflected in your application, your application is probably using an old build of the library. You can rebuild your library whenever you make changes to it, but this extra step takes time. *Incremental builds* functionality improves the library-development experience. Every time a file is changed a partial build is performed that emits the amended files. Incremental builds can be run as a background process in your development environment. To take advantage of this feature add the `--watch` flag to the build command: <docs-code language="shell"> ng build my-lib --watch </docs-code> IMPORTANT: The CLI `build` command uses a different builder and invokes a different build tool for libraries than it does for applications. * The build system for applications, `@angular-devkit/build-angular`, is based on `webpack`, and is included in all new Angular CLI projects * The build system for libraries is based on `ng-packagr`. It is only added to your dependencies when you add a library using `ng generate library my-lib`. The two build systems support different things, and even where they support the same things, they do those things differently. This means that the TypeScript source can result in different JavaScript code in a built library than it would in a built application. For this reason, an application that depends on a library should only use TypeScript path mappings that point to the *built library*. TypeScript path mappings should *not* point to the library source `.ts` files. ## Publishing libraries There are two distribution formats to use when publishing a library: | Distribution formats | Details | |:--- |:--- | | Partial-Ivy \(recommended\) | Contains portable code that can be consumed by Ivy applications built with any version of Angular from v12 onwards. | | Full-Ivy | Contains private Angular Ivy instructions, which are not guaranteed to work across different versions of Angular. This format requires that the library and application are built with the *exact* same version of Angular. This format is useful for environments where all library and application code is built directly from source. | For publishing to npm use the partial-Ivy format as it is stable between patch versions of Angular. Avoid compiling libraries with full-Ivy code if you are publishing to npm because the generated Ivy instructions are not part of Angular's public API, and so might change between patch versions. ## Ensuring library version compatibility The Angular version used to build an application should always be the same or greater than the Angular versions used to build any of its dependent libraries. For example, if you had a library using Angular version 13, the application that depends on that library should use Angular version 13 or later. Angular does not support using an earlier version for the application. If you intend to publish your library to npm, compile with partial-Ivy code by setting `"compilationMode": "partial"` in `tsconfig.prod.json`. This partial format is stable between different versions of Angular, so is safe to publish to npm. Code with this format is processed during the application build using the same version of the Angular compiler, ensuring that the application and all of its libraries use a single version of Angular. Avoid compiling libraries with full-Ivy code if you are publishing to npm because the generated Ivy instructions are not part of Angular's public API, and so might change between patch versions. If you've never published a package in npm before, you must create a user account. Read more in [Publishing npm Packages](https://docs.npmjs.com/getting-started/publishing-npm-packages). ## Consuming partial-Ivy code outside the Angular CLI An application installs many Angular libraries from npm into its `node_modules` directory. However, the code in these libraries cannot be bundled directly along with the built application as it is not fully compiled. To finish compilation, use the Angular linker. For applications that don't use the Angular CLI, the linker is available as a [Babel](https://babeljs.io) plugin. The plugin is to be imported from `@angular/compiler-cli/linker/babel`. The Angular linker Babel plugin supports build caching, meaning that libraries only need to be processed by the linker a single time, regardless of other npm operations. Example of integrating the plugin into a custom [Webpack](https://webpack.js.org) build by registering the linker as a [Babel](https://babeljs.io) plugin using [babel-loader](https://webpack.js.org/loaders/babel-loader/#options). <docs-code header="webpack.config.mjs" path="adev/src/content/examples/angular-linker-plugin/webpack.config.mjs" visibleRegion="webpack-config"/> HELPFUL: The Angular CLI integrates the linker plugin automatically, so if consumers of your library are using the CLI, they can install Ivy-native libraries from npm without any additional configuration.
004731
# Configuring application environments You can define different named build configurations for your project, such as `development` and `staging`, with different defaults. Each named configuration can have defaults for any of the options that apply to the various builder targets, such as `build`, `serve`, and `test`. The [Angular CLI](tools/cli) `build`, `serve`, and `test` commands can then replace files with appropriate versions for your intended target environment. ## Angular CLI configurations Angular CLI builders support a `configurations` object, which allows overwriting specific options for a builder based on the configuration provided on the command line. <docs-code language="json"> { "projects": { "my-app": { "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { // By default, disable source map generation. "sourceMap": false }, "configurations": { // For the `debug` configuration, enable source maps. "debug": { "sourceMap": true } } }, … } } } } </docs-code> You can choose which configuration to use with the `--configuration` option. <docs-code language="shell"> ng build --configuration debug </docs-code> Configurations can be applied to any Angular CLI builder. Multiple configurations can be specified with a comma separator. The configurations are applied in order, with conflicting options using the value from the last configuration. <docs-code language="shell"> ng build --configuration debug,production,customer-facing </docs-code> ## Configure environment-specific defaults `@angular-devkit/build-angular:browser` supports file replacements, an option for substituting source files before executing a build. Using this in combination with `--configuration` provides a mechanism for configuring environment-specific data in your application. Start by [generating environments](cli/generate/environments) to create the `src/environments/` directory and configure the project to use file replacements. <docs-code language="shell"> ng generate environments </docs-code> The project's `src/environments/` directory contains the base configuration file, `environment.ts`, which provides the default configuration for production. You can override default values for additional environments, such as `development` and `staging`, in target-specific configuration files. For example: <docs-code language="text"> my-app/src/environments ├── environment.development.ts ├── environment.staging.ts └── environment.ts </docs-code> The base file `environment.ts`, contains the default environment settings. For example: <docs-code language="typescript"> export const environment = { production: true }; </docs-code> The `build` command uses this as the build target when no environment is specified. You can add further variables, either as additional properties on the environment object, or as separate objects. For example, the following adds a default for a variable to the default environment: <docs-code language="typescript"> export const environment = { production: true, apiUrl: 'http://my-prod-url' }; </docs-code> You can add target-specific configuration files, such as `environment.development.ts`. The following content sets default values for the development build target: <docs-code language="typescript"> export const environment = { production: false, apiUrl: 'http://my-dev-url' }; </docs-code> ## Using environment-specific variables in your app To use the environment configurations you have defined, your components must import the original environments file: <docs-code language="typescript"> import { environment } from './environments/environment'; </docs-code> This ensures that the build and serve commands can find the configurations for specific build targets. The following code in the component file (`app.component.ts`) uses an environment variable defined in the configuration files. <docs-code language="typescript"> import { environment } from './../environments/environment'; // Fetches from `http://my-prod-url` in production, `http://my-dev-url` in development. fetch(environment.apiUrl); </docs-code> The main CLI configuration file, `angular.json`, contains a `fileReplacements` section in the configuration for each build target, which lets you replace any file in the TypeScript program with a target-specific version of that file. This is useful for including target-specific code or variables in a build that targets a specific environment, such as production or staging. By default no files are replaced, however `ng generate environments` sets up this configuration automatically. You can change or add file replacements for specific build targets by editing the `angular.json` configuration directly. <docs-code language="json"> "configurations": { "development": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.development.ts" } ], … </docs-code> This means that when you build your development configuration with `ng build --configuration development`, the `src/environments/environment.ts` file is replaced with the target-specific version of the file, `src/environments/environment.development.ts`. To add a staging environment, create a copy of `src/environments/environment.ts` called `src/environments/environment.staging.ts`, then add a `staging` configuration to `angular.json`: <docs-code language="json"> "configurations": { "development": { … }, "production": { … }, "staging": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.staging.ts" } ] } } </docs-code> You can add more configuration options to this target environment as well. Any option that your build supports can be overridden in a build target configuration. To build using the staging configuration, run the following command: <docs-code language="shell"> ng build --configuration staging </docs-code> By default, the `build` target includes `production` and `development` configurations and `ng serve` uses the development build of the application. You can also configure `ng serve` to use the targeted build configuration if you set the `buildTarget` option: <docs-code language="json"> "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { … }, "configurations": { "development": { // Use the `development` configuration of the `build` target. "buildTarget": "my-app:build:development" }, "production": { // Use the `production` configuration of the `build` target. "buildTarget": "my-app:build:production" } }, "defaultConfiguration": "development" }, </docs-code> The `defaultConfiguration` option specifies which configuration is used by default. When `defaultConfiguration` is not set, `options` are used directly without modification.
004732
# The Angular CLI The Angular CLI is a command-line interface tool which allows you to scaffold, develop, test, deploy, and maintain Angular applications directly from a command shell. Angular CLI is published on npm as the `@angular/cli` package and includes a binary named `ng`. Commands invoking `ng` are using the Angular CLI. <docs-callout title="Try Angular without local setup"> If you are new to Angular, you might want to start with [Try it now!](tutorials/learn-angular), which introduces the essentials of Angular in the context of a ready-made basic online store app for you to examine and modify. This standalone tutorial takes advantage of the interactive [StackBlitz](https://stackblitz.com) environment for online development. You don't need to set up your local environment until you're ready. </docs-callout> <docs-card-container> <docs-card title="Getting Started" link="Get Started" href="tools/cli/setup-local"> Install Angular CLI to create and build your first app. </docs-card> <docs-card title="Command Reference" link="Learn More" href="cli"> Discover CLI commands to make you more productive with Angular. </docs-card> <docs-card title="Schematics" link="Learn More" href="tools/cli/schematics"> Create and run schematics to generate and modify source files in your application automatically. </docs-card> <docs-card title="Builders" link="Learn More" href="tools/cli/cli-builder"> Create and run builders to perform complex transformations from your source code to generated build outputs. </docs-card> </docs-card-container> ## CLI command-language syntax Angular CLI roughly follows Unix/POSIX conventions for option syntax. ### Boolean options Boolean options have two forms: `--this-option` sets the flag to `true`, `--no-this-option` sets it to `false`. You can also use `--this-option=false` or `--this-option=true`. If neither option is supplied, the flag remains in its default state, as listed in the reference documentation. ### Array options Array options can be provided in two forms: `--option value1 value2` or `--option value1 --option value2`. ### Key/value options Some options like `--define` expect an array of `key=value` pairs as their values. Just like array options, key/value options can be provided in two forms: `--define 'KEY_1="value1"' KEY_2=true` or `--define 'KEY_1="value1"' --define KEY_2=true`. ### Relative paths Options that specify files can be given as absolute paths, or as paths relative to the current working directory, which is generally either the workspace or project root.
004735
## Define a generation rule You now have the framework in place for creating the code that actually modifies the user's application to set it up for the service defined in your library. The Angular workspace where the user installed your library contains multiple projects \(applications and libraries\). The user can specify the project on the command line, or let it default. In either case, your code needs to identify the specific project to which this schematic is being applied, so that you can retrieve information from the project configuration. Do this using the `Tree` object that is passed in to the factory function. The `Tree` methods give you access to the complete file tree in your workspace, letting you read and write files during the execution of the schematic. ### Get the project configuration 1. To determine the destination project, use the `workspaces.readWorkspace` method to read the contents of the workspace configuration file, `angular.json`. To use `workspaces.readWorkspace` you need to create a `workspaces.WorkspaceHost` from the `Tree`. Add the following code to your factory function. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Schema Import)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="workspace"/> Be sure to check that the context exists and throw the appropriate error. 1. Now that you have the project name, use it to retrieve the project-specific configuration information. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Project)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="project-info"/> The `workspace.projects` object contains all the project-specific configuration information. 1. The `options.path` determines where the schematic template files are moved to once the schematic is applied. The `path` option in the schematic's schema is substituted by default with the current working directory. If the `path` is not defined, use the `sourceRoot` from the project configuration along with the `projectType`. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Project Info)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="path"/> ### Define the rule A `Rule` can use external template files, transform them, and return another `Rule` object with the transformed template. Use the templating to generate any custom files required for your schematic. 1. Add the following code to your factory function. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Template transform)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="template"/> | Methods | Details | |:--- |:--- | | `apply()` | Applies multiple rules to a source and returns the transformed source. It takes 2 arguments, a source and an array of rules. | | `url()` | Reads source files from your filesystem, relative to the schematic. | | `applyTemplates()` | Receives an argument of methods and properties you want make available to the schematic template and the schematic filenames. It returns a `Rule`. This is where you define the `classify()` and `dasherize()` methods, and the `name` property. | | `classify()` | Takes a value and returns the value in title case. For example, if the provided name is `my service`, it is returned as `MyService`. | | `dasherize()` | Takes a value and returns the value in dashed and lowercase. For example, if the provided name is MyService, it is returned as `my-service`. | | `move()` | Moves the provided source files to their destination when the schematic is applied. | 1. Finally, the rule factory must return a rule. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Chain Rule)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="chain"/> The `chain()` method lets you combine multiple rules into a single rule, so that you can perform multiple operations in a single schematic. Here you are only merging the template rules with any code executed by the schematic. See a complete example of the following schematic rule function. <docs-code header="projects/my-lib/schematics/my-service/index.ts" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts"/> For more information about rules and utility methods, see [Provided Rules](https://github.com/angular/angular-cli/tree/main/packages/angular_devkit/schematics#provided-rules). ## Running your library schematic After you build your library and schematics, you can install the schematics collection to run against your project. The following steps show you how to generate a service using the schematic you created earlier. ### Build your library and schematics From the root of your workspace, run the `ng build` command for your library. <docs-code language="shell"> ng build my-lib </docs-code> Then, you change into your library directory to build the schematic <docs-code language="shell"> cd projects/my-lib npm run build </docs-code> ### Link the library Your library and schematics are packaged and placed in the `dist/my-lib` folder at the root of your workspace. For running the schematic, you need to link the library into your `node_modules` folder. From the root of your workspace, run the `npm link` command with the path to your distributable library. <docs-code language="shell"> npm link dist/my-lib </docs-code> ### Run the schematic Now that your library is installed, run the schematic using the `ng generate` command. <docs-code language="shell"> ng generate my-lib:my-service --name my-data </docs-code> In the console, you see that the schematic was run and the `my-data.service.ts` file was created in your application folder. <docs-code language="shell" hideCopy> CREATE src/app/my-data.service.ts (208 bytes) </docs-code>
004737
# Generating code using schematics A schematic is a template-based code generator that supports complex logic. It is a set of instructions for transforming a software project by generating or modifying code. Schematics are packaged into collections and installed with npm. The schematic collection can be a powerful tool for creating, modifying, and maintaining any software project, but is particularly useful for customizing Angular projects to suit the particular needs of your own organization. You might use schematics, for example, to generate commonly-used UI patterns or specific components, using predefined templates or layouts. Use schematics to enforce architectural rules and conventions, making your projects consistent and interoperative. ## Schematics for the Angular CLI Schematics are part of the Angular ecosystem. The Angular CLI uses schematics to apply transforms to a web-app project. You can modify these schematics, and define new ones to do things like update your code to fix breaking changes in a dependency, for example, or to add a new configuration option or framework to an existing project. Schematics that are included in the `@schematics/angular` collection are run by default by the commands `ng generate` and `ng add`. The package contains named schematics that configure the options that are available to the CLI for `ng generate` sub-commands, such as `ng generate component` and `ng generate service`. The sub-commands for `ng generate` are shorthand for the corresponding schematic. To specify and generate a particular schematic, or a collection of schematics, using the long form: <docs-code language="shell"> ng generate my-schematic-collection:my-schematic-name </docs-code> or <docs-code language="shell"> ng generate my-schematic-name --collection collection-name </docs-code> ### Configuring CLI schematics A JSON schema associated with a schematic tells the Angular CLI what options are available to commands and sub-commands, and determines the defaults. These defaults can be overridden by providing a different value for an option on the command line. See [Workspace Configuration](reference/configs/workspace-config) for information about how to change the generation option defaults for your workspace. The JSON schemas for the default schematics used by the CLI to generate projects and parts of projects are collected in the package [`@schematics/angular`](https://github.com/angular/angular-cli/tree/main/packages/schematics/angular). The schema describes the options available to the CLI for each of the `ng generate` sub-commands, as shown in the `--help` output. ## Developing schematics for libraries As a library developer, you can create your own collections of custom schematics to integrate your library with the Angular CLI. * An *add schematic* lets developers install your library in an Angular workspace using `ng add` * *Generation schematics* can tell the `ng generate` sub-commands how to modify projects, add configurations and scripts, and scaffold artifacts that are defined in your library * An *update schematic* can tell the `ng update` command how to update your library's dependencies and adjust for breaking changes when you release a new version For more details of what these look like and how to create them, see: <docs-pill-row> <docs-pill href="tools/cli/schematics-authoring" title="Authoring Schematics"/> <docs-pill href="tools/cli/schematics-for-libraries" title="Schematics for Libraries"/> </docs-pill-row> ### Add schematics An *add schematic* is typically supplied with a library, so that the library can be added to an existing project with `ng add`. The `add` command uses your package manager to download new dependencies, and invokes an installation script that is implemented as a schematic. For example, the [`@angular/material`](https://material.angular.io/guide/schematics) schematic tells the `add` command to install and set up Angular Material and theming, and register new starter components that can be created with `ng generate`. Look at this one as an example and model for your own add schematic. Partner and third party libraries also support the Angular CLI with add schematics. For example, `@ng-bootstrap/schematics` adds [ng-bootstrap](https://ng-bootstrap.github.io) to an app, and `@clr/angular` installs and sets up [Clarity from VMWare](https://clarity.design/documentation/get-started). An *add schematic* can also update a project with configuration changes, add additional dependencies \(such as polyfills\), or scaffold package-specific initialization code. For example, the `@angular/pwa` schematic turns your application into a PWA by adding an application manifest and service worker. ### Generation schematics Generation schematics are instructions for the `ng generate` command. The documented sub-commands use the default Angular generation schematics, but you can specify a different schematic \(in place of a sub-command\) to generate an artifact defined in your library. Angular Material, for example, supplies generation schematics for the UI components that it defines. The following command uses one of these schematics to render an Angular Material `<mat-table>` that is pre-configured with a datasource for sorting and pagination. <docs-code language="shell"> ng generate @angular/material:table <component-name> </docs-code> ### Update schematics The `ng update` command can be used to update your workspace's library dependencies. If you supply no options or use the help option, the command examines your workspace and suggests libraries to update. <docs-code language="shell"> ng update We analyzed your package.json, there are some packages to update: Name Version Command to update &hyphen;------------------------------------------------------------------------------- @angular/cdk 7.2.2 -> 7.3.1 ng update @angular/cdk @angular/cli 7.2.3 -> 7.3.0 ng update @angular/cli @angular/core 7.2.2 -> 7.2.3 ng update @angular/core @angular/material 7.2.2 -> 7.3.1 ng update @angular/material rxjs 6.3.3 -> 6.4.0 ng update rxjs There might be additional packages that are outdated. Run "ng update --all" to try to update all at the same time. </docs-code> If you pass the command a set of libraries to update \(or the `--all` flag\), it updates those libraries, their peer dependencies, and the peer dependencies that depend on them. HELPFUL: If there are inconsistencies \(for example, if peer dependencies cannot be matched by a simple [semver](https://semver.io) range\), the command generates an error and does not change anything in the workspace. We recommend that you do not force an update of all dependencies by default. Try updating specific dependencies first. For more about how the `ng update` command works, see [Update Command](https://github.com/angular/angular-cli/blob/main/docs/specifications/update.md). If you create a new version of your library that introduces potential breaking changes, you can provide an *update schematic* to enable the `ng update` command to automatically resolve any such changes in the project being updated. For example, suppose you want to update the Angular Material library. <docs-code language="shell"> ng update @angular/material </docs-code> This command updates both `@angular/material` and its dependency `@angular/cdk` in your workspace's `package.json`. If either package contains an update schematic that covers migration from the existing version to a new version, the command runs that schematic on your workspace.
004740
## Inputs and type-checking The template type checker checks whether a binding expression's type is compatible with that of the corresponding directive input. As an example, consider the following component: <docs-code language="typescript"> export interface User { name: string; } @Component({ selector: 'user-detail', template: '{{ user.name }}', }) export class UserDetailComponent { @Input() user: User; } </docs-code> The `AppComponent` template uses this component as follows: <docs-code language="typescript"> @Component({ selector: 'app-root', template: '<user-detail [user]="selectedUser"></user-detail>', }) export class AppComponent { selectedUser: User | null = null; } </docs-code> Here, during type checking of the template for `AppComponent`, the `[user]="selectedUser"` binding corresponds with the `UserDetailComponent.user` input. Therefore, Angular assigns the `selectedUser` property to `UserDetailComponent.user`, which would result in an error if their types were incompatible. TypeScript checks the assignment according to its type system, obeying flags such as `strictNullChecks` as they are configured in the application. Avoid run-time type errors by providing more specific in-template type requirements to the template type checker. Make the input type requirements for your own directives as specific as possible by providing template-guard functions in the directive definition. See [Improving template type checking for custom directives](guide/directives/structural-directives#directive-type-checks) in this guide. ### Strict null checks When you enable `strictTemplates` and the TypeScript flag `strictNullChecks`, typecheck errors might occur for certain situations that might not easily be avoided. For example: * A nullable value that is bound to a directive from a library which did not have `strictNullChecks` enabled. For a library compiled without `strictNullChecks`, its declaration files will not indicate whether a field can be `null` or not. For situations where the library handles `null` correctly, this is problematic, as the compiler will check a nullable value against the declaration files which omit the `null` type. As such, the compiler produces a type-check error because it adheres to `strictNullChecks`. * Using the `async` pipe with an Observable which you know will emit synchronously. The `async` pipe currently assumes that the Observable it subscribes to can be asynchronous, which means that it's possible that there is no value available yet. In that case, it still has to return something —which is `null`. In other words, the return type of the `async` pipe includes `null`, which might result in errors in situations where the Observable is known to emit a non-nullable value synchronously. There are two potential workarounds to the preceding issues: * In the template, include the non-null assertion operator `!` at the end of a nullable expression, such as <docs-code hideCopy language="html"> <user-detail [user]="user!"></user-detail> </docs-code> In this example, the compiler disregards type incompatibilities in nullability, just as in TypeScript code. In the case of the `async` pipe, notice that the expression needs to be wrapped in parentheses, as in <docs-code hideCopy language="html"> <user-detail [user]="(user$ | async)!"></user-detail> </docs-code> * Disable strict null checks in Angular templates completely. When `strictTemplates` is enabled, it is still possible to disable certain aspects of type checking. Setting the option `strictNullInputTypes` to `false` disables strict null checks within Angular templates. This flag applies for all components that are part of the application. ### Advice for library authors As a library author, you can take several measures to provide an optimal experience for your users. First, enabling `strictNullChecks` and including `null` in an input's type, as appropriate, communicates to your consumers whether they can provide a nullable value or not. Additionally, it is possible to provide type hints that are specific to the template type checker. See [Improving template type checking for custom directives](guide/directives/structural-directives#directive-type-checks), and [Input setter coercion](#input-setter-coercion). ## Input setter coercion Occasionally it is desirable for the `@Input()` of a directive or component to alter the value bound to it, typically using a getter/setter pair for the input. As an example, consider this custom button component: Consider the following directive: <docs-code language="typescript"> @Component({ selector: 'submit-button', template: ` <div class="wrapper"> <button [disabled]="disabled">Submit</button> </div> `, }) class SubmitButton { private _disabled: boolean; @Input() get disabled(): boolean { return this._disabled; } set disabled(value: boolean) { this._disabled = value; } } </docs-code> Here, the `disabled` input of the component is being passed on to the `<button>` in the template. All of this works as expected, as long as a `boolean` value is bound to the input. But, suppose a consumer uses this input in the template as an attribute: <docs-code language="html"> <submit-button disabled></submit-button> </docs-code> This has the same effect as the binding: <docs-code language="html"> <submit-button [disabled]="''"></submit-button> </docs-code> At runtime, the input will be set to the empty string, which is not a `boolean` value. Angular component libraries that deal with this problem often "coerce" the value into the right type in the setter: <docs-code language="typescript"> set disabled(value: boolean) { this._disabled = (value === '') || value; } </docs-code> It would be ideal to change the type of `value` here, from `boolean` to `boolean|''`, to match the set of values which are actually accepted by the setter. TypeScript prior to version 4.3 requires that both the getter and setter have the same type, so if the getter should return a `boolean` then the setter is stuck with the narrower type. If the consumer has Angular's strictest type checking for templates enabled, this creates a problem: the empty string \(`''`\) is not actually assignable to the `disabled` field, which creates a type error when the attribute form is used. As a workaround for this problem, Angular supports checking a wider, more permissive type for `@Input()` than is declared for the input field itself. Enable this by adding a static property with the `ngAcceptInputType_` prefix to the component class: <docs-code language="typescript"> class SubmitButton { private _disabled: boolean; @Input() get disabled(): boolean { return this._disabled; } set disabled(value: boolean) { this._disabled = (value === '') || value; } static ngAcceptInputType_disabled: boolean|''; } </docs-code> Since TypeScript 4.3, the setter could have been declared to accept `boolean|''` as type, making the input setter coercion field obsolete. As such, input setters coercion fields have been deprecated. This field does not need to have a value. Its existence communicates to the Angular type checker that the `disabled` input should be considered as accepting bindings that match the type `boolean|''`. The suffix should be the `@Input` *field* name. Care should be taken that if an `ngAcceptInputType_` override is present for a given input, then the setter should be able to handle any values of the overridden type. ## Disabling type checking using `$any()` Disable checking of a binding expression by surrounding the expression in a call to the `$any()` cast pseudo-function. The compiler treats it as a cast to the `any` type just like in TypeScript when a `<any>` or `as any` cast is used. In the following example, casting `person` to the `any` type suppresses the error `Property address does not exist`. <docs-code language="typescript"> @Component({ selector: 'my-component', template: '{{$any(person).address.street}}' }) class MyComponent { person?: Person; } </docs-code>
004745
# Deployment When you are ready to deploy your Angular application to a remote server, you have various options. ## Automatic deployment with the CLI The Angular CLI command `ng deploy` executes the `deploy` [CLI builder](tools/cli/cli-builder) associated with your project. A number of third-party builders implement deployment capabilities to different platforms. You can add any of them to your project with `ng add`. When you add a package with deployment capability, it will automatically update your workspace configuration (`angular.json` file) with a `deploy` section for the selected project. You can then use the `ng deploy` command to deploy that project. For example, the following command automatically deploys a project to [Firebase](https://firebase.google.com/). <docs-code language="shell"> ng add @angular/fire ng deploy </docs-code> The command is interactive. In this case, you must have or create a Firebase account and authenticate using it. The command prompts you to select a Firebase project for deployment before building your application and uploading the production assets to Firebase. The table below lists tools which implement deployment functionality to different platforms. The `deploy` command for each package may require different command line options. You can read more by following the links associated with the package names below: | Deployment to | Setup Command | |:--- |:--- | | [Firebase hosting](https://firebase.google.com/docs/hosting) | [`ng add @angular/fire`](https://npmjs.org/package/@angular/fire) | | [Vercel](https://vercel.com/solutions/angular) | [`vercel init angular`](https://github.com/vercel/vercel/tree/main/examples/angular) | | [Netlify](https://www.netlify.com) | [`ng add @netlify-builder/deploy`](https://npmjs.org/package/@netlify-builder/deploy) | | [GitHub pages](https://pages.github.com) | [`ng add angular-cli-ghpages`](https://npmjs.org/package/angular-cli-ghpages) | | [Amazon Cloud S3](https://aws.amazon.com/s3/?nc2=h_ql_prod_st_s3) | [`ng add @jefiozie/ngx-aws-deploy`](https://www.npmjs.com/package/@jefiozie/ngx-aws-deploy) | If you're deploying to a self-managed server or there's no builder for your favorite cloud platform, you can either [create a builder](tools/cli/cli-builder) that allows you to use the `ng deploy` command, or read through this guide to learn how to manually deploy your application. ## Manual deployment to a remote server To manually deploy your application, create a production build and copy the output directory to a web server or content delivery network (CDN). By default, `ng build` uses the `production` configuration. If you have customized your build configurations, you may want to confirm [production optimizations](tools/cli/deployment#production-optimizations) are being applied before deploying. `ng build` outputs the built artifacts to `dist/my-app/` by default, however this path can be configured with the `outputPath` option in the `@angular-devkit/build-angular:browser` builder. Copy this directory to the server and configure it to serve the directory. While this is a minimal deployment solution, there are a few requirements for the server to serve your Angular application correctly. ## Server configuration This section covers changes you may need to configure on the server to run your Angular application. ### Routed apps must fall back to `index.html` Client-side rendered Angular applications are perfect candidates for serving with a static HTML server because all the content is static and generated at build time. If the application uses the Angular router, you must configure the server to return the application's host page (`index.html`) when asked for a file that it does not have. A routed application should support "deep links". A *deep link* is a URL that specifies a path to a component inside the application. For example, `http://my-app.test/users/42` is a *deep link* to the user detail page that displays the user with `id` 42. There is no issue when the user initially loads the index page and then navigates to that URL from within a running client. The Angular router performs the navigation *client-side* and does not request a new HTML page. But clicking a deep link in an email, entering it in the browser address bar, or even refreshing the browser while already on the deep linked page will all be handled by the browser itself, *outside* the running application. The browser makes a direct request to the server for `/users/42`, bypassing Angular's router. A static server routinely returns `index.html` when it receives a request for `http://my-app.test/`. But most servers by default will reject `http://my-app.test/users/42` and returns a `404 - Not Found` error *unless* it is configured to return `index.html` instead. Configure the fallback route or 404 page to `index.html` for your server, so Angular is served for deep links and can display the correct route. Some servers call this fallback behavior "Single-Page Application" (SPA) mode. Once the browser loads the application, Angular router will read the URL to determine which page it is on and display `/users/42` correctly. For "real" 404 pages such as `http://my-app.test/does-not-exist`, the server does not require any additional configuration. [404 pages implemented in the Angular router](guide/routing/common-router-tasks#displaying-a-404-page) will be displayed correctly. ### Requesting data from a different server (CORS) Web developers may encounter a [*cross-origin resource sharing*](https://developer.mozilla.org/docs/Web/HTTP/CORS "Cross-origin resource sharing") error when making a network request to a server other than the application's own host server. Browsers forbid such requests unless the server explicitly permits them. There isn't anything Angular or the client application can do about these errors. The _server_ must be configured to accept the application's requests. Read about how to enable CORS for specific servers at [enable-cors.org](https://enable-cors.org/server.html "Enabling CORS server"). ## Production optimizations `ng build` uses the `production` configuration unless configured otherwise. This configuration enables the following build optimization features. | Features | Details | |:--- |:--- | | [Ahead-of-Time (AOT) Compilation](tools/cli/aot-compiler) | Pre-compiles Angular component templates. | | [Production mode](tools/cli/deployment#development-only-features) | Optimizes the application for the best runtime performance | | Bundling | Concatenates your many application and library files into a minimum number of deployed files. | | Minification | Removes excess whitespace, comments, and optional tokens. | | Mangling | Renames functions, classes, and variables to use shorter, arbitrary identifiers. | | Dead code elimination | Removes unreferenced modules and unused code. | See [`ng build`](cli/build) for more about CLI build options and their effects. ### Development-only features When you run an application locally using `ng serve`, Angular uses the development configuration at runtime which enables: * Extra safety checks such as [`expression-changed-after-checked`](errors/NG0100) detection. * More detailed error messages. * Additional debugging utilities such as the global `ng` variable with [debugging functions](api#core-global) and [Angular DevTools](tools/devtools) support. These features are helpful during development, but they require extra code in the app, which is undesirable in production. To ensure these features do not negatively impact bundle size for end users, Angular CLI removes development-only code from the bundle when building for production. Building your application with `ng build` by default uses the `production` configuration which removes these features from the output for optimal bundle size. ## `--deploy-url` `--deploy-url` is a command line option used to specify the base path for resolving relative URLs for assets such as images, scripts, and style sheets at *compile* time. <docs-code language="shell"> ng build --deploy-url /my/assets </docs-code> The effect and purpose of `--deploy-url` overlaps with [`<base href>`](guide/routing/common-router-tasks). Both can be used for initial scripts, stylesheets, lazy scripts, and css resources. Unlike `<base href>` which can be defined in a single place at runtime, the `--deploy-url` needs to be hard-coded into an application at build time. Prefer `<base href>` where possible.
004746
# Migrating to the new build system In v17 and higher, the new build system provides an improved way to build Angular applications. This new build system includes: - A modern output format using ESM, with dynamic import expressions to support lazy module loading. - Faster build-time performance for both initial builds and incremental rebuilds. - Newer JavaScript ecosystem tools such as [esbuild](https://esbuild.github.io/) and [Vite](https://vitejs.dev/). - Integrated SSR and prerendering capabilities. This new build system is stable and fully supported for use with Angular applications. You can migrate to the new build system with applications that use the `browser` builder. If using a custom builder, please refer to the documentation for that builder on possible migration options. IMPORTANT: The existing Webpack-based build system is still considered stable and fully supported. Applications can continue to use the `browser` builder and will not be automatically migrated when updating. ## For new applications New applications will use this new build system by default via the `application` builder. ## For existing applications Both automated and manual procedures are available dependening on the requirements of the project. Starting with v18, the update process will ask if you would like to migrate existing applications to use the new build system via the automated migration. HELPFUL: Remember to remove any CommonJS assumptions in the application server code if using SSR such as `require`, `__filename`, `__dirname`, or other constructs from the [CommonJS module scope](https://nodejs.org/api/modules.html#the-module-scope). All application code should be ESM compatible. This does not apply to third-party dependencies. ### Automated migration (Recommended) The automated migration will adjust both the application configuration within `angular.json` as well as code and stylesheets to remove previous Webpack-specific feature usage. While many changes can be automated and most applications will not require any further changes, each application is unique and there may be some manual changes required. After the migration, please attempt a build of the application as there could be new errors that will require adjustments within the code. The errors will attempt to provide solutions to the problem when possible and the later sections of this guide describe some of the more common situations that you may encounter. When updating to Angular v18 via `ng update`, you will be asked to execute the migration. This migration is entirely optional for v18 and can also be run manually at anytime after an update via the following command: <docs-code language="shell"> ng update @angular/cli --name use-application-builder </docs-code> The migration does the following: * Converts existing `browser` or `browser-esbuild` target to `application` * Removes any previous SSR builders (because `application` does that now). * Updates configuration accordingly. * Merges `tsconfig.server.json` with `tsconfig.app.json` and adds the TypeScript option `"esModuleInterop": true` to ensure `express` imports are [ESM compliant](#esm-default-imports-vs-namespace-imports). * Updates application server code to use new bootstrapping and output directory structure. * Removes any Webpack-specific builder stylesheet usage such as the tilde or caret in `@import`/`url()` and updates the configuration to provide equivalent behavior * Converts to use the new lower dependency `@angular/build` Node.js package if no other `@angular-devkit/build-angular` usage is found. ### Manual migration Additionally for existing projects, you can manually opt-in to use the new builder on a per-application basis with two different options. Both options are considered stable and fully supported by the Angular team. The choice of which option to use is a factor of how many changes you will need to make to migrate and what new features you would like to use in the project. - The `browser-esbuild` builder builds only the client-side bundle of an application designed to be compatible with the existing `browser` builder that provides the preexisting build system. It serves as a drop-in replacement for existing `browser` applications. - The `application` builder covers an entire application, such as the client-side bundle, as well as optionally building a server for server-side rendering and performing build-time prerendering of static pages. The `application` builder is generally preferred as it improves server-side rendered (SSR) builds, and makes it easier for client-side rendered projects to adopt SSR in the future. However it requires a little more migration effort, particularly for existing SSR applications if performed manually. If the `application` builder is difficult for your project to adopt, `browser-esbuild` can be an easier solution which gives most of the build performance benefits with fewer breaking changes. #### Manual migration to the compatibility builder A builder named `browser-esbuild` is available within the `@angular-devkit/build-angular` package that is present in an Angular CLI generated application. You can try out the new build system for applications that use the `browser` builder. If using a custom builder, please refer to the documentation for that builder on possible migration options. The compatibility option was implemented to minimize the amount of changes necessary to initially migrate your applications. This is provided via an alternate builder (`browser-esbuild`). You can update the `build` target for any application target to migrate to the new build system. The following is what you would typically find in `angular.json` for an application: <docs-code language="json"> ... "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", ... </docs-code> Changing the `builder` field is the only change you will need to make. <docs-code language="json"> ... "architect": { "build": { "builder": "@angular-devkit/build-angular:browser-esbuild", ... </docs-code> #### Manual migration to the new `application` builder A builder named `application` is also available within the `@angular-devkit/build-angular` package that is present in an Angular CLI generated application. This builder is the default for all new applications created via `ng new`. The following is what you would typically find in `angular.json` for an application: <docs-code language="json"> ... "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", ... </docs-code> Changing the `builder` field is the first change you will need to make. <docs-code language="json"> ... "architect": { "build": { "builder": "@angular-devkit/build-angular:application", ... </docs-code> Once the builder name has been changed, options within the `build` target will need to be updated. The following list discusses all the `browser` builder options that will need to be adjusted. - `main` should be renamed to `browser`. - `polyfills` should be an array, rather than a single file. - `buildOptimizer` should be removed, as this is covered by the `optimization` option. - `resourcesOutputPath` should be removed, this is now always `media`. - `vendorChunk` should be removed, as this was a performance optimization which is no longer needed. - `commonChunk` should be removed, as this was a performance optimization which is no longer needed. - `deployUrl` should be removed and is not supported. Prefer [`<base href>`](guide/routing/common-router-tasks) instead. See [deployment documentation](tools/cli/deployment#--deploy-url) for more information. - `ngswConfigPath` should be renamed to `serviceWorker`. If the application is not using SSR currently, this should be the final step to allow `ng build` to function. After executing `ng build` for the first time, there may be new warnings or errors based on behavioral differences or application usage of Webpack-specific features. Many of the warnings will provide suggestions on how to remedy that problem. If it appears that a warning is incorrect or the solution is not apparent, please open an issue on [GitHub](https://github.com/angular/angular-cli/issues). Also, the later sections of this guide provide additional information on several specific cases as well as current known issues. For applications new to SSR, the [Angular SSR Guide](guide/ssr) provides additional information regarding the setup process for adding SSR to an application. For applications that are already using SSR, additional adjustments will be needed to update the application server to support the new integrated SSR capabilities. The `application` builder now provides the integrated functionality for all of the following preexisting builders: - `app-shell` - `prerender` - `server` - `ssr-dev-server` The `ng update` process will automatically remove usages of the `@nguniversal` scope packages where some of these builders were previously located. The new `@angular/ssr` package will also be automatically added and used with configuration and code being adjusted during the update. The `@angular/ssr` package supports the `browser` builder as well as the `application` builder.
004747
## Executing a build Once you have updated the application configuration, builds can be performed using `ng build` as was previously done. Depending on the choice of builder migration, some of the command line options may be different. If the build command is contained in any `npm` or other scripts, ensure they are reviewed and updated. For applications that have migrated to the `application` builder and that use SSR and/or prererending, you also may be able to remove extra `ng run` commands from scripts now that `ng build` has integrated SSR support. <docs-code language="shell"> ng build </docs-code> ## Starting the development server The development server will automatically detect the new build system and use it to build the application. To start the development server no changes are necessary to the `dev-server` builder configuration or command line. <docs-code language="shell"> ng serve </docs-code> You can continue to use the [command line options](/cli/serve) you have used in the past with the development server. ## Hot module replacement JavaScript-based hot module replacement (HMR) is currently not supported. However, global stylesheet (`styles` build option) HMR is available and enabled by default. Angular focused HMR capabilities are currently planned and will be introduced in a future version. ## Unimplemented options and behavior Several build options are not yet implemented but will be added in the future as the build system moves towards a stable status. If your application uses these options, you can still try out the build system without removing them. Warnings will be issued for any unimplemented options but they will otherwise be ignored. However, if your application relies on any of these options to function, you may want to wait to try. - [WASM imports](https://github.com/angular/angular-cli/issues/25102) -- WASM can still be loaded manually via [standard web APIs](https://developer.mozilla.org/docs/WebAssembly/Loading_and_running). ## ESM default imports vs. namespace imports TypeScript by default allows default exports to be imported as namespace imports and then used in call expressions. This is unfortunately a divergence from the ECMAScript specification. The underlying bundler (`esbuild`) within the new build system expects ESM code that conforms to the specification. The build system will now generate a warning if your application uses an incorrect type of import of a package. However, to allow TypeScript to accept the correct usage, a TypeScript option must be enabled within the application's `tsconfig` file. When enabled, the [`esModuleInterop`](https://www.typescriptlang.org/tsconfig#esModuleInterop) option provides better alignment with the ECMAScript specification and is also recommended by the TypeScript team. Once enabled, you can update package imports where applicable to an ECMAScript conformant form. Using the [`moment`](https://npmjs.com/package/moment) package as an example, the following application code will cause runtime errors: ```ts import * as moment from 'moment'; console.log(moment().format()); ``` The build will generate a warning to notify you that there is a potential problem. The warning will be similar to: <docs-code language="text"> ▲ [WARNING] Calling "moment" will crash at run-time because it's an import namespace object, not a function [call-import-namespace] src/main.ts:2:12: 2 │ console.log(moment().format()); ╵ ~~~~~~ Consider changing "moment" to a default import instead: src/main.ts:1:7: 1 │ import * as moment from 'moment'; │ ~~~~~~~~~~~ ╵ moment </docs-code> However, you can avoid the runtime errors and the warning by enabling the `esModuleInterop` TypeScript option for the application and changing the import to the following: ```ts import moment from 'moment'; console.log(moment().format()); ``` ## Vite as a development server The usage of Vite in the Angular CLI is currently within a _development server capacity only_. Even without using the underlying Vite build system, Vite provides a full-featured development server with client side support that has been bundled into a low dependency npm package. This makes it an ideal candidate to provide comprehensive development server functionality. The current development server process uses the new build system to generate a development build of the application in memory and passes the results to Vite to serve the application. The usage of Vite, much like the Webpack-based development server, is encapsulated within the Angular CLI `dev-server` builder and currently cannot be directly configured. ## Known Issues There are currently several known issues that you may encounter when trying the new build system. This list will be updated to stay current. If any of these issues are currently blocking you from trying out the new build system, please check back in the future as it may have been solved. ### Type-checking of Web Worker code and processing of nested Web Workers Web Workers can be used within application code using the same syntax (`new Worker(new URL('<workerfile>', import.meta.url))`) that is supported with the `browser` builder. However, the code within the Worker will not currently be type-checked by the TypeScript compiler. TypeScript code is supported just not type-checked. Additionally, any nested workers will not be processed by the build system. A nested worker is a Worker instantiation within another Worker file. ### Order-dependent side-effectful imports in lazy modules Import statements that are dependent on a specific ordering and are also used in multiple lazy modules can cause top-level statements to be executed out of order. This is not common as it depends on the usage of side-effectful modules and does not apply to the `polyfills` option. This is caused by a [defect](https://github.com/evanw/esbuild/issues/399) in the underlying bundler but will be addressed in a future update. IMPORTANT: Avoiding the use of modules with non-local side effects (outside of polyfills) is recommended whenever possible regardless of the build system being used and avoids this particular issue. Modules with non-local side effects can have a negative effect on both application size and runtime performance as well. ## Bug reports Report issues and feature requests on [GitHub](https://github.com/angular/angular-cli/issues). Please provide a minimal reproduction where possible to aid the team in addressing issues.
004748
# Building Angular apps You can build your Angular CLI application or library with the `ng build` command. This will compile your TypeScript code to JavaScript, as well as optimize, bundle, and minify the output as appropriate. `ng build` only executes the builder for the `build` target in the default project as specified in `angular.json`. Angular CLI includes four builders typically used as `build` targets: | Builder | Purpose | | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `@angular-devkit/build-angular:browser` | Bundles a client-side application for use in a browser with [Webpack](https://webpack.js.org/). | | `@angular-devkit/build-angular:browser-esbuild` | Bundles a client-side application for use in a browser with [esbuild](https://esbuild.github.io/). See [`browser-esbuild` documentation](tools/cli/build-system-migration#manual-migration-to-the-compatibility-builder) for more information. | | `@angular-devkit/build-angular:application` | Builds an application with a client-side bundle, a Node server, and build-time prerendered routes with [esbuild](https://esbuild.github.io/). | | `@angular-devkit/build-angular:ng-packagr` | Builds an Angular library adhering to [Angular Package Format](tools/libraries/angular-package-format). | Applications generated by `ng new` use `@angular-devkit/build-angular:application` by default. Libraries generated by `ng generate library` use `@angular-devkit/build-angular:ng-packagr` by default. You can determine which builder is being used for a particular project by looking up the `build` target for that project. <docs-code language="json"> { "projects": { "my-app": { "architect": { // `ng build` invokes the Architect target named `build`. "build": { "builder": "@angular-devkit/build-angular:application", … }, "serve": { … } "test": { … } … } } } } </docs-code> This page discusses usage and options of `@angular-devkit/build-angular:application`. ## Output directory The result of this build process is output to a directory (`dist/${PROJECT_NAME}` by default). ## Configuring size budgets As applications grow in functionality, they also grow in size. The CLI lets you set size thresholds in your configuration to ensure that parts of your application stay within size boundaries that you define. Define your size boundaries in the CLI configuration file, `angular.json`, in a `budgets` section for each [configured environment](tools/cli/environments). <docs-code language="json"> { … "configurations": { "production": { … "budgets": [ { "type": "initial", "maximumWarning": "250kb", "maximumError": "500kb" }, ] } } } </docs-code> You can specify size budgets for the entire app, and for particular parts. Each budget entry configures a budget of a given type. Specify size values in the following formats: | Size value | Details | | :-------------- | :-------------------------------------------------------------------------- | | `123` or `123b` | Size in bytes. | | `123kb` | Size in kilobytes. | | `123mb` | Size in megabytes. | | `12%` | Percentage of size relative to baseline. \(Not valid for baseline values.\) | When you configure a budget, the builder warns or reports an error when a given part of the application reaches or exceeds a boundary size that you set. Each budget entry is a JSON object with the following properties: | Property | Value | | :------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | type | The type of budget. One of: <table> <thead> <tr> <th> Value </th> <th> Details </th> </tr> </thead> <tbody> <tr> <td> <code>bundle</code> </td> <td> The size of a specific bundle. </td> </tr> <tr> <td> <code>initial</code> </td> <td> The size of JavaScript needed for bootstrapping the application. Defaults to warning at 500kb and erroring at 1mb. </td> </tr> <tr> <td> <code>allScript</code> </td> <td> The size of all scripts. </td> </tr> <tr> <td> <code>all</code> </td> <td> The size of the entire application. </td> </tr> <tr> <td> <code>anyComponentStyle</code> </td> <td> This size of any one component stylesheet. Defaults to warning at 2kb and erroring at 4kb. </td> </tr> <tr> <td> <code>anyScript</code> </td> <td> The size of any one script. </td> </tr> <tr> <td> <code>any</code> </td> <td> The size of any file. </td> </tr> </tbody> </table> | | name | The name of the bundle (for `type=bundle`). | | baseline | The baseline size for comparison. | | maximumWarning | The maximum threshold for warning relative to the baseline. | | maximumError | The maximum threshold for error relative to the baseline. | | minimumWarning | The minimum threshold for warning relative to the baseline. | | minimumError | The minimum threshold for error relative to the baseline. | | warning | The threshold for warning relative to the baseline (min & max). | | error | The threshold for error relative to the baseline (min & max). | ## Configuring CommonJS dependencies Always prefer native [ECMAScript modules](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) (ESM) throughout your application and its dependencies. ESM is a fully specified web standard and JavaScript language feature with strong static analysis support. This makes bundle optimizations more powerful than other module formats. Angular CLI also supports importing [CommonJS](https://nodejs.org/api/modules.html) dependencies into your project and will bundle these dependencies automatically. However, CommonJS modules can prevent bundlers and minifiers from optimizing those modules effectively, which results in larger bundle sizes. For more information, see [How CommonJS is making your bundles larger](https://web.dev/commonjs-larger-bundles). Angular CLI outputs warnings if it detects that your browser application depends on CommonJS modules. When you encounter a CommonJS dependency, consider asking the maintainer to support ECMAScript modules, contributing that support yourself, or using an alternative dependency which meets your needs. If the best option is to use a CommonJS dependency, you can disable these warnings by adding the CommonJS module name to `allowedCommonJsDependencies` option in the `build` options located in `angular.json`. <docs-code language="json"> "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "allowedCommonJsDependencies": [ "lodash" ] … } … }, </docs-code> ## Configuring browser compatibility The Angular CLI uses [Browserslist](https://github.com/browserslist/browserslist) to ensure compatibility with different browser versions. Depending on supported browsers, Angular will automatically transform certain JavaScript and CSS features to ensure the built application does not use a feature which has not been implemented by a supported browser. However, the Angular CLI will not automatically add polyfills to supplement missing Web APIs. Use the `polyfills` option in `angular.json` to add polyfills. Internally, the Angular CLI uses the below default `browserslist` configuration which matches the [browsers that are supported](reference/versions#browser-support) by Angular. <docs-code language="text"> last 2 Chrome versions last 1 Firefox version last 2 Edge major versions last 2 Safari major versions last 2 iOS major versions last 2 Android major versions Firefox ESR </docs-code> To override the internal configuration, run [`ng generate config browserslist`](cli/generate/config), which generates a `.browserslistrc` configuration file in the project directory. See the [browserslist repository](https://github.com/browserslist/browserslist) for more examples of how to target specific browsers and versions. Avoid expanding this list to more browsers. Even if your application code more broadly compatible, Angular itself might not be. You should only ever _reduce_ the set of browsers or versions in this list. HELPFUL: Use [browsersl.ist](https://browsersl.ist) to display compatible browsers for a `browserslist` query.
004751
## Builder input You can invoke a builder indirectly through a CLI command such as `ng build`, or directly with the Angular CLI `ng run` command. In either case, you must provide required inputs, but can let other inputs default to values that are pre-configured for a specific *target*, specified by a [configuration](tools/cli/environments), or set on the command line. ### Input validation You define builder inputs in a JSON schema associated with that builder. Similar to schematics, the Architect tool collects the resolved input values into an `options` object, and validates their types against the schema before passing them to the builder function. For our example builder, `options` should be a `JsonObject` with two keys: a `source` and a `destination`, each of which are a string. You can provide the following schema for type validation of these values. <docs-code header="src/schema.json" language="json"> { "$schema": "http://json-schema.org/schema", "type": "object", "properties": { "source": { "type": "string" }, "destination": { "type": "string" } } } </docs-code> HELPFUL: This is a minimal example, but the use of a schema for validation can be very powerful. For more information, see the [JSON schemas website](http://json-schema.org). To link our builder implementation with its schema and name, you need to create a *builder definition* file, which you can point to in `package.json`. Create a file named `builders.json` that looks like this: <docs-code header="builders.json" language="json"> { "builders": { "copy": { "implementation": "./dist/my-builder.js", "schema": "./src/schema.json", "description": "Copies a file." } } } </docs-code> In the `package.json` file, add a `builders` key that tells the Architect tool where to find our builder definition file. <docs-code header="package.json" language="json"> { "name": "@example/copy-file", "version": "1.0.0", "description": "Builder for copying files", "builders": "builders.json", "dependencies": { "@angular-devkit/architect": "~0.1200.0", "@angular-devkit/core": "^12.0.0" } } </docs-code> The official name of our builder is now `@example/copy-file:copy`. The first part of this is the package name and the second part is the builder name as specified in the `builders.json` file. These values are accessed on `options.source` and `options.destination`. <docs-code header="src/my-builder.ts (report status)" path="adev/src/content/examples/cli-builder/src/my-builder.ts" visibleRegion="report-status"/> ### Target configuration A builder must have a defined target that associates it with a specific input configuration and project. Targets are defined in the `angular.json` [CLI configuration file](reference/configs/workspace-config). A target specifies the builder to use, its default options configuration, and named alternative configurations. Architect in the Angular CLI uses the target definition to resolve input options for a given run. The `angular.json` file has a section for each project, and the "architect" section of each project configures targets for builders used by CLI commands such as 'build', 'test', and 'serve'. By default, for example, the `ng build` command runs the builder `@angular-devkit/build-angular:browser` to perform the build task, and passes in default option values as specified for the `build` target in `angular.json`. <docs-code header="angular.json" language="json"> … "myApp": { … "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/myApp", "index": "src/index.html", … }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", … } } }, … } } … </docs-code> The command passes the builder the set of default options specified in the "options" section. If you pass the `--configuration=production` flag, it uses the override values specified in the `production` configuration. Specify further option overrides individually on the command line. #### Target strings The generic `ng run` CLI command takes as its first argument a target string of the following form. <docs-code language="shell"> project:target[:configuration] </docs-code> | | Details | |:--- |:--- | | project | The name of the Angular CLI project that the target is associated with. | | target | A named builder configuration from the `architect` section of the `angular.json` file. | | configuration | (optional) The name of a specific configuration override for the given target, as defined in the `angular.json` file. | If your builder calls another builder, it might need to read a passed target string. Parse this string into an object by using the `targetFromTargetString()` utility function from `@angular-devkit/architect`. ## Schedule
004752
and run Architect runs builders asynchronously. To invoke a builder, you schedule a task to be run when all configuration resolution is complete. The builder function is not executed until the scheduler returns a `BuilderRun` control object. The CLI typically schedules tasks by calling the `context.scheduleTarget()` function, and then resolves input options using the target definition in the `angular.json` file. Architect resolves input options for a given target by taking the default options object, then overwriting values from the configuration, then further overwriting values from the overrides object passed to `context.scheduleTarget()`. For the Angular CLI, the overrides object is built from command line arguments. Architect validates the resulting options values against the schema of the builder. If inputs are valid, Architect creates the context and executes the builder. For more information see [Workspace Configuration](reference/configs/workspace-config). HELPFUL: You can also invoke a builder directly from another builder or test by calling `context.scheduleBuilder()`. You pass an `options` object directly to the method, and those option values are validated against the schema of the builder without further adjustment. Only the `context.scheduleTarget()` method resolves the configuration and overrides through the `angular.json` file. ### Default architect configuration Let's create a simple `angular.json` file that puts target configurations into context. You can publish the builder to npm (see [Publishing your Library](tools/libraries/creating-libraries#publishing-your-library)), and install it using the following command: <docs-code language="shell"> npm install @example/copy-file </docs-code> If you create a new project with `ng new builder-test`, the generated `angular.json` file looks something like this, with only default builder configurations. <docs-code header="angular.json" language="json"> { "projects": { "builder-test": { "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { // more options... "outputPath": "dist/builder-test", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "src/tsconfig.app.json" }, "configurations": { "production": { // more options... "optimization": true, "aot": true, "buildOptimizer": true } } } } } } } </docs-code> ### Adding a target Add a new target that will run our builder to copy a file. This target tells the builder to copy the `package.json` file. * We will add a new target section to the `architect` object for our project * The target named `copy-package` uses our builder, which you published to `@example/copy-file`. * The options object provides default values for the two inputs that you defined. * `source` - The existing file you are copying. * `destination` - The path you want to copy to. <docs-code header="angular.json" language="json"> { "projects": { "builder-test": { "architect": { "copy-package": { "builder": "@example/copy-file:copy", "options": { "source": "package.json", "destination": "package-copy.json" } }, // Existing targets... } } } } </docs-code> ### Running the builder To run our builder with the new target's default configuration, use the following CLI command. <docs-code language="shell"> ng run builder-test:copy-package </docs-code> This copies the `package.json` file to `package-copy.json`. Use command-line arguments to override the configured defaults. For example, to run with a different `destination` value, use the following CLI command. <docs-code language="shell"> ng run builder-test:copy-package --destination=package-other.json </docs-code> This copies the file to `package-other.json` instead of `package-copy.json`. Because you did not override the *source* option, it will still copy from the default `package.json` file. ## Testing a builder Use integration testing for your builder, so that you can use the Architect scheduler to create a context, as in this [example](https://github.com/mgechev/cli-builders-demo). In the builder source directory, create a new test file `my-builder.spec.ts`. The test creates new instances of `JsonSchemaRegistry` (for schema validation), `TestingArchitectHost` (an in-memory implementation of `ArchitectHost`), and `Architect`. Here's an example of a test that runs the copy file builder. The test uses the builder to copy the `package.json` file and validates that the copied file's contents are the same as the source. <docs-code header="src/my-builder.spec.ts" path="adev/src/content/examples/cli-builder/src/my-builder.spec.ts"/> HELPFUL: When running this test in your repo, you need the [`ts-node`](https://github.com/TypeStrong/ts-node) package. You can avoid this by renaming `my-builder.spec.ts` to `my-builder.spec.js`. ### Watch mode Most builders to run once and return. However, this behavior is not entirely compatible with a builder that watches for changes (like a devserver, for example). Architect can support watch mode, but there are some things to look out for. * To be used with watch mode, a builder handler function should return an `Observable`. Architect subscribes to the `Observable` until it completes and might reuse it if the builder is scheduled again with the same arguments. * The builder should always emit a `BuilderOutput` object after each execution. Once it's been executed, it can enter a watch mode, to be triggered by an external event. If an event triggers it to restart, the builder should execute the `context.reportRunning()` function to tell Architect that it is running again. This prevents Architect from stopping the builder if another run is scheduled. When your builder calls `BuilderRun.stop()` to exit watch mode, Architect unsubscribes from the builder's `Observable` and calls the builder's teardown logic to clean up. This behavior also allows for long-running builds to be stopped and cleaned up. In general, if your builder is watching an external event, you should separate your run into three phases. | Phases | Details | |:--- |:--- | | Running | The task being performed, such as invoking a compiler. This ends when the compiler finishes and your builder emits a `BuilderOutput` object. | | Watching | Between two runs, watch an external event stream. For example, watch the file system for any changes. This ends when the compiler restarts, and `context.reportRunning()` is called. | | Completion | Either the task is fully completed, such as a compiler which needs to run a number of times, or the builder run was stopped (using `BuilderRun.stop()`). Architect executes teardown logic and unsubscribes from your builder's `Observable`. | ## Summary The CLI Builder API provides a means of changing the behavior of the Angular CLI by using builders to execute custom logic. * Builders can be synchronous or asynchronous, execute once or watch for external events, and can schedule other builders or targets. * Builders have option defaults specified in the `angular.json` configuration file, which can be overwritten by an alternate configuration for the target, and further overwritten by command line flags * The Angular team recommends that you use integration tests to test Architect builders. Use unit tests to validate the logic that the builder executes. * If your builder returns an `Observable`, it should clean up the builder in the teardown logic of that `Observable`.
004764
<docs-decorative-header title="Rendering Dynamic Templates" imgSrc="adev/src/assets/images/templates.svg"> <!-- markdownlint-disable-line --> Use Angular's template syntax to create dynamic HTML. </docs-decorative-header> What you've learned so far enables you to break an application up into components of HTML, but this limits you to static templates (i.e., content that doesn't change). The next step is to learn how to make use of Angular's template syntax to create dynamic HTML. ## Rendering Dynamic Data When you need to display dynamic content in your template, Angular uses the double curly brace syntax in order to distinguish between static and dynamic content. Here is a simplified example from a `TodoListItem` component. ```angular-ts @Component({ selector: 'todo-list-item', template: ` <p>Title: {{ taskTitle }}</p> `, }) export class TodoListItem { taskTitle = 'Read cup of coffee'; } ``` When Angular renders the component you'll see the output: ```angular-html <p>Title: Read cup of coffee</p> ``` This syntax declares an **interpolation** between the dynamic data property inside of the HTML. As a result, whenever the data changes, Angular will automatically update the DOM reflecting the new value of the property. ## Dynamic Properties When you need to dynamically set the value of standard DOM properties on an HTML element, the property is wrapped in square brackets to inform Angular that the declared value should be interpreted as a JavaScript-like statement ([with some Angular enhancements](guide/templates/binding#render-dynamic-text-with-text-interpolation)) instead of a plain string. For example, a common example of dynamically updating properties in your HTML is determining whether the form submit button should be disabled based on whether the form is valid or not. Wrap the desired property in square brackets to tell Angular that the assigned value is dynamic (i.e., not a static string). ```angular-ts @Component({ selector: 'sign-up-form', template: ` <button type="submit" [disabled]="formIsInvalid">Submit</button> `, }) export class SignUpForm { formIsInvalid = true; } ``` In this example, because `formIsInvalid` is true, the rendered HTML would be: ```angular-html <button type="submit" disabled>Submit</button> ``` ## Dynamic Attributes In the event you want to dynamically bind custom HTML attributes (e.g., `aria-`, `data-`, etc.), you might be inclined to wrap the custom attributes with the same square brackets. ```angular-ts @Component({ standalone: true, template: ` <button [data-test-id]="testId">Primary CTA</button> `, }) export class AppBanner { testId = 'main-cta'; } ``` Unfortunately, this will not work because custom HTML attributes are not standard DOM properties. In order for this to work as intended, we need to prepend the custom HTML attribute with the `attr.` prefix. ```angular-ts @Component({ standalone: true, template: ` <button [attr.data-test-id]="testId">Primary CTA</button> `, }) export class AppBanner { testId = 'main-cta'; } ``` ## Next Step Now that you have dynamic data and templates in the application, it's time to learn how to enhance templates by conditionally hiding or showing certain elements, looping over elements, and more. <docs-pill-row> <docs-pill title="Conditionals and Loops" href="essentials/conditionals-and-loops" /> </docs-pill-row>
004765
<docs-decorative-header title="Conditionals and Loops" imgSrc="adev/src/assets/images/directives.svg"> <!-- markdownlint-disable-line --> Conditionally show and/or repeat content based on dynamic data. </docs-decorative-header> One of the advantages of using a framework like Angular is that it provides built-in solutions for common problems that developers encounter. Examples of this include: displaying content based on a certain condition, rendering a list of items based on application data, etc. To solve this problem, Angular uses built-in control flow blocks, which tell the framework when and how your templates should be rendered. ## Conditional rendering One of the most common scenarios that developers encounter is the desire to show or hide content in templates based on a condition. A common example of this is whether or not to display certain controls on the screen based on the user's permission level. ### `@if` block Similar to JavaScript's `if` statement, Angular uses `@if` control flow blocks to conditionally hide and show part of a template and its contents. ```angular-ts // user-controls.component.ts @Component({ standalone: true, selector: 'user-controls', template: ` @if (isAdmin) { <button>Erase database</button> } `, }) export class UserControls { isAdmin = true; } ``` In this example, Angular only renders the `<button>` element if the `isAdmin` property is true. Otherwise, it does not appear on the page. ### `@else` block While the `@if` block can be helpful in many situations, it's common to also show fallback UI when the condition is not met. For example, in the `UserControls` component, rather than show a blank screen, it would be helpful to users to know that they're not able to see anything because they're not authenticated. When you need a fallback, similar to JavaScript's `else` clause, add an `@else` block to accomplish the same effect. ```angular-ts // user-controls.component.ts @Component({ standalone: true, selector: 'user-controls', template: ` @if (isAdmin) { <button>Erase database</button> } @else { <p>You are not authorized.</p> } `, }) export class UserControls { isAdmin = true; } ``` ## Rendering a list Another common scenario developers encounter is the need to render a list of items. ### `@for` block Similar to JavaScript’s `for...of` loops, Angular provides the `@for` block for rendering repeated elements. ```angular-html <!-- ingredient-list.component.html --> <ul> @for (ingredient of ingredientList; track ingredient.name) { <li>{{ ingredient.quantity }} - {{ ingredient.name }}</li> } </ul> ``` ```angular-ts // ingredient-list.component.ts @Component({ standalone: true, selector: 'ingredient-list', templateUrl: './ingredient-list.component.html', }) export class IngredientList { ingredientList = [ {name: 'noodles', quantity: 1}, {name: 'miso broth', quantity: 1}, {name: 'egg', quantity: 2}, ]; } ``` However, unlike a standard `for...of` loop, you might've noticed that there's an additional `track` keyword. #### `track` property When Angular renders a list of elements with `@for`, those items can later change or move. Angular needs to track each element through any reordering, usually by treating a property of the item as a unique identifier or key. This ensures any updates to the list are reflected correctly in the UI and tracked properly within Angular, especially in the case of stateful elements or animations. To accomplish this, we can provide a unique key to Angular with the `track` keyword. ## Next Step With the ability to determine when and how templates are rendered, it's time to learn how we handle an important aspect of most applications: handling user input. <docs-pill-row> <docs-pill title="Handling User Interaction" href="essentials/handling-user-interaction" /> </docs-pill-row>
004766
<docs-decorative-header title="Components" imgSrc="adev/src/assets/images/components.svg"> <!-- markdownlint-disable-line --> The fundamental building block for creating applications in Angular. </docs-decorative-header> Components provide structure for organizing your project into easy-to-understand parts with clear responsibilities so that your code is maintainable and scalable. Here is an example of how a Todo application could be broken down into a tree of components. ```mermaid flowchart TD A[TodoApp]-->B A-->C B[TodoList]-->D C[TodoMetrics] D[TodoListItem] ``` In this guide, we'll take a look at how to create and use components in Angular. ## Defining a Component Every component has the following core properties: 1. A `@Component`[decorator](https://www.typescriptlang.org/docs/handbook/decorators.html) that contains some configuration 2. An HTML template that controls what renders into the DOM 3. A [CSS selector](https://developer.mozilla.org/docs/Learn/CSS/Building_blocks/Selectors) that defines how the component is used in HTML 4. A TypeScript class with behaviors such as managing state, handling user input, or fetching data from a server. Here is a simplified example of a TodoListItem component. ```angular-ts // todo-list-item.component.ts @Component({ selector: 'todo-list-item', template: ` <li>(TODO) Read Angular Essentials Guide</li> `, }) export class TodoListItem { /* Component behavior is defined in here */ } ``` Other common metadata that you'll also see in components include: - `standalone: true` — The recommended approach of streamlining the authoring experience of components - `styles` — A string or array of strings that contains any CSS styles you want applied to the component Knowing this, here is an updated version of our `TodoListItem` component. ```angular-ts // todo-list-item.component.ts @Component({ standalone: true, selector: 'todo-list-item', template: ` <li>(TODO) Read Angular Essentials Guide</li> `, styles: ` li { color: red; font-weight: 300; } `, }) export class TodoListItem { /* Component behavior is defined in here */ } ``` ### Separating HTML and CSS into separate files For teams that prefer managing their HTML and/or CSS in separate files, Angular provides two additional properties: `templateUrl` and `styleUrl`. Using the previous `TodoListItem` component, the alternative approach looks like: ```angular-ts // todo-list-item.component.ts @Component({ standalone: true, selector: 'todo-list-item', templateUrl: './todo-list-item.component.html', styleUrl: './todo-list-item.component.css', }) export class TodoListItem { /* Component behavior is defined in here */ } ``` ```angular-html <!-- todo-list-item.component.html --> <li>(TODO) Read Angular Essentials Guide</li> ``` ```css /* todo-list-item.component.css */ li { color: red; font-weight: 300; } ``` ## Using a Component One advantage of component architecture is that your application is modular. In other words, components can be used in other components. To use a component, you need to: 1. Import the component into the file 2. Add it to the component's `imports` array 3. Use the component's selector in the `template` Here's an example of a `TodoList` component importing the `TodoListItem` component from before: ```angular-ts // todo-list.component.ts import {TodoListItem} from './todo-list-item.component.ts'; @Component({ standalone: true, imports: [TodoListItem], template: ` <ul> <todo-list-item></todo-list-item> </ul> `, }) export class TodoList {} ``` ## Next Step Now that you know how components work in Angular, it's time to learn how we add and manage dynamic data in our application. <docs-pill-row> <docs-pill title="Managing Dynamic Data" href="essentials/managing-dynamic-data" /> </docs-pill-row>
004807
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* tslint:disable:no-console */ // #docregion Component import {Component} from '@angular/core'; import {FormArray, FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form [formGroup]="form" (ngSubmit)="onSubmit()"> <div formArrayName="cities"> <div *ngFor="let city of cities.controls; index as i"> <input [formControlName]="i" placeholder="City" /> </div> </div> <button>Submit</button> </form> <button (click)="addCity()">Add City</button> <button (click)="setPreset()">Set preset</button> `, standalone: false, }) export class NestedFormArray { form = new FormGroup({ cities: new FormArray([new FormControl('SF'), new FormControl('NY')]), }); get cities(): FormArray { return this.form.get('cities') as FormArray; } addCity() { this.cities.push(new FormControl()); } onSubmit() { console.log(this.cities.value); // ['SF', 'NY'] console.log(this.form.value); // { cities: ['SF', 'NY'] } } setPreset() { this.cities.patchValue(['LA', 'MTV']); } } // #enddocregion
004813
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Component import {Component} from '@angular/core'; @Component({ selector: 'example-app', template: ` <form #f="ngForm"> <select name="state" ngModel> <option value="" disabled>Choose a state</option> <option *ngFor="let state of states" [ngValue]="state"> {{ state.abbrev }} </option> </select> </form> <p>Form value: {{ f.value | json }}</p> <!-- example value: {state: {name: 'New York', abbrev: 'NY'} } --> `, standalone: false, }) export class SelectControlComp { states = [ {name: 'Arizona', abbrev: 'AZ'}, {name: 'California', abbrev: 'CA'}, {name: 'Colorado', abbrev: 'CO'}, {name: 'New York', abbrev: 'NY'}, {name: 'Pennsylvania', abbrev: 'PA'}, ]; } // #enddocregion
004825
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* tslint:disable:no-console */ // #docregion Component import {Component} from '@angular/core'; import {NgForm} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate> <input name="first" ngModel required #first="ngModel" /> <input name="last" ngModel /> <button>Submit</button> </form> <p>First name value: {{ first.value }}</p> <p>First name valid: {{ first.valid }}</p> <p>Form value: {{ f.value | json }}</p> <p>Form valid: {{ f.valid }}</p> `, standalone: false, }) export class SimpleFormComp { onSubmit(f: NgForm) { console.log(f.value); // { first: '', last: '' } console.log(f.valid); // false } } // #enddocregion
004834
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { inject, InjectFlags, InjectionToken, InjectOptions, Injector, ProviderToken, ɵsetCurrentInjector as setCurrentInjector, ɵsetInjectorProfilerContext, } from '@angular/core'; class MockRootScopeInjector implements Injector { constructor(readonly parent: Injector) {} get<T>( token: ProviderToken<T>, defaultValue?: any, flags: InjectFlags | InjectOptions = InjectFlags.Default, ): T { if ((token as any).ɵprov && (token as any).ɵprov.providedIn === 'root') { const old = setCurrentInjector(this); const previousInjectorProfilerContext = ɵsetInjectorProfilerContext({ injector: this, token: null, }); try { return (token as any).ɵprov.factory(); } finally { setCurrentInjector(old); ɵsetInjectorProfilerContext(previousInjectorProfilerContext); } } return this.parent.get(token, defaultValue, flags); } } { describe('injector metadata examples', () => { it('works', () => { // #docregion Injector const injector: Injector = Injector.create({ providers: [{provide: 'validToken', useValue: 'Value'}], }); expect(injector.get('validToken')).toEqual('Value'); expect(() => injector.get('invalidToken')).toThrowError(); expect(injector.get('invalidToken', 'notFound')).toEqual('notFound'); // #enddocregion }); it('injects injector', () => { // #docregion injectInjector const injector = Injector.create({providers: []}); expect(injector.get(Injector)).toBe(injector); // #enddocregion }); it('should infer type', () => { // #docregion InjectionToken const BASE_URL = new InjectionToken<string>('BaseUrl'); const injector = Injector.create({ providers: [{provide: BASE_URL, useValue: 'http://localhost'}], }); const url = injector.get(BASE_URL); // Note: since `BASE_URL` is `InjectionToken<string>` // `url` is correctly inferred to be `string` expect(url).toBe('http://localhost'); // #enddocregion }); it('injects a tree-shakeable InjectionToken', () => { class MyDep {} const injector = new MockRootScopeInjector( Injector.create({providers: [{provide: MyDep, deps: []}]}), ); // #docregion ShakableInjectionToken class MyService { constructor(readonly myDep: MyDep) {} } const MY_SERVICE_TOKEN = new InjectionToken<MyService>('Manually constructed MyService', { providedIn: 'root', factory: () => new MyService(inject(MyDep)), }); const instance = injector.get(MY_SERVICE_TOKEN); expect(instance instanceof MyService).toBeTruthy(); expect(instance.myDep instanceof MyDep).toBeTruthy(); // #enddocregion }); }); }
004870
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { AfterContentChecked, AfterContentInit, AfterViewChecked, AfterViewInit, Component, DoCheck, Input, OnChanges, OnDestroy, OnInit, SimpleChanges, Type, } from '@angular/core'; import {TestBed} from '@angular/core/testing'; (function () { describe('lifecycle hooks examples', () => { it('should work with ngOnInit', () => { // #docregion OnInit @Component({ selector: 'my-cmp', template: ` ... `, standalone: false, }) class MyComponent implements OnInit { ngOnInit() { // ... } } // #enddocregion expect(createAndLogComponent(MyComponent)).toEqual([['ngOnInit', []]]); }); it('should work with ngDoCheck', () => { // #docregion DoCheck @Component({ selector: 'my-cmp', template: ` ... `, standalone: false, }) class MyComponent implements DoCheck { ngDoCheck() { // ... } } // #enddocregion expect(createAndLogComponent(MyComponent)).toEqual([['ngDoCheck', []]]); }); it('should work with ngAfterContentChecked', () => { // #docregion AfterContentChecked @Component({ selector: 'my-cmp', template: ` ... `, standalone: false, }) class MyComponent implements AfterContentChecked { ngAfterContentChecked() { // ... } } // #enddocregion expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterContentChecked', []]]); }); it('should work with ngAfterContentInit', () => { // #docregion AfterContentInit @Component({ selector: 'my-cmp', template: ` ... `, standalone: false, }) class MyComponent implements AfterContentInit { ngAfterContentInit() { // ... } } // #enddocregion expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterContentInit', []]]); }); it('should work with ngAfterViewChecked', () => { // #docregion AfterViewChecked @Component({ selector: 'my-cmp', template: ` ... `, standalone: false, }) class MyComponent implements AfterViewChecked { ngAfterViewChecked() { // ... } } // #enddocregion expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterViewChecked', []]]); }); it('should work with ngAfterViewInit', () => { // #docregion AfterViewInit @Component({ selector: 'my-cmp', template: ` ... `, standalone: false, }) class MyComponent implements AfterViewInit { ngAfterViewInit() { // ... } } // #enddocregion expect(createAndLogComponent(MyComponent)).toEqual([['ngAfterViewInit', []]]); }); it('should work with ngOnDestroy', () => { // #docregion OnDestroy @Component({ selector: 'my-cmp', template: ` ... `, standalone: false, }) class MyComponent implements OnDestroy { ngOnDestroy() { // ... } } // #enddocregion expect(createAndLogComponent(MyComponent)).toEqual([['ngOnDestroy', []]]); }); it('should work with ngOnChanges', () => { // #docregion OnChanges @Component({ selector: 'my-cmp', template: ` ... `, standalone: false, }) class MyComponent implements OnChanges { @Input() prop: number = 0; ngOnChanges(changes: SimpleChanges) { // changes.prop contains the old and the new value... } } // #enddocregion const log = createAndLogComponent(MyComponent, ['prop']); expect(log.length).toBe(1); expect(log[0][0]).toBe('ngOnChanges'); const changes: SimpleChanges = log[0][1][0]; expect(changes['prop'].currentValue).toBe(true); }); }); function createAndLogComponent(clazz: Type<any>, inputs: string[] = []): any[] { const log: any[] = []; createLoggingSpiesFromProto(clazz, log); const inputBindings = inputs.map((input) => `[${input}] = true`).join(' '); @Component({ template: ` <my-cmp ${inputBindings}></my-cmp> `, standalone: false, }) class ParentComponent {} const fixture = TestBed.configureTestingModule({ declarations: [ParentComponent, clazz], }).createComponent(ParentComponent); fixture.detectChanges(); fixture.destroy(); return log; } function createLoggingSpiesFromProto(clazz: Type<any>, log: any[]) { const proto = clazz.prototype; // For ES2015+ classes, members are not enumerable in the prototype. Object.getOwnPropertyNames(proto).forEach((method) => { if (method === 'constructor') { return; } proto[method] = (...args: any[]) => { log.push([method, args]); }; }); } })();
004878
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Component, Injectable, Injector, Input, NgModule, OnInit, TemplateRef, ViewChild, ViewContainerRef, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; // #docregion SimpleExample @Component({ selector: 'hello-world', template: 'Hello World!', standalone: false, }) export class HelloWorld {} @Component({ selector: 'ng-component-outlet-simple-example', template: ` <ng-container *ngComponentOutlet="HelloWorld"></ng-container> `, standalone: false, }) export class NgComponentOutletSimpleExample { // This field is necessary to expose HelloWorld to the template. HelloWorld = HelloWorld; } // #enddocregion // #docregion CompleteExample @Injectable() export class Greeter { suffix = '!'; } @Component({ selector: 'complete-component', template: ` {{ label }}: <ng-content></ng-content> <ng-content></ng-content> {{ greeter.suffix }} `, standalone: false, }) export class CompleteComponent { @Input() label!: string; constructor(public greeter: Greeter) {} } @Component({ selector: 'ng-component-outlet-complete-example', template: ` <ng-template #ahoj>Ahoj</ng-template> <ng-template #svet>Svet</ng-template> <ng-container *ngComponentOutlet=" CompleteComponent; inputs: myInputs; injector: myInjector; content: myContent " ></ng-container> `, standalone: false, }) export class NgComponentOutletCompleteExample implements OnInit { // This field is necessary to expose CompleteComponent to the template. CompleteComponent = CompleteComponent; myInputs = {'label': 'Complete'}; myInjector: Injector; @ViewChild('ahoj', {static: true}) ahojTemplateRef!: TemplateRef<any>; @ViewChild('svet', {static: true}) svetTemplateRef!: TemplateRef<any>; myContent?: any[][]; constructor( injector: Injector, private vcr: ViewContainerRef, ) { this.myInjector = Injector.create({ providers: [{provide: Greeter, deps: []}], parent: injector, }); } ngOnInit() { // Create the projectable content from the templates this.myContent = [ this.vcr.createEmbeddedView(this.ahojTemplateRef).rootNodes, this.vcr.createEmbeddedView(this.svetTemplateRef).rootNodes, ]; } } // #enddocregion @Component({ selector: 'example-app', template: ` <ng-component-outlet-simple-example></ng-component-outlet-simple-example> <hr /> <ng-component-outlet-complete-example></ng-component-outlet-complete-example> `, standalone: false, }) export class AppComponent {} @NgModule({ imports: [BrowserModule], declarations: [ AppComponent, NgComponentOutletSimpleExample, NgComponentOutletCompleteExample, HelloWorld, CompleteComponent, ], }) export class AppModule {}
004915
/** * @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, inject, Injectable} from '@angular/core'; import {bootstrapApplication} from '@angular/platform-browser'; import { ActivatedRoute, ActivatedRouteSnapshot, CanActivateChildFn, CanActivateFn, CanMatchFn, provideRouter, ResolveFn, Route, RouterStateSnapshot, UrlSegment, } from '@angular/router'; @Component({ template: '', standalone: false, }) export class App {} @Component({ template: '', standalone: false, }) export class TeamComponent {} // #docregion CanActivateFn @Injectable() class UserToken {} @Injectable() class PermissionsService { canActivate(currentUser: UserToken, userId: string): boolean { return true; } canMatch(currentUser: UserToken): boolean { return true; } } const canActivateTeam: CanActivateFn = ( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ) => { return inject(PermissionsService).canActivate(inject(UserToken), route.params['id']); }; // #enddocregion // #docregion CanActivateFnInRoute bootstrapApplication(App, { providers: [ provideRouter([ { path: 'team/:id', component: TeamComponent, canActivate: [canActivateTeam], }, ]), ], }); // #enddocregion // #docregion CanActivateChildFn const canActivateChildExample: CanActivateChildFn = ( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ) => { return inject(PermissionsService).canActivate(inject(UserToken), route.params['id']); }; bootstrapApplication(App, { providers: [ provideRouter([ { path: 'team/:id', component: TeamComponent, canActivateChild: [canActivateChildExample], children: [], }, ]), ], }); // #enddocregion // #docregion CanDeactivateFn @Component({ template: '', standalone: false, }) export class UserComponent { hasUnsavedChanges = true; } bootstrapApplication(App, { providers: [ provideRouter([ { path: 'user/:id', component: UserComponent, canDeactivate: [(component: UserComponent) => !component.hasUnsavedChanges], }, ]), ], }); // #enddocregion // #docregion CanMatchFn const canMatchTeam: CanMatchFn = (route: Route, segments: UrlSegment[]) => { return inject(PermissionsService).canMatch(inject(UserToken)); }; bootstrapApplication(App, { providers: [ provideRouter([ { path: 'team/:id', component: TeamComponent, canMatch: [canMatchTeam], }, ]), ], }); // #enddocregion // #docregion ResolveDataUse @Component({ template: '', standalone: false, }) export class HeroDetailComponent { constructor(private activatedRoute: ActivatedRoute) {} ngOnInit() { this.activatedRoute.data.subscribe(({hero}) => { // do something with your resolved data ... }); } } // #enddocregion // #docregion ResolveFn interface Hero { name: string; } @Injectable() export class HeroService { getHero(id: string) { return {name: `Superman-${id}`}; } } export const heroResolver: ResolveFn<Hero> = ( route: ActivatedRouteSnapshot, state: RouterStateSnapshot, ) => { return inject(HeroService).getHero(route.paramMap.get('id')!); }; bootstrapApplication(App, { providers: [ provideRouter([ { path: 'detail/:id', component: HeroDetailComponent, resolve: {hero: heroResolver}, }, ]), ], }); // #enddocregion
004917
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion activated-route import {Component, NgModule} from '@angular/core'; // #enddocregion activated-route import {BrowserModule} from '@angular/platform-browser'; // #docregion activated-route import {ActivatedRoute, RouterModule} from '@angular/router'; import {Observable} from 'rxjs'; import {map} from 'rxjs/operators'; // #enddocregion activated-route // #docregion activated-route @Component({ // #enddocregion activated-route selector: 'example-app', template: '...', standalone: false, }) export class ActivatedRouteComponent { constructor(route: ActivatedRoute) { const id: Observable<string> = route.params.pipe(map((p) => p['id'])); const url: Observable<string> = route.url.pipe(map((segments) => segments.join(''))); // route.data includes both `data` and `resolve` const user = route.data.pipe(map((d) => d['user'])); } } // #enddocregion activated-route @NgModule({ imports: [BrowserModule, RouterModule.forRoot([])], declarations: [ActivatedRouteComponent], bootstrap: [ActivatedRouteComponent], }) export class AppModule {}
004922
# CLI Overview and Command Reference The Angular CLI is a command-line interface tool that you use to initialize, develop, scaffold, and maintain Angular applications directly from a command shell. ## Installing Angular CLI Major versions of Angular CLI follow the supported major version of Angular, but minor versions can be released separately. Install the CLI using the `npm` package manager: <code-example format="shell" language="shell"> npm install -g &commat;angular/cli<aio-angular-dist-tag class="pln"></aio-angular-dist-tag> </code-example> For details about changes between versions, and information about updating from previous releases, see the Releases tab on GitHub: https://github.com/angular/angular-cli/releases ## Basic workflow Invoke the tool on the command line through the `ng` executable. Online help is available on the command line. Enter the following to list commands or options for a given command \(such as [new](cli/new)\) with a short description. <code-example format="shell" language="shell"> ng --help ng new --help </code-example> To create, build, and serve a new, basic Angular project on a development server, go to the parent directory of your new workspace use the following commands: <code-example format="shell" language="shell"> ng new my-first-project cd my-first-project ng serve </code-example> In your browser, open http://localhost:4200/ to see the new application run. When you use the [ng serve](cli/serve) command to build an application and serve it locally, the server automatically rebuilds the application and reloads the page when you change any of the source files. <div class="alert is-helpful"> When you run `ng new my-first-project` a new folder, named `my-first-project`, will be created in the current working directory. Since you want to be able to create files inside that folder, make sure you have sufficient rights in the current working directory before running the command. If the current working directory is not the right place for your project, you can change to a more appropriate directory by running `cd <path-to-other-directory>`. </div> ## Workspaces and project files The [ng new](cli/new) command creates an *Angular workspace* folder and generates a new application skeleton. A workspace can contain multiple applications and libraries. The initial application created by the [ng new](cli/new) command is at the top level of the workspace. When you generate an additional application or library in a workspace, it goes into a `projects/` subfolder. A newly generated application contains the source files for a root module, with a root component and template. Each application has a `src` folder that contains the logic, data, and assets. You can edit the generated files directly, or add to and modify them using CLI commands. Use the [ng generate](cli/generate) command to add new files for additional components and services, and code for new pipes, directives, and so on. Commands such as [add](cli/add) and [generate](cli/generate), which create or operate on applications and libraries, must be executed from within a workspace or project folder. * See more about the [Workspace file structure](guide/file-structure). ### Workspace and project configuration A single workspace configuration file, `angular.json`, is created at the top level of the workspace. This is where you can set per-project defaults for CLI command options, and specify configurations to use when the CLI builds a project for different targets. The [ng config](cli/config) command lets you set and retrieve configuration values from the command line, or you can edit the `angular.json` file directly. <div class="alert is-helpful"> **NOTE**: <br /> Option names in the configuration file must use [camelCase](guide/glossary#case-types), while option names supplied to commands must be dash-case. </div> * See more about [Workspace Configuration](guide/workspace-config). ## CLI command-language syntax Command syntax is shown as follows: `ng` *<command-name>* *<required-arg>* [*optional-arg*] `[options]` * Most commands, and some options, have aliases. Aliases are shown in the syntax statement for each command. * Option names are prefixed with a double dash \(`--`\) characters. Option aliases are prefixed with a single dash \(`-`\) character. Arguments are not prefixed. For example: <code-example format="shell" language="shell"> ng build my-app -c production </code-example> * Typically, the name of a generated artifact can be given as an argument to the command or specified with the `--name` option. * Arguments and option names must be given in [dash-case](guide/glossary#case-types). For example: `--my-option-name` ### Boolean options Boolean options have two forms: `--this-option` sets the flag to `true`, `--no-this-option` sets it to `false`. If neither option is supplied, the flag remains in its default state, as listed in the reference documentation. ### Array options Array options can be provided in two forms: `--option value1 value2` or `--option value1 --option value2`. ### Relative paths Options that specify files can be given as absolute paths, or as paths relative to the current working directory, which is generally either the workspace or project root. ### Schematics The [ng generate](cli/generate) and [ng add](cli/add) commands take, as an argument, the artifact or library to be generated or added to the current project. In addition to any general options, each artifact or library defines its own options in a *schematic*. Schematic options are supplied to the command in the same format as immediate command options. <!-- links --> <!-- external links --> <!-- end links --> @reviewed 2022-02-28
004949
// #docregion import {CommonModule} from '@angular/common'; import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {AppComponent} from './app.component'; import {ActorFormComponent} from './actor-form/actor-form.component'; @NgModule({ imports: [BrowserModule, CommonModule, FormsModule], declarations: [AppComponent, ActorFormComponent], providers: [], bootstrap: [AppComponent], }) export class AppModule {}
004950
// #docregion import {Component} from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', standalone: false, }) export class AppComponent {}
004962
import {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MyLibService {}
005027
<!DOCTYPE html> <html lang="en"> <head> <title>Angular Quickstart Seed</title> <base href="/"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="styles.css"> <!-- Polyfills --> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/bundles/zone.umd.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <script src="systemjs.config.js"></script> <script> System.import('main.js').catch(function(err){ console.error(err); }); </script> </head> <body> <app-root><!-- content managed by Angular --></app-root> </body> </html>
005044
import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {FormsModule} from '@angular/forms'; import {FavoriteColorComponent} from './favorite-color/favorite-color.component'; @NgModule({ imports: [CommonModule, FormsModule], declarations: [FavoriteColorComponent], exports: [FavoriteColorComponent], }) export class TemplateModule {}
005051
import {bootstrapApplication, provideProtractorTestingSupport} from '@angular/platform-browser'; import {provideHttpClient} from '@angular/common/http'; import {AppComponent} from './app/app.component'; bootstrapApplication(AppComponent, { // HttpClientModule is only used in deprecated HeroListComponent providers: [ provideHttpClient(), provideProtractorTestingSupport(), // essential for e2e testing ], });
005085
import {provideHttpClient} from '@angular/common/http'; import {ApplicationConfig, importProvidersFrom} from '@angular/core'; import {provideProtractorTestingSupport} from '@angular/platform-browser'; import {provideRouter} from '@angular/router'; import {HttpClientInMemoryWebApiModule} from 'angular-in-memory-web-api'; import {routes} from './app.routes'; import {InMemoryDataService} from './in-memory-data.service'; import {HeroService} from './model/hero.service'; import {UserService} from './model/user.service'; import {TwainService} from './twain/twain.service'; export const appProviders = [ provideRouter(routes), provideHttpClient(), provideProtractorTestingSupport(), importProvidersFrom( // The HttpClientInMemoryWebApiModule module intercepts HTTP requests // and returns simulated server responses. // Remove it when a real server is ready to receive requests. HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, {dataEncapsulation: false}), ), HeroService, TwainService, UserService, ]; export const appConfig: ApplicationConfig = { providers: appProviders, };
005088
/* eslint-disable @angular-eslint/directive-selector, guard-for-in, @angular-eslint/no-input-rename */ import { Component, ContentChildren, Directive, EventEmitter, HostBinding, HostListener, Injectable, Input, OnChanges, OnDestroy, OnInit, Optional, Output, Pipe, PipeTransform, SimpleChanges, } from '@angular/core'; import {FormsModule} from '@angular/forms'; import {of} from 'rxjs'; import {delay} from 'rxjs/operators'; import {sharedImports} from '../shared/shared'; ////////// The App: Services and Components for the tests. ////////////// export interface Hero { name: string; } ////////// Services /////////////// @Injectable() export class ValueService { value = 'real value'; getValue() { return this.value; } setValue(value: string) { this.value = value; } getObservableValue() { return of('observable value'); } getPromiseValue() { return Promise.resolve('promise value'); } getObservableDelayValue() { return of('observable delay value').pipe(delay(10)); } } // #docregion MasterService @Injectable() export class MasterService { constructor(private valueService: ValueService) {} getValue() { return this.valueService.getValue(); } } // #enddocregion MasterService /////////// Pipe //////////////// /* * Reverse the input string. */ @Pipe({name: 'reverse', standalone: true}) export class ReversePipe implements PipeTransform { transform(s: string) { let r = ''; for (let i = s.length; i; ) { r += s[--i]; } return r; } } //////////// Components ///////////// @Component({ standalone: true, selector: 'bank-account', template: ` Bank Name: {{ bank }} Account Id: {{ id }} `, }) export class BankAccountComponent { @Input() bank = ''; @Input('account') id = ''; // Removed on 12/02/2016 when ceased public discussion of the `Renderer`. Revive in future? // constructor(private renderer: Renderer, private el: ElementRef ) { // renderer.setElementProperty(el.nativeElement, 'customProperty', true); // } } /** A component with attributes, styles, classes, and property setting */ @Component({ standalone: true, selector: 'bank-account-parent', template: ` <bank-account bank="RBC" account="4747" [style.width.px]="width" [style.color]="color" [class.closed]="isClosed" [class.open]="!isClosed" > </bank-account> `, imports: [BankAccountComponent], }) export class BankAccountParentComponent { width = 200; color = 'red'; isClosed = true; } // #docregion LightswitchComp @Component({ standalone: true, selector: 'lightswitch-comp', template: ` <button type="button" (click)="clicked()">Click me!</button> <span>{{ message }}</span>`, }) export class LightswitchComponent { isOn = false; clicked() { this.isOn = !this.isOn; } get message() { return `The light is ${this.isOn ? 'On' : 'Off'}`; } } // #enddocregion LightswitchComp @Component({ standalone: true, selector: 'child-1', template: '<span>Child-1({{text}})</span>', }) export class Child1Component { @Input() text = 'Original'; } @Component({ standalone: true, selector: 'child-2', template: '<div>Child-2({{text}})</div>', }) export class Child2Component { @Input() text = ''; } @Component({ standalone: true, selector: 'child-3', template: '<div>Child-3({{text}})</div>', }) export class Child3Component { @Input() text = ''; } @Component({ standalone: true, selector: 'input-comp', template: '<input [(ngModel)]="name">', imports: [FormsModule], }) export class InputComponent { name = 'John'; } /* Prefer this metadata syntax */ // @Directive({ // selector: 'input[value]', // host: { // '[value]': 'value', // '(input)': 'valueChange.emit($event.target.value)' // }, // inputs: ['value'], // outputs: ['valueChange'] // }) // export class InputValueBinderDirective { // value: any; // valueChange: EventEmitter<any> = new EventEmitter(); // } // As the styleguide recommends @Directive({standalone: true, selector: 'input[value]'}) export class InputValueBinderDirective { @HostBinding() @Input() value: any; @Output() valueChange: EventEmitter<any> = new EventEmitter(); @HostListener('input', ['$event.target.value']) onInput(value: any) { this.valueChange.emit(value); } } @Component({ standalone: true, selector: 'input-value-comp', template: ` Name: <input [value]="name" /> {{ name }} `, }) export class InputValueBinderComponent { name = 'Sally'; // initial value } @Component({ standalone: true, selector: 'parent-comp', imports: [Child1Component], template: 'Parent(<child-1></child-1>)', }) export class ParentComponent {} @Component({ standalone: true, selector: 'io-comp', template: '<button type="button" class="hero" (click)="click()">Original {{hero.name}}</button>', }) export class IoComponent { @Input() hero!: Hero; @Output() selected = new EventEmitter<Hero>(); click() { this.selected.emit(this.hero); } } @Component({ standalone: true, selector: 'io-parent-comp', template: ` @if (!selectedHero) { <p><i>Click to select a hero</i></p> } @if (selectedHero) { <p>The selected hero is {{ selectedHero.name }}</p> } @for (hero of heroes; track hero) { <io-comp [hero]="hero" (selected)="onSelect($event)"> </io-comp> } `, imports: [IoComponent, sharedImports], }) export class IoParentComponent { heroes: Hero[] = [{name: 'Bob'}, {name: 'Carol'}, {name: 'Ted'}, {name: 'Alice'}]; selectedHero!: Hero; onSelect(hero: Hero) { this.selectedHero = hero; } } @Component({ standalone: true, selector: 'my-if-comp', template: 'MyIf(@if (showMore) {<span>More</span>})', imports: [sharedImports], }) export class MyIfComponent { showMore = false; } @Component({ standalone: true, selector: 'my-service-comp', template: 'injected value: {{valueService.value}}', providers: [ValueService], }) export class TestProvidersComponent { constructor(public valueService: ValueService) {} } @Component({ standalone: true, selector: 'my-service-comp', template: 'injected value: {{valueService.value}}', viewProviders: [ValueService], }) export class TestViewProvidersComponent { constructor(public valueService: ValueService) {} } @Component({ standalone: true, selector: 'external-template-comp', templateUrl: './demo-external-template.html', }) export class ExternalTemplateComponent implements OnInit { serviceValue = ''; constructor(@Optional() private service?: ValueService) {} ngOnInit() { if (this.service) { this.serviceValue = this.service.getValue(); } } } @Component({ standalone: true, selector: 'comp-w-ext-comp', imports: [ExternalTemplateComponent], template: ` <h3>comp-w-ext-comp</h3> <external-template-comp></external-template-comp> `, }) export class InnerCompWithExternalTemplateComponent {} @Component({standalone: true, selector: 'needs-content', template: '<ng-content></ng-content>'}) export class NeedsContentComponent { // children with #content local variable @ContentChildren('content') children: any; } ///////// MyIfChildComp ////////
005089
@Component({ standalone: true, selector: 'my-if-child-1', template: ` <h4>MyIfChildComp</h4> <div> <label for="child-value" >Child value: <input id="child-value" [(ngModel)]="childValue" /> </label> </div> <p><i>Change log:</i></p> @for (log of changeLog; track log; let i = $index) { <div>{{ i + 1 }} - {{ log }}</div> }`, imports: [FormsModule, sharedImports], }) export class MyIfChildComponent implements OnInit, OnChanges, OnDestroy { @Input() value = ''; @Output() valueChange = new EventEmitter<string>(); get childValue() { return this.value; } set childValue(v: string) { if (this.value === v) { return; } this.value = v; this.valueChange.emit(v); } changeLog: string[] = []; ngOnInitCalled = false; ngOnChangesCounter = 0; ngOnDestroyCalled = false; ngOnInit() { this.ngOnInitCalled = true; this.changeLog.push('ngOnInit called'); } ngOnDestroy() { this.ngOnDestroyCalled = true; this.changeLog.push('ngOnDestroy called'); } ngOnChanges(changes: SimpleChanges) { for (const propName in changes) { this.ngOnChangesCounter += 1; const prop = changes[propName]; const cur = JSON.stringify(prop.currentValue); const prev = JSON.stringify(prop.previousValue); this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`); } } } ///////// MyIfParentComp //////// @Component({ standalone: true, selector: 'my-if-parent-comp', template: ` <h3>MyIfParentComp</h3> <label for="parent" >Parent value: <input id="parent" [(ngModel)]="parentValue" /> </label> <button type="button" (click)="clicked()">{{ toggleLabel }} Child</button><br /> @if (showChild) { <div style="margin: 4px; padding: 4px; background-color: aliceblue;"> <my-if-child-1 [(value)]="parentValue"></my-if-child-1> </div> } `, imports: [FormsModule, MyIfChildComponent, sharedImports], }) export class MyIfParentComponent implements OnInit { ngOnInitCalled = false; parentValue = 'Hello, World'; showChild = false; toggleLabel = 'Unknown'; ngOnInit() { this.ngOnInitCalled = true; this.clicked(); } clicked() { this.showChild = !this.showChild; this.toggleLabel = this.showChild ? 'Close' : 'Show'; } } @Component({ standalone: true, selector: 'reverse-pipe-comp', template: ` <input [(ngModel)]="text" /> <span>{{ text | reverse }}</span> `, imports: [ReversePipe, FormsModule], }) export class ReversePipeComponent { text = 'my dog has fleas.'; } @Component({ standalone: true, imports: [NeedsContentComponent], template: '<div>Replace Me</div>', }) export class ShellComponent {} @Component({ standalone: true, selector: 'demo-comp', template: ` <h1>Specs Demo</h1> <my-if-parent-comp></my-if-parent-comp> <hr /> <h3>Input/Output Component</h3> <io-parent-comp></io-parent-comp> <hr /> <h3>External Template Component</h3> <external-template-comp></external-template-comp> <hr /> <h3>Component With External Template Component</h3> <comp-w-ext-comp></comp-w-ext-comp> <hr /> <h3>Reverse Pipe</h3> <reverse-pipe-comp></reverse-pipe-comp> <hr /> <h3>InputValueBinder Directive</h3> <input-value-comp></input-value-comp> <hr /> <h3>Button Component</h3> <lightswitch-comp></lightswitch-comp> <hr /> <h3>Needs Content</h3> <needs-content #nc> <child-1 #content text="My"></child-1> <child-2 #content text="dog"></child-2> <child-2 text="has"></child-2> <child-3 #content text="fleas"></child-3> <div #content>!</div> </needs-content> `, imports: [ Child1Component, Child2Component, Child3Component, ExternalTemplateComponent, InnerCompWithExternalTemplateComponent, InputValueBinderComponent, IoParentComponent, LightswitchComponent, NeedsContentComponent, ReversePipeComponent, MyIfParentComponent, ], }) export class DemoComponent {} //////// Aggregations //////////// export const demoProviders = [MasterService, ValueService];
005106
// #docplaster import {ComponentFixture, inject, TestBed} from '@angular/core/testing'; import {UserService} from '../model/user.service'; import {WelcomeComponent} from './welcome.component'; // #docregion mock-user-service class MockUserService { isLoggedIn = true; user = {name: 'Test User'}; } // #enddocregion mock-user-service describe('WelcomeComponent', () => { let comp: WelcomeComponent; let fixture: ComponentFixture<WelcomeComponent>; let componentUserService: UserService; // the actually injected service let userService: UserService; // the TestBed injected service let el: HTMLElement; // the DOM element with the welcome message // #docregion setup beforeEach(() => { fixture = TestBed.createComponent(WelcomeComponent); fixture.autoDetectChanges(); comp = fixture.componentInstance; // #docregion injected-service // UserService actually injected into the component userService = fixture.debugElement.injector.get(UserService); // #enddocregion injected-service componentUserService = userService; // #docregion inject-from-testbed // UserService from the root injector userService = TestBed.inject(UserService); // #enddocregion inject-from-testbed // get the "welcome" element by CSS selector (e.g., by class name) el = fixture.nativeElement.querySelector('.welcome'); }); // #enddocregion setup // #docregion tests it('should welcome the user', async () => { await fixture.whenStable(); const content = el.textContent; expect(content).withContext('"Welcome ..."').toContain('Welcome'); expect(content).withContext('expected name').toContain('Test User'); }); it('should welcome "Bubba"', async () => { userService.user.set({name: 'Bubba'}); // welcome message hasn't been shown yet await fixture.whenStable(); expect(el.textContent).toContain('Bubba'); }); it('should request login if not logged in', async () => { userService.isLoggedIn.set(false); // welcome message hasn't been shown yet await fixture.whenStable(); const content = el.textContent; expect(content).withContext('not welcomed').not.toContain('Welcome'); expect(content) .withContext('"log in"') .toMatch(/log in/i); }); // #enddocregion tests it("should inject the component's UserService instance", inject( [UserService], (service: UserService) => { expect(service).toBe(componentUserService); }, )); it('TestBed and Component UserService should be the same', () => { expect(userService).toBe(componentUserService); }); });
005109
import {provideHttpClient} from '@angular/common/http'; import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; import {NO_ERRORS_SCHEMA} from '@angular/core'; import {TestBed, waitForAsync} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {NavigationEnd, provideRouter, Router} from '@angular/router'; import {RouterTestingHarness} from '@angular/router/testing'; import {firstValueFrom} from 'rxjs'; import {filter} from 'rxjs/operators'; import {addMatchers, click} from '../../testing'; import {HeroService} from '../model/hero.service'; import {getTestHeroes} from '../model/testing/test-heroes'; import {DashboardComponent} from './dashboard.component'; import {appConfig} from '../app.config'; import {HeroDetailComponent} from '../hero/hero-detail.component'; beforeEach(addMatchers); let comp: DashboardComponent; let harness: RouterTestingHarness; //////// Deep //////////////// describe('DashboardComponent (deep)', () => { compileAndCreate(); tests(clickForDeep); function clickForDeep() { // get first <div class="hero"> const heroEl: HTMLElement = harness.routeNativeElement!.querySelector('.hero')!; click(heroEl); return firstValueFrom( TestBed.inject(Router).events.pipe(filter((e) => e instanceof NavigationEnd)), ); } }); //////// Shallow //////////////// describe('DashboardComponent (shallow)', () => { beforeEach(() => { TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [DashboardComponent, HeroDetailComponent], providers: [provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}])], schemas: [NO_ERRORS_SCHEMA], }), ); }); compileAndCreate(); tests(clickForShallow); function clickForShallow() { // get first <dashboard-hero> DebugElement const heroDe = harness.routeDebugElement!.query(By.css('dashboard-hero')); heroDe.triggerEventHandler('selected', comp.heroes[0]); return Promise.resolve(); } }); /** Add TestBed providers, compile, and create DashboardComponent */ function compileAndCreate() { beforeEach(async () => { // #docregion router-harness TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [DashboardComponent], providers: [ provideRouter([{path: '**', component: DashboardComponent}]), provideHttpClient(), provideHttpClientTesting(), HeroService, ], }), ); harness = await RouterTestingHarness.create(); comp = await harness.navigateByUrl('/', DashboardComponent); TestBed.inject(HttpTestingController).expectOne('api/heroes').flush(getTestHeroes()); // #enddocregion router-harness }); } /** * The (almost) same tests for both. * Only change: the way that the first hero is clicked */ function tests(heroClick: () => Promise<unknown>) { describe('after get dashboard heroes', () => { let router: Router; // Trigger component so it gets heroes and binds to them beforeEach(waitForAsync(() => { router = TestBed.inject(Router); harness.detectChanges(); // runs ngOnInit -> getHeroes })); it('should HAVE heroes', () => { expect(comp.heroes.length) .withContext('should have heroes after service promise resolves') .toBeGreaterThan(0); }); it('should DISPLAY heroes', () => { // Find and examine the displayed heroes // Look for them in the DOM by css class const heroes = harness.routeNativeElement!.querySelectorAll('dashboard-hero'); expect(heroes.length).withContext('should display 4 heroes').toBe(4); }); // #docregion navigate-test it('should tell navigate when hero clicked', async () => { await heroClick(); // trigger click on first inner <div class="hero"> // expecting to navigate to id of the component's first hero const id = comp.heroes[0].id; expect(TestBed.inject(Router).url) .withContext('should nav to HeroDetail for first hero') .toEqual(`/heroes/${id}`); }); // #enddocregion navigate-test }); }
005117
// #docplaster import {fakeAsync, ComponentFixture, TestBed, tick, waitForAsync} from '@angular/core/testing'; import {asyncData, asyncError} from '../../testing'; import {Subject, defer, of, throwError} from 'rxjs'; import {last} from 'rxjs/operators'; import {TwainComponent} from './twain.component'; import {TwainService} from './twain.service'; describe('TwainComponent', () => { let component: TwainComponent; let fixture: ComponentFixture<TwainComponent>; let getQuoteSpy: jasmine.Spy; let quoteEl: HTMLElement; let testQuote: string; // Helper function to get the error message element value // An *ngIf keeps it out of the DOM until there is an error const errorMessage = () => { const el = fixture.nativeElement.querySelector('.error'); return el ? el.textContent : null; }; // #docregion setup beforeEach(() => { TestBed.configureTestingModule({ imports: [TwainComponent], providers: [TwainService], }); testQuote = 'Test Quote'; // #docregion spy // Create a fake TwainService object with a `getQuote()` spy const twainService = TestBed.inject(TwainService); // Make the spy return a synchronous Observable with the test data getQuoteSpy = spyOn(twainService, 'getQuote').and.returnValue(of(testQuote)); // #enddocregion spy fixture = TestBed.createComponent(TwainComponent); fixture.autoDetectChanges(); component = fixture.componentInstance; quoteEl = fixture.nativeElement.querySelector('.twain'); }); // #enddocregion setup describe('when test with synchronous observable', () => { it('should not show quote before OnInit', () => { expect(quoteEl.textContent).withContext('nothing displayed').toBe(''); expect(errorMessage()).withContext('should not show error element').toBeNull(); expect(getQuoteSpy.calls.any()).withContext('getQuote not yet called').toBe(false); }); // The quote would not be immediately available if the service were truly async. // #docregion sync-test it('should show quote after component initialized', async () => { await fixture.whenStable(); // onInit() // sync spy result shows testQuote immediately after init expect(quoteEl.textContent).toBe(testQuote); expect(getQuoteSpy.calls.any()).withContext('getQuote called').toBe(true); }); // #enddocregion sync-test // The error would not be immediately available if the service were truly async. // Use `fakeAsync` because the component error calls `setTimeout` // #docregion error-test it('should display error when TwainService fails', fakeAsync(() => { // tell spy to return an error observable after a timeout getQuoteSpy.and.returnValue( defer(() => { return new Promise((resolve, reject) => { setTimeout(() => { reject('TwainService test failure'); }); }); }), ); fixture.detectChanges(); // onInit() // sync spy errors immediately after init tick(); // flush the setTimeout() fixture.detectChanges(); // update errorMessage within setTimeout() expect(errorMessage()) .withContext('should display error') .toMatch(/test failure/); expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); })); // #enddocregion error-test }); describe('when test with asynchronous observable', () => { beforeEach(() => { // #docregion async-setup // Simulate delayed observable values with the `asyncData()` helper getQuoteSpy.and.returnValue(asyncData(testQuote)); // #enddocregion async-setup }); it('should not show quote before OnInit', () => { expect(quoteEl.textContent).withContext('nothing displayed').toBe(''); expect(errorMessage()).withContext('should not show error element').toBeNull(); expect(getQuoteSpy.calls.any()).withContext('getQuote not yet called').toBe(false); }); it('should still not show quote after component initialized', () => { fixture.detectChanges(); // getQuote service is async => still has not returned with quote // so should show the start value, '...' expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); expect(errorMessage()).withContext('should not show error').toBeNull(); expect(getQuoteSpy.calls.any()).withContext('getQuote called').toBe(true); }); // #docregion fake-async-test it('should show quote after getQuote (fakeAsync)', fakeAsync(() => { fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); tick(); // flush the observable to get the quote fixture.detectChanges(); // update view expect(quoteEl.textContent).withContext('should show quote').toBe(testQuote); expect(errorMessage()).withContext('should not show error').toBeNull(); })); // #enddocregion fake-async-test // #docregion async-test it('should show quote after getQuote (async)', async () => { fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); await fixture.whenStable(); // wait for async getQuote fixture.detectChanges(); // update view with quote expect(quoteEl.textContent).toBe(testQuote); expect(errorMessage()).withContext('should not show error').toBeNull(); }); // #enddocregion async-test it('should display error when TwainService fails', fakeAsync(() => { // tell spy to return an async error observable getQuoteSpy.and.returnValue(asyncError<string>('TwainService test failure')); fixture.detectChanges(); tick(); // component shows error after a setTimeout() fixture.detectChanges(); // update error message expect(errorMessage()) .withContext('should display error') .toMatch(/test failure/); expect(quoteEl.textContent).withContext('should show placeholder').toBe('...'); })); }); });
005124
import {Injectable, signal} from '@angular/core'; @Injectable({providedIn: 'root'}) export class UserService { isLoggedIn = signal(true); user = signal({name: 'Sam Spade'}); }
005137
// #docplaster import {HttpClient, HttpHandler, provideHttpClient} from '@angular/common/http'; import {HttpTestingController, provideHttpClientTesting} from '@angular/common/http/testing'; import {fakeAsync, TestBed, tick} from '@angular/core/testing'; import {provideRouter, Router} from '@angular/router'; import {RouterTestingHarness} from '@angular/router/testing'; import {asyncData, click} from '../../testing'; import {Hero} from '../model/hero'; import {sharedImports} from '../shared/shared'; import {HeroDetailComponent} from './hero-detail.component'; import {HeroDetailService} from './hero-detail.service'; import {HeroListComponent} from './hero-list.component'; ////// Testing Vars ////// let component: HeroDetailComponent; let harness: RouterTestingHarness; let page: Page; ////// Tests ////// describe('HeroDetailComponent', () => { describe('with HeroModule setup', heroModuleSetup); describe('when override its provided HeroDetailService', overrideSetup); describe('with FormsModule setup', formsModuleSetup); describe('with SharedModule setup', sharedModuleSetup); }); /////////////////// const testHero = getTestHeroes()[0]; function overrideSetup() { // #docregion hds-spy class HeroDetailServiceSpy { testHero: Hero = {...testHero}; /* emit cloned test hero */ getHero = jasmine .createSpy('getHero') .and.callFake(() => asyncData(Object.assign({}, this.testHero))); /* emit clone of test hero, with changes merged in */ saveHero = jasmine .createSpy('saveHero') .and.callFake((hero: Hero) => asyncData(Object.assign(this.testHero, hero))); } // #enddocregion hds-spy // #docregion setup-override beforeEach(async () => { await TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [HeroDetailComponent, HeroListComponent], providers: [ provideRouter([ {path: 'heroes', component: HeroListComponent}, {path: 'heroes/:id', component: HeroDetailComponent}, ]), HttpClient, HttpHandler, // HeroDetailService at this level is IRRELEVANT! {provide: HeroDetailService, useValue: {}}, ], }), ) // #docregion override-component-method .overrideComponent(HeroDetailComponent, { set: {providers: [{provide: HeroDetailService, useClass: HeroDetailServiceSpy}]}, }) // #enddocregion override-component-method .compileComponents(); }); // #enddocregion setup-override // #docregion override-tests let hdsSpy: HeroDetailServiceSpy; beforeEach(async () => { harness = await RouterTestingHarness.create(); component = await harness.navigateByUrl(`/heroes/${testHero.id}`, HeroDetailComponent); page = new Page(); // get the component's injected HeroDetailServiceSpy hdsSpy = harness.routeDebugElement!.injector.get(HeroDetailService) as any; harness.detectChanges(); }); it('should have called `getHero`', () => { expect(hdsSpy.getHero.calls.count()) .withContext('getHero called once') .toBe(1, 'getHero called once'); }); it("should display stub hero's name", () => { expect(page.nameDisplay.textContent).toBe(hdsSpy.testHero.name); }); it('should save stub hero change', fakeAsync(() => { const origName = hdsSpy.testHero.name; const newName = 'New Name'; page.nameInput.value = newName; page.nameInput.dispatchEvent(new Event('input')); // tell Angular expect(component.hero.name).withContext('component hero has new name').toBe(newName); expect(hdsSpy.testHero.name).withContext('service hero unchanged before save').toBe(origName); click(page.saveBtn); expect(hdsSpy.saveHero.calls.count()).withContext('saveHero called once').toBe(1); tick(); // wait for async save to complete expect(hdsSpy.testHero.name).withContext('service hero has new name after save').toBe(newName); expect(TestBed.inject(Router).url).toEqual('/heroes'); })); } // #enddocregion override-tests //////////////////// import {getTestHeroes} from '../model/testing/test-hero.service'; const firstHero = getTestHeroes()[0]; function heroModuleSetup() { // #docregion setup-hero-module beforeEach(async () => { await TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [HeroDetailComponent, HeroListComponent], providers: [ provideRouter([ {path: 'heroes/:id', component: HeroDetailComponent}, {path: 'heroes', component: HeroListComponent}, ]), provideHttpClient(), provideHttpClientTesting(), ], }), ).compileComponents(); }); // #enddocregion setup-hero-module // #docregion route-good-id describe('when navigate to existing hero', () => { let expectedHero: Hero; beforeEach(async () => { expectedHero = firstHero; await createComponent(expectedHero.id); }); // #docregion selected-tests it("should display that hero's name", () => { expect(page.nameDisplay.textContent).toBe(expectedHero.name); }); // #enddocregion route-good-id it('should navigate when click cancel', () => { click(page.cancelBtn); expect(TestBed.inject(Router).url).toEqual(`/heroes/${expectedHero.id}`); }); it('should save when click save but not navigate immediately', () => { click(page.saveBtn); expect(TestBed.inject(HttpTestingController).expectOne({method: 'PUT', url: 'api/heroes'})); expect(TestBed.inject(Router).url).toEqual('/heroes/41'); }); it('should navigate when click save and save resolves', fakeAsync(() => { click(page.saveBtn); tick(); // wait for async save to complete expect(TestBed.inject(Router).url).toEqual('/heroes/41'); })); // #docregion title-case-pipe it('should convert hero name to Title Case', async () => { harness.fixture.autoDetectChanges(); // get the name's input and display elements from the DOM const hostElement: HTMLElement = harness.routeNativeElement!; const nameInput: HTMLInputElement = hostElement.querySelector('input')!; const nameDisplay: HTMLElement = hostElement.querySelector('span')!; // simulate user entering a new name into the input box nameInput.value = 'quick BROWN fOx'; // Dispatch a DOM event so that Angular learns of input value change. nameInput.dispatchEvent(new Event('input')); // Wait for Angular to update the display binding through the title pipe await harness.fixture.whenStable(); expect(nameDisplay.textContent).toBe('Quick Brown Fox'); }); // #enddocregion selected-tests // #enddocregion title-case-pipe }); // #docregion route-bad-id describe('when navigate to non-existent hero id', () => { beforeEach(async () => { await createComponent(999); }); it('should try to navigate back to hero list', () => { expect(TestBed.inject(Router).url).toEqual('/heroes'); }); }); // #enddocregion route-bad-id } ///////////////////// import {FormsModule} from '@angular/forms'; import {TitleCasePipe} from '../shared/title-case.pipe'; import {appConfig} from '../app.config'; function formsModuleSetup() { // #docregion setup-forms-module beforeEach(async () => { await TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [FormsModule, HeroDetailComponent, TitleCasePipe], providers: [ provideHttpClient(), provideHttpClientTesting(), provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}]), ], }), ).compileComponents(); }); // #enddocregion setup-forms-module it("should display 1st hero's name", async () => { const expectedHero = firstHero; await createComponent(expectedHero.id).then(() => { expect(page.nameDisplay.textContent).toBe(expectedHero.name); }); }); } /////////////////////// function sharedModuleSetup() { // #docregion setup-shared-module beforeEach(async () => { await TestBed.configureTestingModule( Object.assign({}, appConfig, { imports: [HeroDetailComponent, sharedImports], providers: [ provideRouter([{path: 'heroes/:id', component: HeroDetailComponent}]), provideHttpClient(), provideHttpClientTesting(), ], }), ).compileComponents(); }); // #enddocregion setup-shared-module it("should display 1st hero's name", async () => { const expectedHero = firstHero; await createComponent(expectedHero.id).then(() => { expect(page.nameDisplay.textContent).toBe(expectedHero.name); }); }); } /////////// Helpers ///// /** Create the HeroDetailComponent, initialize it, set test variables */ // #docregion create-component
005157
// #docplaster import {APP_BASE_HREF} from '@angular/common'; import {CommonEngine} from '@angular/ssr/node'; import express from 'express'; import {fileURLToPath} from 'node:url'; import {dirname, join, resolve} from 'node:path'; import bootstrap from './src/main.server'; // The Express app is exported so that it can be used by serverless Functions. export function app(): express.Express { const server = express(); const serverDistFolder = dirname(fileURLToPath(import.meta.url)); const browserDistFolder = resolve(serverDistFolder, '../browser'); const indexHtml = join(serverDistFolder, 'index.server.html'); const commonEngine = new CommonEngine(); server.set('view engine', 'html'); server.set('views', browserDistFolder); // TODO: implement data requests securely // Serve data from URLS that begin "/api/" server.get('/api/**', (req, res) => { res.status(404).send('data requests are not yet supported'); }); // Serve static files from /browser server.get( '*.*', express.static(browserDistFolder, { maxAge: '1y', }), ); // All regular routes use the Angular engine server.get('*', (req, res, next) => { const {protocol, originalUrl, baseUrl, headers} = req; commonEngine .render({ bootstrap, documentFilePath: indexHtml, url: `${protocol}://${headers.host}${originalUrl}`, publicPath: browserDistFolder, providers: [{provide: APP_BASE_HREF, useValue: req.baseUrl}], }) .then((html) => res.send(html)) .catch((err) => next(err)); }); return server; } function run(): void { const port = process.env['PORT'] || 4000; // Start up the Node server const server = app(); server.listen(port, () => { console.log(`Node Express server listening on http://localhost:${port}`); }); } run();
005168
import {mergeApplicationConfig, ApplicationConfig} from '@angular/core'; import {provideServerRendering} from '@angular/platform-server'; import {appConfig} from './app.config'; const serverConfig: ApplicationConfig = { providers: [provideServerRendering()], }; export const config = mergeApplicationConfig(appConfig, serverConfig);
005171
import {Component} from '@angular/core'; import {RouterLink, RouterOutlet} from '@angular/router'; import {PLATFORM_ID, APP_ID, Inject} from '@angular/core'; import {isPlatformBrowser} from '@angular/common'; import {MessagesComponent} from './messages/messages.component'; @Component({ standalone: true, selector: 'app-root', templateUrl: './app.component.html', imports: [RouterLink, RouterOutlet, MessagesComponent], styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'Tour of Heroes'; constructor(@Inject(PLATFORM_ID) platformId: object, @Inject(APP_ID) appId: string) { const platform = isPlatformBrowser(platformId) ? 'in the browser' : 'on the server'; console.log(`Running ${platform} with appId=${appId}`); } }
005180
import {Component, OnInit} from '@angular/core'; import {NgFor} from '@angular/common'; import {RouterLink} from '@angular/router'; import {Hero} from '../hero'; import {HeroService} from '../hero.service'; @Component({ standalone: true, selector: 'app-heroes', templateUrl: './heroes.component.html', imports: [NgFor, RouterLink], styleUrls: ['./heroes.component.css'], }) export class HeroesComponent implements OnInit { heroes: Hero[] = []; constructor(private heroService: HeroService) {} ngOnInit() { this.getHeroes(); } getHeroes(): void { this.heroService.getHeroes().subscribe((heroes) => (this.heroes = heroes)); } add(name: string): void { name = name.trim(); if (!name) { return; } this.heroService.addHero({name} as Hero).subscribe((hero) => { this.heroes.push(hero); }); } delete(hero: Hero): void { this.heroes = this.heroes.filter((h) => h !== hero); this.heroService.deleteHero(hero).subscribe(); } }
005192
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <base href="/"> <title>Elements</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <app-root></app-root> </body> </html>
005209
<ul> <li *ngFor="let hero of heroes"> {{ hero.name }} </li> </ul>
005223
// #docregion import {Component} from '@angular/core'; // #docregion example /* avoid */ // UsersComponent is in an Admin feature @Component({ standalone: true, selector: 'users', template: '', }) export class UsersComponent {} // #enddocregion example
005224
// #docplaster // #docregion import {Component} from '@angular/core'; // #docregion example @Component({ // #enddocregion example template: '<div>users component</div>', // #docregion example standalone: true, selector: 'admin-users', }) export class UsersComponent {} // #enddocregion example
005294
import {Component} from '@angular/core'; import {HeroesComponent} from './heroes'; @Component({ standalone: true, selector: 'sg-app', template: '<toh-heroes></toh-heroes>', imports: [HeroesComponent], }) export class AppComponent {}
005297
<!-- #docregion --> <div> <h2>My Heroes</h2> <ul class="heroes"> @for (hero of heroes | async; track hero) { <li> <button type="button" (click)="selectedHero=hero"> <span class="badge">{{ hero.id }}</span> <span class="name">{{ hero.name }}</span> </button> </li> } </ul> @if (selectedHero) { <div> <h2>{{ selectedHero.name | uppercase }} is my hero</h2> </div> } </div>
005298
import {Component} from '@angular/core'; import {Observable} from 'rxjs'; import {Hero, HeroService} from './shared'; import {AsyncPipe, NgFor, NgIf, UpperCasePipe} from '@angular/common'; // #docregion example /* avoid */ @Component({ standalone: true, selector: 'toh-heroes', template: ` <div> <h2>My Heroes</h2> <ul class="heroes"> @for (hero of heroes | async; track hero) { <li (click)="selectedHero=hero"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> } </ul> @if (selectedHero) { <div> <h2>{{selectedHero.name | uppercase}} is my hero</h2> </div> } </div> `, styles: [ ` .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { cursor: pointer; position: relative; left: 0; background-color: #EEE; margin: .5em; padding: .3em 0; height: 1.6em; border-radius: 4px; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 0.8em 0.7em 0 0.7em; background-color: #607D8B; line-height: 1em; position: relative; left: -1px; top: -4px; height: 1.8em; margin-right: .8em; border-radius: 4px 0 0 4px; } `, ], imports: [NgFor, NgIf, AsyncPipe, UpperCasePipe], }) export class HeroesComponent { heroes: Observable<Hero[]>; selectedHero!: Hero; constructor(private heroService: HeroService) { this.heroes = this.heroService.getHeroes(); } } // #enddocregion example
005366
// #docregion /* avoid */ import {Component, OnInit} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs'; import {catchError, finalize} from 'rxjs/operators'; import {Hero} from '../shared/hero.model'; const heroesUrl = 'http://angular.io'; @Component({ standalone: true, selector: 'toh-hero-list', template: `...`, }) export class HeroListComponent implements OnInit { heroes: Hero[]; constructor(private http: HttpClient) { this.heroes = []; } getHeroes() { this.heroes = []; this.http .get(heroesUrl) .pipe( catchError(this.catchBadResponse), finalize(() => this.hideSpinner()), ) .subscribe((heroes: Hero[]) => (this.heroes = heroes)); } ngOnInit() { this.getHeroes(); } private catchBadResponse(err: any, source: Observable<any>) { // log and handle the exception return new Observable(); } private hideSpinner() { // hide the spinner } }
005368
// #docregion example import {Component, OnInit} from '@angular/core'; import {Hero, HeroService} from '../shared'; @Component({ standalone: true, selector: 'toh-hero-list', template: `...`, }) export class HeroListComponent implements OnInit { heroes: Hero[] = []; constructor(private heroService: HeroService) {} getHeroes() { this.heroes = []; this.heroService.getHeroes().subscribe((heroes) => (this.heroes = heroes)); } ngOnInit() { this.getHeroes(); } } // #enddocregion example
005373
// #docregion /* avoid */ import {Component, NgModule, OnInit} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; interface Hero { id: number; name: string; } @Component({ selector: 'app-root', template: ` <h1>{{title}}</h1> <pre>{{heroes | json}}</pre> `, styleUrls: ['../app.component.css'], standalone: false, }) export class AppComponent implements OnInit { title = 'Tour of Heroes'; heroes: Hero[] = []; ngOnInit() { getHeroes().then((heroes) => (this.heroes = heroes)); } } @NgModule({ imports: [BrowserModule], declarations: [AppComponent], exports: [AppComponent], bootstrap: [AppComponent], }) export class AppModule {} platformBrowserDynamic().bootstrapModule(AppModule); const HEROES: Hero[] = [ {id: 1, name: 'Bombasto'}, {id: 2, name: 'Tornado'}, {id: 3, name: 'Magneta'}, ]; function getHeroes(): Promise<Hero[]> { return Promise.resolve(HEROES); // TODO: get hero data from the server; }
005403
<!-- #docplaster --> <!-- #docregion --> <h1>Structural Directives</h1> <p>Conditional display of hero</p> <blockquote> <!-- #docregion asterisk --> <div *ngIf="hero" class="name">{{hero.name}}</div> <!-- #enddocregion asterisk --> </blockquote> <p>List of heroes</p> <ul> <li *ngFor="let hero of heroes">{{hero.name}}</li> </ul> <hr> <h2 id="ngIf">NgIf</h2> <p *ngIf="true"> Expression is true and ngIf is true. This paragraph is in the DOM. </p> <p *ngIf="false"> Expression is false and ngIf is false. This paragraph is not in the DOM. </p> <p [style.display]="'block'"> Expression sets display to "block". This paragraph is visible. </p> <p [style.display]="'none'"> Expression sets display to "none". This paragraph is hidden but still in the DOM. </p> <h4>NgIf with template</h4> <p>&lt;ng-template&gt; element</p> <!-- #docregion ngif-template --> <ng-template [ngIf]="hero"> <div class="name">{{hero.name}}</div> </ng-template> <!-- #enddocregion ngif-template --> <hr> <h2 id="ng-container">&lt;ng-container&gt;</h2> <h4>*ngIf with a &lt;ng-container&gt;</h4> <button type="button" (click)="hero = hero ? null : heroes[0]">Toggle hero</button> <!-- #docregion ngif-ngcontainer --> <p> I turned the corner <ng-container *ngIf="hero"> and saw {{hero.name}}. I waved </ng-container> and continued on my way. </p> <!-- #enddocregion ngif-ngcontainer --> <p> I turned the corner <span *ngIf="hero"> and saw {{hero.name}}. I waved </span> and continued on my way. </p> <p><em>&lt;select&gt; with &lt;span&gt;</em></p> <div> Pick your favorite hero (<label for="show-sad"><input id="show-sad" type="checkbox" checked (change)="showSad = !showSad">show sad</label>) </div> <select [(ngModel)]="hero"> <span *ngFor="let h of heroes"> <span *ngIf="showSad || h.emotion !== 'sad'"> <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option> </span> </span> </select> <p><em>&lt;select&gt; with &lt;ng-container&gt;</em></p> <!-- #docregion select-ngcontainer --> <div> Pick your favorite hero (<label for="showSad"><input id="showSad" type="checkbox" checked (change)="showSad = !showSad">show sad</label>) </div> <select [(ngModel)]="hero"> <ng-container *ngFor="let h of heroes"> <ng-container *ngIf="showSad || h.emotion !== 'sad'"> <option [ngValue]="h">{{h.name}} ({{h.emotion}})</option> </ng-container> </ng-container> </select> <!-- #enddocregion select-ngcontainer --> <br><br> <hr> <h2 id="ngFor">NgFor</h2> <div class="box"> <p class="code">&lt;div *ngFor="let hero of heroes; let i=index; let odd=odd; trackBy: trackById" [class.odd]="odd"&gt;</p> <!--#docregion inside-ngfor --> <div *ngFor="let hero of heroes; let i=index; let odd=odd; trackBy: trackById" [class.odd]="odd"> ({{i}}) {{hero.name}} </div> <!--#enddocregion inside-ngfor --> <p class="code">&lt;ng-template ngFor let-hero [ngForOf]="heroes" let-i="index" let-odd="odd" [ngForTrackBy]="trackById"/&gt;</p> <!--#docregion inside-ngfor --> <ng-template ngFor let-hero [ngForOf]="heroes" let-i="index" let-odd="odd" [ngForTrackBy]="trackById"> <div [class.odd]="odd"> ({{i}}) {{hero.name}} </div> </ng-template> <!--#enddocregion inside-ngfor --> </div> <hr> <h2 id="ngSwitch">NgSwitch</h2> <div>Pick your favorite hero</div> <p> <label for="hero-{{h}}" *ngFor="let h of heroes"> <input id="hero-{{h}}" type="radio" name="heroes" [(ngModel)]="hero" [value]="h">{{h.name}} </label> <label for="none-of-the-above"><input id="none-of-the-above" type="radio" name="heroes" (click)="hero = null">None of the above</label> </p> <h4>NgSwitch</h4> <div [ngSwitch]="hero?.emotion"> <app-happy-hero *ngSwitchCase="'happy'" [hero]="hero!"></app-happy-hero> <app-sad-hero *ngSwitchCase="'sad'" [hero]="hero!"></app-sad-hero> <app-confused-hero *ngSwitchCase="'confused'" [hero]="hero!"></app-confused-hero> <app-unknown-hero *ngSwitchDefault [hero]="hero!"></app-unknown-hero> </div> <h4>NgSwitch with &lt;ng-template&gt;</h4> <div [ngSwitch]="hero?.emotion"> <ng-template ngSwitchCase="happy"> <app-happy-hero [hero]="hero!"></app-happy-hero> </ng-template> <ng-template ngSwitchCase="sad"> <app-sad-hero [hero]="hero!"></app-sad-hero> </ng-template> <ng-template ngSwitchCase="confused"> <app-confused-hero [hero]="hero!"></app-confused-hero> </ng-template > <ng-template ngSwitchDefault> <app-unknown-hero [hero]="hero!"></app-unknown-hero> </ng-template> </div> <hr> <h2 id="appUnless">UnlessDirective</h2> <!-- #docregion toggle-info --> <p> The condition is currently <span [ngClass]="{ 'a': !condition, 'b': condition, 'unless': true }">{{condition}}</span>. <button type="button" (click)="condition = !condition" [ngClass] = "{ 'a': condition, 'b': !condition }" > Toggle condition to {{condition ? 'false' : 'true'}} </button> </p> <!-- #enddocregion toggle-info --> <!-- #docregion appUnless--> <p *appUnless="condition" class="unless a"> (A) This paragraph is displayed because the condition is false. </p> <p *appUnless="!condition" class="unless b"> (B) Although the condition is true, this paragraph is displayed because appUnless is set to false. </p> <!-- #enddocregion appUnless--> <h4>UnlessDirective with template</h4> <!-- #docregion appUnless-1 --> <p *appUnless="condition">Show this sentence unless the condition is true.</p> <!-- #enddocregion appUnless-1 --> <p *appUnless="condition" class="code unless"> (A) &lt;p *appUnless="condition" class="code unless"&gt; </p> <ng-template [appUnless]="condition"> <p class="code unless"> (A) &lt;ng-template [appUnless]="condition"&gt; </p> </ng-template> <hr /> <h2 id="appIfLoaded">IfLoadedDirective</h2> <app-hero></app-hero> <hr /> <h2 id="appTrigonometry">TrigonometryDirective</h2> <!-- #docregion appTrigonometry --> <ul *appTrigonometry="30; sin as s; cos as c; tan as t"> <li>sin(30°): {{ s }}</li> <li>cos(30°): {{ c }}</li> <li>tan(30°): {{ t }}</li> </ul> <!-- #enddocregion appTrigonometry -->
005478
import {Component} from '@angular/core'; import {ChildComponent} from './child.component'; @Component({ standalone: true, selector: 'app-parent', imports: [ChildComponent], template: '<app-child/>', }) export class ParentComponent {}
005510
<h1>Built-in Directives</h1> <h2>Built-in attribute directives</h2> <h3 id="ngModel">NgModel (two-way) Binding</h3> <fieldset><h4>NgModel examples</h4> <p>Current item name: {{ currentItem.name }}</p> <p> <label for="without">without NgModel:</label> <input [value]="currentItem.name" (input)="currentItem.name=getValue($event)" id="without"> </p> <p> <!-- #docregion NgModel-1 --> <label for="example-ngModel">[(ngModel)]:</label> <input [(ngModel)]="currentItem.name" id="example-ngModel"> <!-- #enddocregion NgModel-1 --> </p> <p> <label for="example-change">(ngModelChange)="...name=$event":</label> <input [ngModel]="currentItem.name" (ngModelChange)="currentItem.name=$event" id="example-change"> </p> <p> <label for="example-uppercase">(ngModelChange)="setUppercaseName($event)" <!-- #docregion uppercase --> <input [ngModel]="currentItem.name" (ngModelChange)="setUppercaseName($event)" id="example-uppercase"> <!-- #enddocregion uppercase --> </label> </p> </fieldset> <hr><h2 id="ngClass">NgClass Binding</h2> <p>currentClasses is {{ currentClasses | json }}</p> <!-- #docregion NgClass-1 --> <div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special.</div> <!-- #enddocregion NgClass-1 --> <ul> <li> <label for="saveable">saveable</label> <input type="checkbox" [(ngModel)]="canSave" id="saveable"> </li> <li> <label for="modified">modified:</label> <input type="checkbox" [value]="!isUnchanged" (change)="isUnchanged=!isUnchanged" id="modified"></li> <li> <label for="special">special: <input type="checkbox" [(ngModel)]="isSpecial" id="special"></label> </li> </ul> <button type="button" (click)="setCurrentClasses()">Refresh currentClasses</button> <div [ngClass]="currentClasses"> This div should be {{ canSave ? "": "not"}} saveable, {{ isUnchanged ? "unchanged" : "modified" }} and {{ isSpecial ? "": "not"}} special after clicking "Refresh".</div> <br><br> <!-- #docregion special-div --> <!-- toggle the "special" class on/off with a property --> <div [ngClass]="isSpecial ? 'special' : ''">This div is special</div> <!-- #enddocregion special-div --> <div class="helpful study course">Helpful study course</div> <div [ngClass]="{'helpful':false, 'study':true, 'course':true}">Study course</div> <!-- NgStyle binding --> <hr><h3>NgStyle Binding</h3> <div [style.font-size]="isSpecial ? 'x-large' : 'smaller'"> This div is x-large or smaller. </div> <h4>[ngStyle] binding to currentStyles - CSS property names</h4> <p>currentStyles is {{ currentStyles | json }}</p> <!-- #docregion NgStyle-2 --> <div [ngStyle]="currentStyles"> This div is initially italic, normal weight, and extra large (24px). </div> <!-- #enddocregion NgStyle-2 --> <br> <label for="canSave">italic: <input id="canSave" type="checkbox" [(ngModel)]="canSave"></label> | <label for="isUnchanged">normal: <input id="isUnchanged" type="checkbox" [(ngModel)]="isUnchanged"></label> | <label for="isSpecial">xlarge: <input id="isSpecial" type="checkbox" [(ngModel)]="isSpecial"></label> <button type="button" (click)="setCurrentStyles()">Refresh currentStyles</button> <br><br> <div [ngStyle]="currentStyles"> This div should be {{ canSave ? "italic": "plain"}}, {{ isUnchanged ? "normal weight" : "bold" }} and, {{ isSpecial ? "extra large": "normal size"}} after clicking "Refresh".</div> <hr> <h2>Built-in structural directives</h2> <h3 id="ngIf">NgIf Binding</h3> <div> <p>If isActive is true, app-item-detail will render: </p> <!-- #docregion NgIf-1 --> <app-item-detail *ngIf="isActive" [item]="item"></app-item-detail> <!-- #enddocregion NgIf-1 --> <button type="button" (click)="isActiveToggle()">Toggle app-item-detail</button> </div> <p>If currentCustomer isn't null, say hello to Laura:</p> <!-- #docregion NgIf-2 --> <div *ngIf="currentCustomer">Hello, {{ currentCustomer.name }}</div> <!-- #enddocregion NgIf-2 --> <p>nullCustomer is null by default. NgIf guards against null. Give it a value to show it:</p> <!-- #docregion NgIf-2b --> <div *ngIf="nullCustomer">Hello, <span>{{ nullCustomer }}</span></div> <!-- #enddocregion NgIf-2b --> <button type="button" (click)="giveNullCustomerValue()">Give nullCustomer a value</button> <h4>NgIf binding with template (no *)</h4> <ng-template [ngIf]="currentItem">Add {{ currentItem.name }} with template</ng-template> <hr> <h4>Show/hide vs. NgIf</h4> <!-- isSpecial is true --> <div [class.hidden]="!isSpecial">Show with class</div> <div [class.hidden]="isSpecial">Hide with class</div> <p>ItemDetail is in the DOM but hidden</p> <app-item-detail [class.hidden]="isSpecial"></app-item-detail> <div [style.display]="isSpecial ? 'block' : 'none'">Show with style</div> <div [style.display]="isSpecial ? 'none' : 'block'">Hide with style</div> <hr> <h2 id="ngFor">NgFor Binding</h2> <div class="box"> <!-- #docregion NgFor-1, NgFor-1-2 --> <div *ngFor="let item of items">{{ item.name }}</div> <!-- #enddocregion NgFor-1, NgFor-1-2 --> </div> <p>*ngFor with ItemDetailComponent element</p> <div class="box"> <!-- #docregion NgFor-2, NgFor-1-2 --> <app-item-detail *ngFor="let item of items" [item]="item"></app-item-detail> <!-- #enddocregion NgFor-2, NgFor-1-2 --> </div> <h4 id="ngFor-index">*ngFor with index</h4> <p>with <em>semi-colon</em> separator</p> <div class="box"> <!-- #docregion NgFor-3 --> <div *ngFor="let item of items; let i=index">{{ i + 1 }} - {{ item.name }}</div> <!-- #enddocregion NgFor-3 --> </div> <p>with <em>comma</em> separator</p> <div class="box"> <div *ngFor="let item of items, let i=index">{{ i + 1 }} - {{ item.name }}</div> </div> <h4 id="ngFor-trackBy">*ngFor trackBy</h4> <button type="button" (click)="resetList()">Reset items</button> <button type="button" (click)="changeIds()">Change ids</button> <button type="button" (click)="clearTrackByCounts()">Clear counts</button> <p><em>without</em> trackBy</p> <div class="box"> <div #noTrackBy *ngFor="let item of items">({{ item.id }}) {{ item.name }}</div> <div id="noTrackByCnt" *ngIf="itemsNoTrackByCount" > Item DOM elements change #{{ itemsNoTrackByCount }} without trackBy </div> </div> <p>with trackBy</p> <div class="box"> <div #withTrackBy *ngFor="let item of items; trackBy: trackByItems">({{ item.id }}) {{ item.name }}</div> <div id="withTrackByCnt" *ngIf="itemsWithTrackByCount"> Item DOM elements change #{{ itemsWithTrackByCount }} with trackBy </div> </div> <br><br><br>
005511
<p>with trackBy and <em>semi-colon</em> separator</p> <div class="box"> <!-- #docregion trackBy --> <div *ngFor="let item of items; trackBy: trackByItems"> ({{ item.id }}) {{ item.name }} </div> <!-- #enddocregion trackBy --> </div> <p>with trackBy and <em>comma</em> separator</p> <div class="box"> <div *ngFor="let item of items, trackBy: trackByItems">({{ item.id }}) {{ item.name }}</div> </div> <p>with trackBy and <em>space</em> separator</p> <div class="box"> <div *ngFor="let item of items trackBy: trackByItems">({{ item.id }}) {{ item.name }}</div> </div> <p>with <em>generic</em> trackById function</p> <div class="box"> <div *ngFor="let item of items, trackBy: trackById">({{ item.id }}) {{ item.name }}</div> </div> <hr><h2>NgSwitch Binding</h2> <p>Pick your favorite item</p> <div> <label for="item-{{i}}" *ngFor="let i of items"> <div><input id="item-{{i}}"type="radio" name="items" [(ngModel)]="currentItem" [value]="i">{{ i.name }} </div> </label> </div> <!-- #docregion NgSwitch --> <div [ngSwitch]="currentItem.feature"> <app-stout-item *ngSwitchCase="'stout'" [item]="currentItem"></app-stout-item> <app-device-item *ngSwitchCase="'slim'" [item]="currentItem"></app-device-item> <app-lost-item *ngSwitchCase="'vintage'" [item]="currentItem"></app-lost-item> <app-best-item *ngSwitchCase="'bright'" [item]="currentItem"></app-best-item> <!-- #enddocregion NgSwitch --> <!-- #docregion NgSwitch-div --> <div *ngSwitchCase="'bright'">Are you as bright as {{ currentItem.name }}?</div> <!-- #enddocregion NgSwitch-div --> <!-- #docregion NgSwitch --> <app-unknown-item *ngSwitchDefault [item]="currentItem"></app-unknown-item> </div> <!-- #enddocregion NgSwitch -->
005523
// #docregion import {Component} from '@angular/core'; import {CarComponent} from './car/car.component'; import {HeroesComponent} from './heroes/heroes.component'; @Component({ standalone: true, selector: 'app-root', template: ` <h1>{{title}}</h1> <app-car></app-car> <app-heroes></app-heroes> `, imports: [CarComponent, HeroesComponent], }) export class AppComponent { title = 'Dependency Injection'; }
005527
import {Component, Inject} from '@angular/core'; import {APP_CONFIG, AppConfig} from './injection.config'; import {UserService} from './user.service'; import {HeroesComponent} from './heroes/heroes.component'; import {HeroesTspComponent} from './heroes/heroes-tsp.component'; import {ProvidersComponent} from './providers.component'; import {CarComponent} from './car/car.component'; import {InjectorComponent} from './injector.component'; import {TestComponent} from './test.component'; import {NgIf} from '@angular/common'; @Component({ standalone: true, selector: 'app-root', template: ` <h1>{{title}}</h1> <app-car></app-car> <app-injectors></app-injectors> <app-tests></app-tests> <h2>User</h2> <p id="user"> {{userInfo}} <button type="button" (click)="nextUser()">Next User</button> <p> @if (isAuthorized) { <app-heroes id="authorized"></app-heroes> } @if (!isAuthorized) { <app-heroes id="unauthorized"></app-heroes> } @if (isAuthorized) { <app-heroes-tsp id="tspAuthorized"></app-heroes-tsp> } <app-providers></app-providers> `, imports: [ HeroesComponent, HeroesTspComponent, ProvidersComponent, CarComponent, InjectorComponent, TestComponent, NgIf, ], }) export class AppComponent { title: string; constructor( @Inject(APP_CONFIG) config: AppConfig, private userService: UserService, ) { this.title = config.title; } get isAuthorized() { return this.user.isAuthorized; } nextUser() { this.userService.getNewUser(); } get user() { return this.userService.user; } get userInfo() { return ( `Current user, ${this.user.name}, is ` + `${this.isAuthorized ? '' : 'not'} authorized. ` ); } }
005530
import {ApplicationConfig} from '@angular/core'; import {Logger} from './logger.service'; import {UserService} from './user.service'; import {APP_CONFIG, HERO_DI_CONFIG} from './injection.config'; import {provideProtractorTestingSupport} from '@angular/platform-browser'; const appConfig: ApplicationConfig = { providers: [ provideProtractorTestingSupport(), Logger, UserService, {provide: APP_CONFIG, useValue: HERO_DI_CONFIG}, ], }; export default appConfig;
005531
import {Component, Inject} from '@angular/core'; import {APP_CONFIG, AppConfig} from './injection.config'; import {CarComponent} from './car/car.component'; import {HeroesComponent} from './heroes/heroes.component'; @Component({ standalone: true, selector: 'app-root', template: ` <h1>{{title}}</h1> <app-car></app-car> <app-heroes></app-heroes> `, imports: [CarComponent, HeroesComponent], }) export class AppComponent { title: string; // #docregion ctor constructor(@Inject(APP_CONFIG) config: AppConfig) { this.title = config.title; } // #enddocregion ctor }
005553
// #docregion import {EnvironmentInjector, inject, Injectable, runInInjectionContext} from '@angular/core'; @Injectable({providedIn: 'root'}) export class SomeService {} // #docregion run-in-context @Injectable({ providedIn: 'root', }) export class HeroService { private environmentInjector = inject(EnvironmentInjector); someMethod() { runInInjectionContext(this.environmentInjector, () => { inject(SomeService); // Do what you need with the injected service }); } } // #enddocregion run-in-context
005556
import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {RouterModule} from '@angular/router'; import {ServiceModule} from './service-and-module'; // #docregion @NgModule({ imports: [BrowserModule, RouterModule.forRoot([]), ServiceModule], }) export class AppModule {}
005558
import {Injectable} from '@angular/core'; // #docregion @Injectable({ providedIn: 'root', }) export class Service {}
005559
// #docregion import {Injectable, NgModule} from '@angular/core'; @Injectable() export class Service { doSomething(): void {} } @NgModule({ providers: [Service], }) export class ServiceModule {}
005572
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Animations</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <app-root></app-root> </body> </html>
005602
import {ApplicationConfig} from '@angular/core'; import {routes} from './app.routes'; import {provideRouter} from '@angular/router'; import {provideProtractorTestingSupport} from '@angular/platform-browser'; import {provideAnimations} from '@angular/platform-browser/animations'; export const appConfig: ApplicationConfig = { providers: [ // needed for supporting e2e tests provideProtractorTestingSupport(), provideRouter(routes), provideAnimations(), ], };
005613
import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule], declarations: [], bootstrap: [], }) export class AppModule {}
005695
// #docplaster import {NgModule} from '@angular/core'; import {Routes, RouterModule} from '@angular/router'; // CLI imports router // #docregion child-routes const routes: Routes = [ { path: 'first-component', component: FirstComponent, // this is the component with the <router-outlet> in the template children: [ { path: 'child-a', // child route path component: ChildAComponent, // child route component that the router renders }, { path: 'child-b', component: ChildBComponent, // another child route component that the router renders }, ], }, ]; // #enddocregion child-routes @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
005702
// #docplaster // #docregion import {inject} from '@angular/core'; import {Router, NavigationExtras} from '@angular/router'; import {AuthService} from './auth.service'; export const authGuard = () => { const authService = inject(AuthService); const router = inject(Router); if (authService.isLoggedIn) { return true; } // Create a dummy session id const sessionId = 123456789; // Set our navigation extras object // that contains our global query params and fragment const navigationExtras: NavigationExtras = { queryParams: {session_id: sessionId}, fragment: 'anchor', }; // Redirect to the login page with extras return router.createUrlTree(['/login'], navigationExtras); };
005705
// #docplaster import {inject} from '@angular/core'; import {Router, NavigationExtras} from '@angular/router'; import {AuthService} from './auth.service'; export const authGuard = () => { const router = inject(Router); const authService = inject(AuthService); if (authService.isLoggedIn) { return true; } // Create a dummy session id const sessionId = 123456789; // Set our navigation extras object // that contains our global query params and fragment const navigationExtras: NavigationExtras = { queryParams: {session_id: sessionId}, fragment: 'anchor', }; // Navigate to the login page with extras return router.createUrlTree(['/login'], navigationExtras); };
005708
// #docregion import {inject} from '@angular/core'; import {Router} from '@angular/router'; import {AuthService} from './auth.service'; export const authGuard = () => { const authService = inject(AuthService); const router = inject(Router); if (authService.isLoggedIn) { return true; } // Redirect to the login page return router.parseUrl('/login'); }; // #enddocregion
005709
import {inject} from '@angular/core'; import {Router} from '@angular/router'; import {AuthService} from './auth.service'; export const authGuard = () => { const authService = inject(AuthService); const router = inject(Router); if (authService.isLoggedIn) { return true; } // Redirect to the login page return router.parseUrl('/login'); };
005783
import {Component} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {bootstrapApplication} from '@angular/platform-browser'; @Component({ selector: 'app-root', standalone: true, template: ` <label for="name">Name:</label> <input type="text" id="name" [(ngModel)]="name" placeholder="Enter a name here" /> <hr /> <h1>Hello {{ name }}!</h1> `, imports: [FormsModule], }) export class DemoComponent { name = ''; } bootstrapApplication(DemoComponent);
005798
# Create Home component This tutorial lesson demonstrates how to create a new [component](guide/components) for your Angular app. <docs-video src="https://www.youtube.com/embed/R0nRX8jD2D0?si=OMVaw71EIa44yIOJ"/> ## What you'll learn Your app has a new component: `HomeComponent`. ## Conceptual preview of Angular components Angular apps are built around components, which are Angular's building blocks. Components contain the code, HTML layout, and CSS style information that provide the function and appearance of an element in the app. In Angular, components can contain other components. An app's functions and appearance can be divided and partitioned into components. In Angular, components have metadata that define its properties. When you create your `HomeComponent`, you use these properties: * `selector`: to describe how Angular refers to the component in templates. * `standalone`: to describe whether the component requires a `NgModule`. * `imports`: to describe the component's dependencies. * `template`: to describe the component's HTML markup and layout. * `styleUrls`: to list the URLs of the CSS files that the component uses in an array. <docs-pill-row> <docs-pill href="api/core/Component" title="Learn more about Components"/> </docs-pill-row> <docs-workflow> <docs-step title="Create the `HomeComponent`"> In this step, you create a new component for your app. In the **Terminal** pane of your IDE: 1. In your project directory, navigate to the `first-app` directory. 1. Run this command to create a new `HomeComponent` <docs-code language="shell"> ng generate component home </docs-code> 1. Run this command to build and serve your app. Note: This step is only for your local environment! <docs-code language="shell"> ng serve </docs-code> 1. Open a browser and navigate to `http://localhost:4200` to find the application. 1. Confirm that the app builds without error. HELPFUL: It should render the same as it did in the previous lesson because even though you added a new component, you haven't included it in any of the app's templates, yet. 1. Leave `ng serve` running as you complete the next steps. </docs-step> <docs-step title="Add the new component to your app's layout"> In this step, you add the new component, `HomeComponent` to your app's root component, `AppComponent`, so that it displays in your app's layout. In the **Edit** pane of your IDE: 1. Open `app.component.ts` in the editor. 1. In `app.component.ts`, import `HomeComponent` by adding this line to the file level imports. <docs-code header="Import HomeComponent in src/app/app.component.ts" path="adev/src/content/tutorials/first-app/steps/03-HousingLocation/src/app/app.component.ts" visibleLines="[2]"/> 1. In `app.component.ts`, in `@Component`, update the `imports` array property and add `HomeComponent`. <docs-code header="Replace in src/app/app.component.ts" path="adev/src/content/tutorials/first-app/steps/03-HousingLocation/src/app/app.component.ts" visibleLines="[7]"/> 1. In `app.component.ts`, in `@Component`, update the `template` property to include the following HTML code. <docs-code header="Replace in src/app/app.component.ts" path="adev/src/content/tutorials/first-app/steps/03-HousingLocation/src/app/app.component.ts" visibleLines="[8,17]"/> 1. Save your changes to `app.component.ts`. 1. If `ng serve` is running, the app should update. If `ng serve` is not running, start it again. *Hello world* in your app should change to *home works!* from the `HomeComponent`. 1. Check the running app in the browser and confirm that the app has been updated. <img alt="browser frame of page displaying the text 'home works!'" src="assets/images/tutorials/first-app/homes-app-lesson-02-step-2.png"> </docs-step> <docs-step title="Add features to `HomeComponent`"> In this step you add features to `HomeComponent`. In the previous step, you added the default `HomeComponent` to your app's template so its default HTML appeared in the app. In this step, you add a search filter and button that is used in a later lesson. For now, that's all that `HomeComponent` has. Note that, this step just adds the search elements to the layout without any functionality, yet. In the **Edit** pane of your IDE: 1. In the `first-app` directory, open `home.component.ts` in the editor. 1. In `home.component.ts`, in `@Component`, update the `template` property with this code. <docs-code header="Replace in src/app/home/home.component.ts" path="adev/src/content/tutorials/first-app/steps/03-HousingLocation/src/app/home/home.component.ts" visibleLines="[8,15]"/> 1. Next, open `home.component.css` in the editor and update the content with these styles. Note: In the browser, these can go in `src/app/home/home.component.ts` in the `styles` array. <docs-code header="Replace in src/app/home/home.component.css" path="adev/src/content/tutorials/first-app/steps/03-HousingLocation/src/app/home/home.component.css"/> 1. Confirm that the app builds without error. You should find the filter query box and button in your app and they should be styled. Correct any errors before you continue to the next step. <img alt="browser frame of homes-app displaying logo, filter text input box and search button" src="assets/images/tutorials/first-app/homes-app-lesson-02-step-3.png"> </docs-step> </docs-workflow> Summary: In this lesson, you created a new component for your app and gave it a filter edit control and button. For more information about the topics covered in this lesson, visit: <docs-pill-row> <docs-pill href="cli/generate/component" title="`ng generate component`"/> <docs-pill href="api/core/Component" title="`Component` reference"/> <docs-pill href="guide/components" title="Angular components overview"/> </docs-pill-row>
005831
import {Component} from '@angular/core'; import {CommonModule} from '@angular/common'; @Component({ selector: 'app-home', standalone: true, imports: [CommonModule], template: ` <section> <form> <input type="text" placeholder="Filter by city" /> <button class="primary" type="button">Search</button> </form> </section> `, styleUrls: ['./home.component.css'], }) export class HomeComponent {}
005847
import {Component} from '@angular/core'; import {CommonModule} from '@angular/common'; @Component({ selector: 'app-housing-location', standalone: true, imports: [CommonModule], template: ` <p>housing-location works!</p> `, styleUrls: ['./housing-location.component.css'], }) export class HousingLocationComponent {}
005853
# Add a property binding to a component’s template This tutorial lesson demonstrates how to add property binding to a template and use it to pass dynamic data to components. <docs-video src="https://www.youtube.com/embed/eM3zi_n7lNs?si=AsiczpWnMz5HhJqB&amp;start=599"/> ## What you'll learn * Your app has data bindings in the `HomeComponent` template. * Your app sends data from the `HomeComponent` to the `HousingLocationComponent`. ## Conceptual preview of Inputs In this lesson, you'll continue the process of sharing data from the parent component to the child component by binding data to those properties in the template using property binding. Property binding enables you to connect a variable to an `Input` in an Angular template. The data is then dynamically bound to the `Input`. For a more in depth explanation, please refer to the [Property binding](guide/templates/property-binding) guide. <docs-workflow> <docs-step title="Update the `HomeComponent` template"> This step adds property binding to the `<app-housing-location>` tag. In the code editor: 1. Navigate to `src/app/home/home.component.ts` 1. In the template property of the `@Component` decorator, update the code to match the code below: <docs-code header="Add housingLocation property binding" path="adev/src/content/tutorials/first-app/steps/07-dynamic-template-values/src/app/home/home.component.ts" visibleLines="[17,19]"/> When adding a property binding to a component tag, we use the `[attribute] = "value"` syntax to notify Angular that the assigned value should be treated as a property from the component class and not a string value. The value on the right-hand side is the name of the property from the `HomeComponent`. </docs-step> <docs-step title="Confirm the code still works"> 1. Save your changes and confirm the app does not have any errors. 1. Correct any errors before you continue to the next step. </docs-step> </docs-workflow> Summary: In this lesson, you added a new property binding and passed in a reference to a class property. Now, the `HousingLocationComponent` has access to data that it can use to customize the component's display. For more information about the topics covered in this lesson, visit: <docs-pill-row> <docs-pill href="guide/templates/property-binding" title="Property binding"/> </docs-pill-row>
005876
import {Component} from '@angular/core'; import {HomeComponent} from './home/home.component'; import {RouterLink, RouterOutlet} from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [HomeComponent, RouterLink, RouterOutlet], template: ` <main> <a [routerLink]="['/']"> <header class="brand-name"> <img class="brand-logo" src="/assets/logo.svg" alt="logo" aria-hidden="true" /> </header> </a> <section class="content"> <router-outlet></router-outlet> </section> </main> `, styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'homes'; }
005896
import {Component} from '@angular/core'; import {HomeComponent} from './home/home.component'; import {RouterLink, RouterOutlet} from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [HomeComponent, RouterLink, RouterOutlet], template: ` <main> <a [routerLink]="['/']"> <header class="brand-name"> <img class="brand-logo" src="/assets/logo.svg" alt="logo" aria-hidden="true" /> </header> </a> <section class="content"> <router-outlet></router-outlet> </section> </main> `, styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'homes'; }
005909
# Add routes to the application This tutorial lesson demonstrates how to add routes to your app. <docs-video src="https://www.youtube.com/embed/r5DEBMuStPw?si=H6Bx6nLJoMLaMxkx" /> IMPORTANT: We recommend using your local environment to learn routing. ## What you'll learn At the end of this lesson your application will have support for routing. ## Conceptual preview of routing This tutorial introduces routing in Angular. Routing is the ability to navigate from one component in the application to another. In [Single Page Applications (SPA)](guide/routing), only parts of the page are updated to represent the requested view for the user. The [Angular Router](guide/routing) enables users to declare routes and specify which component should be displayed on the screen if that route is requested by the application. In this lesson, you will enable routing in your application to navigate to the details page. <docs-workflow> <docs-step title="Create a default details component "> 1. From the terminal, enter the following command to create the `DetailsComponent`: <docs-code language="shell"> ng generate component details </docs-code> This component will represent the details page that provides more information on a given housing location. </docs-step> <docs-step title="Add routing to the application"> 1. In the `src/app` directory, create a file called `routes.ts`. This file is where we will define the routes in the application. 1. In `main.ts`, make the following updates to enable routing in the application: 1. Import the routes file and the `provideRouter` function: <docs-code header="Import routing details in src/main.ts" path="adev/src/content/tutorials/first-app/steps/11-details-page/src/main.ts" visibleLines="[7,8]"/> 1. Update the call to `bootstrapApplication` to include the routing configuration: <docs-code header="Add router configuration in src/main.ts" path="adev/src/content/tutorials/first-app/steps/11-details-page/src/main.ts" visibleLines="[10,17]"/> 1. In `src/app/app.component.ts`, update the component to use routing: 1. Add a file level import for `RoutingModule`: <docs-code header="Import RouterModule in src/app/app.component.ts" path="adev/src/content/tutorials/first-app/steps/11-details-page/src/app/app.component.ts" visibleLines="[3]"/> 1. Add `RouterModule` to the `@Component` metadata imports <docs-code header="Import RouterModule in src/app/app.component.ts" path="adev/src/content/tutorials/first-app/steps/11-details-page/src/app/app.component.ts" visibleLines="[7]"/> 1. In the `template` property, replace the `<app-home></app-home>` tag with the `<router-outlet>` directive and add a link back to the home page. Your code should match this code: <docs-code header="Add router-outlet in src/app/app.component.ts" path="adev/src/content/tutorials/first-app/steps/11-details-page/src/app/app.component.ts" visibleLines="[8,18]"/> </docs-step> <docs-step title="Add route to new component"> In the previous step you removed the reference to the `<app-home>` component in the template. In this step, you will add a new route to that component. 1. In `routes.ts`, perform the following updates to create a route. 1. Add a file level imports for the `HomeComponent`, `DetailsComponent` and the `Routes` type that you'll use in the route definitions. <docs-code header="Import components and Routes" path="adev/src/content/tutorials/first-app/steps/11-details-page/src/app/routes.ts" visibleLines="[1,3]"/> 1. Define a variable called `routeConfig` of type `Routes` and define two routes for the app: <docs-code header="Add routes to the app" path="adev/src/content/tutorials/first-app/steps/11-details-page/src/app/routes.ts" visibleLines="[5,18]"/> The entries in the `routeConfig` array represent the routes in the application. The first entry navigates to the `HomeComponent` whenever the url matches `''`. The second entry uses some special formatting that will be revisited in a future lesson. 1. Save all changes and confirm that the application works in the browser. The application should still display the list of housing locations. </docs-step> </docs-workflow> Summary: In this lesson, you enabled routing in your app as well as defined new routes. Now your app can support navigation between views. In the next lesson, you will learn to navigate to the "details" page for a given housing location. You are making great progress with your app, well done. For more information about the topics covered in this lesson, visit: <docs-pill-row> <docs-pill href="guide/routing" title="Routing in Angular Overview"/> <docs-pill href="guide/routing/common-router-tasks" title="Common Routing Tasks"/> </docs-pill-row>
005961
# Use *ngFor to list objects in component This tutorial lesson demonstrates how to use `ngFor` directive in Angular templates in order to display dynamically repeated data in a template. <docs-video src="https://www.youtube.com/embed/eM3zi_n7lNs?si=MIl5NcRxvcLjYt5f&amp;start=477"/> ## What you'll learn * You will have added a data set to the app * Your app will display a list of elements from the new data set using `ngFor` ## Conceptual preview of ngFor In Angular, `ngFor` is a specific type of [directive](guide/directives) used to dynamically repeat data in a template. In plain JavaScript you would use a for loop - ngFor provides similar functionality for Angular templates. You can utilize `ngFor` to iterate over arrays and even asynchronous values. In this lesson, you'll add a new array of data to iterate over. For a more in depth explanation, please refer to the [Built-in directives](guide/directives#ngFor) guide. <docs-workflow> <docs-step title="Add housing data to the `HomeComponent`"> In the `HomeComponent` there is only a single housing location. In this step, you will add an array of `HousingLocation` entries. 1. In `src/app/home/home.component.ts`, remove the `housingLocation` property from the `HomeComponent` class. 1. Update the `HomeComponent` class to have a property called `housingLocationList`. Update your code to match the following code: <docs-code header="Add housingLocationList property" path="adev/src/content/tutorials/first-app/steps/09-services/src/app/home/home.component.ts" visibleLines="26-131"/> IMPORTANT: Do not remove the `@Component` decorator, you will update that code in an upcoming step. </docs-step> <docs-step title="Update the `HomeComponent` template to use `ngFor`"> Now the app has a dataset that you can use to display the entries in the browser using the `ngFor` directive. 1. Update the `<app-housing-location>` tag in the template code to this: <docs-code header="Add ngFor to HomeComponent template" path="adev/src/content/tutorials/first-app/steps/09-services/src/app/home/home.component.ts" visibleLines="[17,22]"/> Note, in the code `[housingLocation] = "housingLocation"` the `housingLocation` value now refers to the variable used in the `ngFor` directive. Before this change, it referred to the property on the `HomeComponent` class. 1. Save all changes. 1. Refresh the browser and confirm that the app now renders a grid of housing locations. <section class="lightbox"> <img alt="browser frame of homes-app displaying logo, filter text input box, search button and a grid of housing location cards" src="assets/images/tutorials/first-app/homes-app-lesson-08-step-2.png"> </section> </docs-step> </docs-workflow> Summary: In this lesson, you used the `ngFor` directive to repeat data dynamically in Angular templates. You also added a new array of data to be used in the Angular app. The application now dynamically renders a list of housing locations in the browser. The app is taking shape, great job. For more information about the topics covered in this lesson, visit: <docs-pill-row> <docs-pill href="guide/directives/structural-directives" title="Structural Directives"/> <docs-pill href="guide/directives#ngFor" title="ngFor guide"/> <docs-pill href="api/common/NgFor" title="ngFor"/> </docs-pill-row>
006004
# Add HTTP communication to your app This tutorial demonstrates how to integrate HTTP and an API into your app. Up until this point your app has read data from a static array in an Angular service. The next step is to use a JSON server that your app will communicate with over HTTP. The HTTP request will simulate the experience of working with data from a server. <docs-video src="https://www.youtube.com/embed/5K10oYJ5Y-E?si=TiuNKx_teR9baO7k"/> IMPORTANT: We recommend using your local environment for this step of the tutorial.
006005
## What you'll learn Your app will use data from a JSON server <docs-workflow> <docs-step title="Configure the JSON server"> JSON Server is an open source tool used to create mock REST APIs. You'll use it to serve the housing location data that is currently stored in the housing service. 1. Install `json-server` from npm by using the following command. <docs-code language="bash"> npm install -g json-server </docs-code> 1. In the root directory of your project, create a file called `db.json`. This is where you will store the data for the `json-server`. 1. Open `db.json` and copy the following code into the file <docs-code language="json"> { "locations": [ { "id": 0, "name": "Acme Fresh Start Housing", "city": "Chicago", "state": "IL", "photo": "https://angular.dev/assets/images/tutorials/common/bernard-hermant-CLKGGwIBTaY-unsplash.jpg", "availableUnits": 4, "wifi": true, "laundry": true }, { "id": 1, "name": "A113 Transitional Housing", "city": "Santa Monica", "state": "CA", "photo": "https://angular.dev/assets/images/tutorials/common/brandon-griggs-wR11KBaB86U-unsplash.jpg", "availableUnits": 0, "wifi": false, "laundry": true }, { "id": 2, "name": "Warm Beds Housing Support", "city": "Juneau", "state": "AK", "photo": "https://angular.dev/assets/images/tutorials/common/i-do-nothing-but-love-lAyXdl1-Wmc-unsplash.jpg", "availableUnits": 1, "wifi": false, "laundry": false }, { "id": 3, "name": "Homesteady Housing", "city": "Chicago", "state": "IL", "photo": "https://angular.dev/assets/images/tutorials/common/ian-macdonald-W8z6aiwfi1E-unsplash.jpg", "availableUnits": 1, "wifi": true, "laundry": false }, { "id": 4, "name": "Happy Homes Group", "city": "Gary", "state": "IN", "photo": "https://angular.dev/assets/images/tutorials/common/krzysztof-hepner-978RAXoXnH4-unsplash.jpg", "availableUnits": 1, "wifi": true, "laundry": false }, { "id": 5, "name": "Hopeful Apartment Group", "city": "Oakland", "state": "CA", "photo": "https://angular.dev/assets/images/tutorials/common/r-architecture-JvQ0Q5IkeMM-unsplash.jpg", "availableUnits": 2, "wifi": true, "laundry": true }, { "id": 6, "name": "Seriously Safe Towns", "city": "Oakland", "state": "CA", "photo": "https://angular.dev/assets/images/tutorials/common/phil-hearing-IYfp2Ixe9nM-unsplash.jpg", "availableUnits": 5, "wifi": true, "laundry": true }, { "id": 7, "name": "Hopeful Housing Solutions", "city": "Oakland", "state": "CA", "photo": "https://angular.dev/assets/images/tutorials/common/r-architecture-GGupkreKwxA-unsplash.jpg", "availableUnits": 2, "wifi": true, "laundry": true }, { "id": 8, "name": "Seriously Safe Towns", "city": "Oakland", "state": "CA", "photo": "https://angular.dev/assets/images/tutorials/common/saru-robert-9rP3mxf8qWI-unsplash.jpg", "availableUnits": 10, "wifi": false, "laundry": false }, { "id": 9, "name": "Capital Safe Towns", "city": "Portland", "state": "OR", "photo": "https://angular.dev/assets/images/tutorials/common/webaliser-_TPTXZd9mOo-unsplash.jpg", "availableUnits": 6, "wifi": true, "laundry": true } ] } </docs-code> 1. Save this file. 1. Time to test your configuration. From the command line, at the root of your project run the following commands. <docs-code language="bash"> json-server --watch db.json </docs-code> 1. In your web browser, navigate to the `http://localhost:3000/locations` and confirm that the response includes the data stored in `db.json`. If you have any trouble with your configuration, you can find more details in the [official documentation](https://www.npmjs.com/package/json-server). </docs-step> <docs-step title="Update service to use web server instead of local array"> The data source has been configured, the next step is to update your web app to connect to it use the data. 1. In `src/app/housing.service.ts`, make the following changes: 1. Update the code to remove `housingLocationList` property and the array containing the data. 1. Add a string property called `url` and set its value to `'http://localhost:3000/locations'` <docs-code language="javascript"> url = 'http://localhost:3000/locations'; </docs-code> This code will result in errors in the rest of the file because it depends on the `housingLocationList` property. We're going to update the service methods next. 1. Update the `getAllHousingLocations` function to make a call to the web server you configured. <docs-code header="" path="adev/src/content/tutorials/first-app/steps/14-http/src-final/app/housing.service.ts" visibleLines="[10,13]"/> The code now uses asynchronous code to make a **GET** request over HTTP. HELPFUL: For this example, the code uses `fetch`. For more advanced use cases consider using `HttpClient` provided by Angular. 1. Update the `getHousingLocationsById` function to make a call to the web server you configured. <docs-code header="" path="adev/src/content/tutorials/first-app/steps/14-http/src-final/app/housing.service.ts" visibleLines="[15,18]"/> 1. Once all the updates are complete, your updated service should match the following code. <docs-code header="Final version of housing.service.ts" path="adev/src/content/tutorials/first-app/steps/14-http/src-final/app/housing.service.ts" visibleLines="[1,24]" /> </docs-step> <docs-step title="Update the components to use asynchronous calls to the housing service"> The server is now reading data from the HTTP request but the components that rely on the service now have errors because they were programmed to use the synchronous version of the service. 1. In `src/app/home/home.component.ts`, update the `constructor` to use the new asynchronous version of the `getAllHousingLocations` method. <docs-code header="" path="adev/src/content/tutorials/first-app/steps/14-http/src-final/app/home/home.component.ts" visibleLines="[32,37]"/> 1. In `src/app/details/details.component.ts`, update the `constructor` to use the new asynchronous version of the `getHousingLocationById` method. <docs-code header="" path="adev/src/content/tutorials/first-app/steps/14-http/src-final/app/details/details.component.ts" visibleLines="[61,66]"/> 1. Save your code. 1. Open the application in the browser and confirm that it runs without any errors. </docs-step> </docs-workflow> Note: This lesson relies on the `fetch` browser API. For the support of interceptors, please refer to the [Http Client documentation](/guide/http) Summary: In this lesson, you updated your app to use a local web server (`json-server`), and use asynchronous service methods to retrieve data. Congratulations! You've successfully completed this tutorial and are ready to continue your journey with building even more complex Angular Apps. If you would like to learn more, please consider completing some of Angular's other developer [tutorials](tutorials) and [guides](overview).
006012
import {Component} from '@angular/core'; import {HomeComponent} from './home/home.component'; import {RouterLink, RouterOutlet} from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [HomeComponent, RouterLink, RouterOutlet], template: ` <main> <a [routerLink]="['/']"> <header class="brand-name"> <img class="brand-logo" src="/assets/logo.svg" alt="logo" aria-hidden="true" /> </header> </a> <section class="content"> <router-outlet></router-outlet> </section> </main> `, styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'homes'; }
006026
/* * Protractor support is deprecated in Angular. * Protractor is used in this example for compatibility with Angular documentation tools. */ import {bootstrapApplication, provideProtractorTestingSupport} from '@angular/platform-browser'; import {AppComponent} from './app/app.component'; import {provideRouter} from '@angular/router'; import routeConfig from './app/routes'; bootstrapApplication(AppComponent, { providers: [provideProtractorTestingSupport(), provideRouter(routeConfig)], }).catch((err) => console.error(err));
006031
import {Component} from '@angular/core'; import {HomeComponent} from './home/home.component'; import {RouterLink, RouterOutlet} from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [HomeComponent, RouterLink, RouterOutlet], template: ` <main> <a [routerLink]="['/']"> <header class="brand-name"> <img class="brand-logo" src="/assets/logo.svg" alt="logo" aria-hidden="true" /> </header> </a> <section class="content"> <router-outlet></router-outlet> </section> </main> `, styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'homes'; }
006048
# Control Flow in Components - `@if` Deciding what to display on the screen for a user is a common task in application development. Many times, the decision is made programmatically using conditions. To express conditional displays in templates, Angular uses the `@if` template syntax. In this activity, you'll learn how to use conditionals in templates. <hr/> The syntax that enables the conditional display of elements in a template is `@if`. Here's an example of how to use the `@if` syntax in a component: ```angular-ts @Component({ ... template: ` @if (isLoggedIn) { <p>Welcome back, Friend!</p> } `, }) class AppComponent { isLoggedIn = true; } ``` Two things to take note of: - There is an `@` prefix for the `if` because it is a special type of syntax called [Angular template syntax](guide/templates) - For applications using v16 and older please refer to the [Angular documentation for NgIf](guide/directives/structural-directives) for more information. <docs-workflow> <docs-step title="Create a property called `isServerRunning`"> In the `AppComponent` class, add a `boolean` property called `isServerRunning`, set the initial value to `true`. </docs-step> <docs-step title="Use `@if` in the template"> Update the template to display the message `Yes, the server is running` if the value of `isServerRunning` is `true`. </docs-step> <docs-step title="Use `@else` in the template"> Now Angular supports native template syntax for defining the else case with the `@else` syntax. Update the template to display the message `No, the server is not running` as the else case. Here's an example: ```angular-ts template: ` @if (isServerRunning) { ... } @else { ... } `; ``` Add your code to fill in the missing markup. </docs-step> </docs-workflow> This type of functionality is called conditional control flow. Next you'll learn how to repeat items in a template.
006054
import {Component} from '@angular/core'; import {RouterOutlet, RouterLink} from '@angular/router'; @Component({ selector: 'app-root', template: ` <nav> <a routerLink="/">Home</a> | <a routerLink="/user">User</a> </nav> <router-outlet /> `, standalone: true, imports: [RouterOutlet, RouterLink], }) export class AppComponent {}
006064
# Routing Overview For most apps, there comes a point where the app requires more than a single page. When that time inevitably comes, routing becomes a big part of the performance story for users. In this activity, you'll learn how to setup and configure your app to use Angular Router. <hr> <docs-workflow> <docs-step title="Create an app.routes.ts file"> Inside `app.routes.ts`, make the following changes: 1. Import `Routes` from the `@angular/router` package. 1. Export a constant called `routes` of type `Routes`, assign it `[]` as the value. ```ts import {Routes} from '@angular/router'; export const routes: Routes = []; ``` </docs-step> <docs-step title="Add routing to provider"> In `app.config.ts`, configure the app to Angular Router with the following steps: 1. Import the `provideRouter` function from `@angular/router`. 1. Import `routes` from the `./app.routes.ts`. 1. Call the `provideRouter` function with `routes` passed in as an argument in the `providers` array. <docs-code language="ts" highlight="[2,3,6]"> import {ApplicationConfig} from '@angular/core'; import {provideRouter} from '@angular/router'; import {routes} from './app.routes'; export const appConfig: ApplicationConfig = { providers: [provideRouter(routes)], }; </docs-code> </docs-step> <docs-step title="Import `RouterOutlet` in the component"> Finally, to make sure your app is ready to use the Angular Router, you need to tell the app where you expect the router to display the desired content. Accomplish that by using the `RouterOutlet` directive from `@angular/router`. Update the template for `AppComponent` by adding `<router-outlet />` <docs-code language="angular-ts" highlight="[11]"> import {RouterOutlet} from '@angular/router'; @Component({ ... template: ` <nav> <a href="/">Home</a> | <a href="/user">User</a> </nav> <router-outlet /> `, standalone: true, imports: [RouterOutlet], }) export class AppComponent {} </docs-code> </docs-step> </docs-workflow> Your app is now setup to use Angular Router. Nice work! 🙌 Keep the momentum going to learn the next step of defining the routes for our app.
006066
import {Routes} from '@angular/router'; export const routes: Routes = [];
006086
# Inject-based dependency injection Creating an injectable service is the first part of the dependency injection (DI) system in Angular. How do you inject a service into a component? Angular has a convenient function called `inject()` that can be used in the proper context. Note: Injection contexts are beyond the scope of this tutorial, but you can find more information in the [Angular Docs](guide/di/dependency-injection-context) if you would like to learn more. In this activity, you'll learn how to inject a service and use it in a component. <hr> It is often helpful to initialize class properties with values provided by the DI system. Here's an example: <docs-code language="ts" highlight="[3]"> @Component({...}) class PetCareDashboardComponent { petRosterService = inject(PetRosterService); } </docs-code> <docs-workflow> <docs-step title="Inject the `CarService`"> In `app.component.ts`, using the `inject()` function inject the `CarService` and assign it to a property called `carService` Note: Notice the difference between the property `carService` and the class `CarService`. </docs-step> <docs-step title="Use the `carService` instance"> Calling `inject(CarService)` gave you an instance of the `CarService` that you can use in your application, stored in the `carService` property. In the `constructor` function of the `AppComponent`, add the following implementation: ```ts constructor() { this.display = this.carService.getCars().join(' ⭐️ '); } ``` </docs-step> <docs-step title="Update the `AppComponent` template"> Update the component template in `app.component.ts` with the following code: ```ts template: `<p>Car Listing: {{ display }}</p>`, ``` </docs-step> </docs-workflow> You've just injected your first service into a component - fantastic effort. Before you finish this section on DI, you'll learn an alternative syntax to inject resources into your components.
006101
# Reactive Forms When you want to manage your forms programmatically instead of relying purely on the template, reactive forms are the answer. In this activity, you'll learn how to setup reactive forms. <hr> <docs-workflow> <docs-step title="Import `ReactiveForms` module"> In `app.component.ts`, import `ReactiveFormsModule` from `@angular/forms` and add it to the `imports` array of the component. ```angular-ts import { ReactiveFormsModule } from '@angular/forms'; @Component({ selector: 'app-root', standalone: true, template: ` <form> <label>Name <input type="text" /> </label> <label>Email <input type="email" /> </label> <button type="submit">Submit</button> </form> `, imports: [ReactiveFormsModule], }) ``` </docs-step> <docs-step title="Create the `FormGroup` object with FormControls"> Reactive forms use the `FormControl` class to represent the form controls (e.g., inputs). Angular provides the `FormGroup` class to serve as a grouping of form controls into a helpful object that makes handling large forms more convenient for developers. Add `FormControl` and `FormGroup` to the import from `@angular/forms` so that you can create a FormGroup for each form, with the properties `name` and `email` as FormControls. ```ts import {ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms'; ... export class AppComponent { profileForm = new FormGroup({ name: new FormControl(''), email: new FormControl(''), }); } ``` </docs-step> <docs-step title="Link the FormGroup and FormControls to the form"> Each `FormGroup` should be attached to a form using the `[formGroup]` directive. In addition, each `FormControl` can be attached with the `formControlName` directive and assigned to the corresponding property. Update the template with the following form code: ```angular-html <form [formGroup]="profileForm"> <label> Name <input type="text" formControlName="name" /> </label> <label> Email <input type="email" formControlName="email" /> </label> <button type="submit">Submit</button> </form> ``` </docs-step> <docs-step title="Handle update to the form"> When you want to access data from the `FormGroup`, it can be done by accessing the value of the `FormGroup`. Update the `template` to display the form values: ```angular-html ... <h2>Profile Form</h2> <p>Name: {{ profileForm.value.name }}</p> <p>Email: {{ profileForm.value.email }}</p> ``` </docs-step> <docs-step title="Access FormGroup values"> Add a new method to the component class called `handleSubmit` that you'll later use to handle the form submission. This method will display values from the form, you can access the values from the FormGroup. In the component class, add the `handleSubmit()` method to handle the form submission. <docs-code language="ts"> handleSubmit() { alert( this.profileForm.value.name + ' | ' + this.profileForm.value.email ); } </docs-code> </docs-step> <docs-step title="Add `ngSubmit` to the form"> You have access to the form values, now it is time to handle the submission event and use the `handleSubmit` method. Angular has an event handler for this specific purpose called `ngSubmit`. Update the form element to call the `handleSubmit` method when the form is submitted. <docs-code language="angular-html" highlight="[3]"> <form [formGroup]="profileForm" (ngSubmit)="handleSubmit()"> </docs-code> </docs-step> </docs-workflow> And just like that, you know how to work with reactive forms in Angular. Fantastic job with this activity. Keep going to learn about form validation.
006109
# Control Flow in Components - `@for` Often when building web applications, you need to repeat some code a specific number of times - for example, given an array of names, you may want to display each name in a `<p>` tag. In this activity, you'll learn how to use `@for` to repeat elements in a template. <hr/> The syntax that enables repeating elements in a template is `@for`. Here's an example of how to use the `@for` syntax in a component: ```angular-ts @Component({ ... template: ` @for (os of operatingSystems; track os.id) { {{ os.name }} } `, }) export class AppComponent { operatingSystems = [{id: 'win', name: 'Windows'}, {id: 'osx', name: 'MacOS'}, {id: 'linux', name: 'Linux'}]; } ``` Two things to take note of: * There is an `@` prefix for the `for` because it is a special syntax called [Angular template syntax](guide/templates) * For applications using v16 and older please refer to the [Angular documentation for NgFor](guide/directives/structural-directives) <docs-workflow> <docs-step title="Add the `users` property"> In the `AppComponent` class, add a property called `users` that contains users and their names. ```ts [{id: 0, name: 'Sarah'}, {id: 1, name: 'Amy'}, {id: 2, name: 'Rachel'}, {id: 3, name: 'Jessica'}, {id: 4, name: 'Poornima'}] ``` </docs-step> <docs-step title="Update the template"> Update the template to display each user name in a `p` element using the `@for` template syntax. ```angular-html @for (user of users; track user.id) { <p>{{ user.name }}</p> } ``` Note: the use of `track` is required, you may use the `id` or some other unique identifier. </docs-step> </docs-workflow> This type of functionality is called control flow. Next, you'll learn to customize and communicate with components - by the way, you're doing a great job so far.
006144
# Property Binding in Angular Property binding in Angular enables you to set values for properties of HTML elements, Angular components and more. Use property binding to dynamically set values for properties and attributes. You can do things such as toggle button features, set image paths programmatically, and share values between components. In this activity, you'll learn how to use property binding in templates. <hr /> To bind to an element's attribute, wrap the attribute name in square brackets. Here's an example: ```angular-html <img alt="photo" [src]="imageURL"> ``` In this example, the value of the `src` attribute will be bound to the class property `imageURL`. Whatever value `imageURL` has will be set as the `src` attribute of the `img` tag. <docs-workflow> <docs-step title="Add a property called `isEditable`" header="app.component.ts" language="ts"> Update the code in `app.component.ts` by adding a property to the `AppComponent` class called `isEditable` with the initial value set to `true`. <docs-code highlight="[2]"> export class AppComponent { isEditable = true; } </docs-code> </docs-step> <docs-step title="Bind to `contentEditable`" header="app.component.ts" language="ts"> Next, bind the `contentEditable` attribute of the `div` to the `isEditable` property by using the <code aria-label="square brackets">[]</code> syntax. <docs-code highlight="[3]" language="angular-ts"> @Component({ ... template: `<div [contentEditable]="isEditable"></div>`, }) </docs-code> </docs-step> </docs-workflow> The div is now editable. Nice work 👍 Property binding is one of Angular's many powerful features. If you'd like to learn more checkout [the Angular documentation](guide/templates/property-binding).