_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/adev/src/content/guide/pipes/overview.md_0_1920
# Understanding Pipes Use pipes to transform strings, currency amounts, dates, and other data for display. ## What is a pipe Pipes are simple functions to use in templates to accept an input value and return a transformed value. Pipes are useful because you can use them throughout your application, while only declaring each pipe once. For example, you would use a pipe to show a date as **April 15, 1988** rather than the raw string format. You can create your own custom pipes to expose reusable transformations in templates. ## Built-in pipes Angular provides built-in pipes for typical data transformations, including transformations for internationalization (i18n), which use locale information to format data. The following are commonly used built-in pipes for data formatting: - [`DatePipe`](api/common/DatePipe): Formats a date value according to locale rules. - [`UpperCasePipe`](api/common/UpperCasePipe): Transforms text to all upper case. - [`LowerCasePipe`](api/common/LowerCasePipe): Transforms text to all lower case. - [`CurrencyPipe`](api/common/CurrencyPipe): Transforms a number to a currency string, formatted according to locale rules. - [`DecimalPipe`](/api/common/DecimalPipe): Transforms a number into a string with a decimal point, formatted according to locale rules. - [`PercentPipe`](api/common/PercentPipe): Transforms a number to a percentage string, formatted according to locale rules. - [`AsyncPipe`](api/common/AsyncPipe): Subscribe and unsubscribe to an asynchronous source such as an observable. - [`JsonPipe`](api/common/JsonPipe): Display a component object property to the screen as JSON for debugging. Note: For a complete list of built-in pipes, see the [pipes API documentation](/api?type=pipe "Pipes API reference summary"). To learn more about using pipes for internationalization (i18n) efforts, see [formatting data based on locale](guide/i18n/format-data-locale).
{ "end_byte": 1920, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/pipes/overview.md" }
angular/adev/src/content/guide/pipes/precedence.md_0_898
# Pipe precedence in template expressions Sometimes you want to choose between two values, based on some condition, before passing the choice to the pipe. You could use the JavaScript ternary operator (`?:`) in the template to make that choice. Beware! The pipe operator has a higher precedence than the JavaScript ternary operator (`?:`). If you simply write the expression as if it were evaluated left-to-right, you might be surprised by the result. For example, ```ts condition ? a : b | pipe ``` is parsed as ```ts condition ? a : (b | pipe) ``` The value of `b` passes through `pipe`; the value of `a` *will not*. If you want the pipe to apply to the result of the ternary expression, wrap the entire expression in parentheses. For example, ```ts (condition ? a : b) | pipe ``` In general, you should always use parentheses to be sure Angular evaluates the expression as you intend.
{ "end_byte": 898, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/pipes/precedence.md" }
angular/adev/src/content/guide/pipes/change-detection.md_0_8114
# Change detection with pipes Pipes are often used with data-bound values that might change based on user actions. If the data is a primitive input value, such as `String` or `Number`, or an object reference as input, such as `Date` or `Array`, Angular executes the pipe whenever it detects a change for the value. <docs-code-multifile path="adev/src/content/examples/pipes/src/app/power-booster.component.ts"> <docs-code header="src/app/exponential-strength.pipe.ts" path="adev/src/content/examples/pipes/src/app/exponential-strength.pipe.ts" highlight="[16]" visibleRegion="pipe-class" /> <docs-code header="src/app/power-booster.component.ts" path="adev/src/content/examples/pipes/src/app/power-booster.component.ts"/> </docs-code-multifile> The `exponentialStrength` pipe executes every time the user changes the value or the exponent. See the highlighted line above. Angular detects each change and immediately runs the pipe. This is fine for primitive input values. However, if you change something *inside* a composite object (such as the month of a date, an element of an array, or an object property), you need to understand how change detection works, and how to use an `impure` pipe. ## How change detection works Angular looks for changes to data-bound values in a change detection process that runs after every DOM event: every keystroke, mouse move, timer tick, and server response. The following example, which doesn't use a pipe, demonstrates how Angular uses its default change detection strategy to monitor and update its display of every hero in the `heroes` array. The example tabs show the following: | Files | Details | |:--- |:--- | | `flying-heroes.component.html (v1)` | The `*ngFor` repeater displays the hero names. | | `flying-heroes.component.ts (v1)` | Provides heroes, adds heroes into the array, and resets the array. | <docs-code-multifile> <docs-code header="src/app/flying-heroes.component.html (v1)" path="adev/src/content/examples/pipes/src/app/flying-heroes.component.html" visibleRegion="template-1"/> <docs-code header="src/app/flying-heroes.component.ts (v1)" path="adev/src/content/examples/pipes/src/app/flying-heroes.component.ts" visibleRegion="v1"/> </docs-code-multifile> Angular updates the display every time the user adds a hero. If the user clicks the **Reset** button, Angular replaces `heroes` with a new array of the original heroes and updates the display. If you add the ability to remove or change a hero, Angular would detect those changes and update the display as well. However, executing a pipe to update the display with every change would slow down your application's performance. So Angular uses a faster change-detection algorithm for executing a pipe, as described in the next section. ## Detecting pure changes to primitives and object references By default, pipes are defined as *pure* so that Angular executes the pipe only when it detects a *pure change* to the input value or parameters. A pure change is either a change to a primitive input value \(such as `String`, `Number`, `Boolean`, or `Symbol`\), or a changed object reference \(such as `Date`, `Array`, `Function`, or `Object`\). A pure pipe must use a pure function, which is one that processes inputs and returns values without side effects. In other words, given the same input, a pure function should always return the same output. With a pure pipe, Angular ignores changes within objects and arrays because checking a primitive value or object reference is much faster than performing a deep check for differences within objects. Angular can quickly determine if it can skip executing the pipe and updating the view. However, a pure pipe with an array as input might not work the way you want. To demonstrate this issue, change the previous example to filter the list of heroes to just those heroes who can fly. For this, consider we use the `FlyingHeroesPipe` in the `*ngFor` repeater as shown in the following code. The tabs for the example show the following: | Files | Details | |:--- |:--- | | flying-heroes.component.html | Template with the new pipe used. | | flying-heroes.pipe.ts | File with custom pipe that filters flying heroes. | <docs-code-multifile> <docs-code header="src/app/flying-heroes.component.html" path="adev/src/content/examples/pipes/src/app/flying-heroes.component.html" visibleRegion="template-flying-heroes"/> <docs-code header="src/app/flying-heroes.pipe.ts" path="adev/src/content/examples/pipes/src/app/flying-heroes.pipe.ts" visibleRegion="pure"/> </docs-code-multifile> The application now shows unexpected behavior: When the user adds flying heroes, none of them appear under "Heroes who fly." This happens because the code that adds a hero does so by pushing it onto the `heroes` array that is used as input for the `flyingHeroes` pipe. <docs-code header="src/app/flying-heroes.component.ts" path="adev/src/content/examples/pipes/src/app/flying-heroes.component.ts" visibleRegion="push"/> The change detector ignores changes within elements of an array, so the pipe doesn't run. The reason Angular ignores the changed array element is that the *reference* to the array hasn't changed. Because the array is the same, Angular does not update the display. One way to get the behavior you want is to change the object reference itself. Replace the array with a new array containing the newly changed elements, and then input the new array to the pipe. In the preceding example, create an array with the new hero appended, and assign that to `heroes`. Angular detects the change in the array reference and executes the pipe. To summarize, if you mutate the input array, the pure pipe doesn't execute. If you *replace* the input array, the pipe executes and the display is updated. As an alternative, use an *impure* pipe to detect changes within composite objects such as arrays, as described in the next section. ## Detecting impure changes within composite objects To execute a custom pipe after a change *within* a composite object, such as a change to an element of an array, you need to define your pipe as `impure` to detect impure changes. Angular executes an impure pipe every time it detects a change (e.g. every keystroke or mouse event). IMPORTANT: While an impure pipe can be useful, be careful using one. A long-running impure pipe could dramatically slow down your application. Make a pipe impure by setting its `pure` flag to `false`: <docs-code header="src/app/flying-heroes.pipe.ts" path="adev/src/content/examples/pipes/src/app/flying-heroes.pipe.ts" visibleRegion="pipe-decorator" highlight="[19]"/> The following code shows the complete implementation of `FlyingHeroesImpurePipe`, which extends `FlyingHeroesPipe` to inherit its characteristics. The example shows that you don't have to change anything else—the only difference is setting the `pure` flag as `false` in the pipe metadata. <docs-code-multifile> <docs-code header="src/app/flying-heroes.pipe.ts (FlyingHeroesImpurePipe)" path="adev/src/content/examples/pipes/src/app/flying-heroes.pipe.ts" visibleRegion="impure"/> <docs-code header="src/app/flying-heroes.pipe.ts (FlyingHeroesPipe)" path="adev/src/content/examples/pipes/src/app/flying-heroes.pipe.ts" visibleRegion="pure"/> </docs-code-multifile> `FlyingHeroesImpurePipe` is a reasonable candidate for an impure pipe because the `transform` function is trivial and fast: <docs-code header="src/app/flying-heroes.pipe.ts (filter)" path="adev/src/content/examples/pipes/src/app/flying-heroes.pipe.ts" visibleRegion="filter"/> You can derive a `FlyingHeroesImpureComponent` from `FlyingHeroesComponent`. As shown in the following code, only the pipe in the template changes. <docs-code header="src/app/flying-heroes-impure.component.html (excerpt)" path="adev/src/content/examples/pipes/src/app/flying-heroes-impure.component.html" visibleRegion="template-flying-heroes"/>
{ "end_byte": 8114, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/pipes/change-detection.md" }
angular/adev/src/content/guide/pipes/transform-data.md_0_2863
# Custom pipes for new transforms Create custom pipes to encapsulate transformations that are not provided with the built-in pipes. Then, use your custom pipe in template expressions, the same way you use built-in pipes—to transform input values to output values for display. ## Marking a class as a pipe To mark a class as a pipe and supply configuration metadata, apply the `@Pipe` to the class. Use UpperCamelCase (the general convention for class names) for the pipe class name, and camelCase for the corresponding `name` string. Do not use hyphens in the `name`. For details and more examples, see [Pipe names](/style-guide#pipe-names "Pipe names in the Angular coding style guide"). Use `name` in template expressions as you would for a built-in pipe. ```ts import { Pipe } from '@angular/core'; @Pipe({ name: 'greet', standalone: true, }) export class GreetPipe {} ``` ## Using the PipeTransform interface Implement the [`PipeTransform`](/api/core/PipeTransform "API reference for PipeTransform") interface in your custom pipe class to perform the transformation. Angular invokes the `transform` method with the value of a binding as the first argument, and any parameters as the second argument in list form, and returns the transformed value. ```ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'greet', standalone: true, }) export class GreetPipe implements PipeTransform { transform(value: string, param1: boolean, param2: boolean): string { return `Hello ${value}`; } } ``` ## Example: Transforming a value exponentially In a game, you might want to implement a transformation that raises a value exponentially to increase a hero's power. For example, if the hero's score is 2, boosting the hero's power exponentially by 10 produces a score of 1024 (`2**10`). Use a custom pipe for this transformation. The following code example shows two component definitions: | Files | Details | |:--- |:--- | | `exponential-strength.pipe.ts` | Defines a custom pipe named `exponentialStrength` with the `transform` method that performs the transformation. It defines an argument to the `transform` method \(`exponent`\) for a parameter passed to the pipe. | | `power-booster.component.ts` | Demonstrates how to use the pipe, specifying a value \(`2`\) and the exponent parameter \(`10`\). | <docs-code-multifile> <docs-code header="src/app/exponential-strength.pipe.ts" language="ts" path="adev/src/content/examples/pipes/src/app/exponential-strength.pipe.ts"/> <docs-code header="src/app/power-booster.component.ts" language="ts" path="adev/src/content/examples/pipes/src/app/power-booster.component.ts"/> </docs-code-multifile>
{ "end_byte": 2863, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/pipes/transform-data.md" }
angular/adev/src/content/guide/pipes/BUILD.bazel_0_776
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "pipes", srcs = glob([ "*.md", ]), data = [ "//adev/src/content/examples/pipes:src/app/exponential-strength.pipe.ts", "//adev/src/content/examples/pipes:src/app/flying-heroes.component.html", "//adev/src/content/examples/pipes:src/app/flying-heroes.component.ts", "//adev/src/content/examples/pipes:src/app/flying-heroes.pipe.ts", "//adev/src/content/examples/pipes:src/app/flying-heroes-impure.component.html", "//adev/src/content/examples/pipes:src/app/hero-async-message.component.ts", "//adev/src/content/examples/pipes:src/app/power-booster.component.ts", ], visibility = ["//adev:__subpackages__"], )
{ "end_byte": 776, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/pipes/BUILD.bazel" }
angular/adev/src/content/guide/pipes/unwrapping-data-observables.md_0_1307
# Unwrapping data from an observable Observables let you pass messages between parts of your application. You can use observables for event handling, asynchronous programming, and handling multiple values. Observables can deliver single or multiple values of any type, either synchronously (as a function delivers a value to its caller) or asynchronously on a schedule. Use the built-in [`AsyncPipe`](api/common/AsyncPipe "API description of AsyncPipe") to accept an observable as input and subscribe to the input automatically. Without this pipe, your component code would have to subscribe to the observable to consume its values, extract the resolved values, expose them for binding, and unsubscribe when the observable is destroyed in order to prevent memory leaks. `AsyncPipe` is a pipe that saves boilerplate code in your component to maintain the subscription and keep delivering values from that observable as they arrive. The following code example binds an observable of message strings (`message$`) to a view with the `async` pipe. <!-- TODO: Enable preview if this example does not depend on Zone/ or if we run the example with Zone. --> <docs-code header="src/app/hero-async-message.component.ts" path="adev/src/content/examples/pipes/src/app/hero-async-message.component.ts" />
{ "end_byte": 1307, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/pipes/unwrapping-data-observables.md" }
angular/adev/src/content/guide/testing/attribute-directives.md_0_3624
# Testing Attribute Directives An *attribute directive* modifies the behavior of an element, component or another directive. Its name reflects the way the directive is applied: as an attribute on a host element. ## Testing the `HighlightDirective` The sample application's `HighlightDirective` sets the background color of an element based on either a data bound color or a default color \(lightgray\). It also sets a custom property of the element \(`customProperty`\) to `true` for no reason other than to show that it can. <docs-code header="app/shared/highlight.directive.ts" path="adev/src/content/examples/testing/src/app/shared/highlight.directive.ts"/> It's used throughout the application, perhaps most simply in the `AboutComponent`: <docs-code header="app/about/about.component.ts" path="adev/src/content/examples/testing/src/app/about/about.component.ts"/> Testing the specific use of the `HighlightDirective` within the `AboutComponent` requires only the techniques explored in the ["Nested component tests"](guide/testing/components-scenarios#nested-component-tests) section of [Component testing scenarios](guide/testing/components-scenarios). <docs-code header="app/about/about.component.spec.ts" path="adev/src/content/examples/testing/src/app/about/about.component.spec.ts" visibleRegion="tests"/> However, testing a single use case is unlikely to explore the full range of a directive's capabilities. Finding and testing all components that use the directive is tedious, brittle, and almost as unlikely to afford full coverage. *Class-only tests* might be helpful, but attribute directives like this one tend to manipulate the DOM. Isolated unit tests don't touch the DOM and, therefore, do not inspire confidence in the directive's efficacy. A better solution is to create an artificial test component that demonstrates all ways to apply the directive. <docs-code header="app/shared/highlight.directive.spec.ts (TestComponent)" path="adev/src/content/examples/testing/src/app/shared/highlight.directive.spec.ts" visibleRegion="test-component"/> <img alt="HighlightDirective spec in action" src="assets/images/guide/testing/highlight-directive-spec.png"> HELPFUL: The `<input>` case binds the `HighlightDirective` to the name of a color value in the input box. The initial value is the word "cyan" which should be the background color of the input box. Here are some tests of this component: <docs-code header="app/shared/highlight.directive.spec.ts (selected tests)" path="adev/src/content/examples/testing/src/app/shared/highlight.directive.spec.ts" visibleRegion="selected-tests"/> A few techniques are noteworthy: * The `By.directive` predicate is a great way to get the elements that have this directive *when their element types are unknown* * The [`:not` pseudo-class](https://developer.mozilla.org/docs/Web/CSS/:not) in `By.css('h2:not([highlight])')` helps find `<h2>` elements that *do not* have the directive. `By.css('*:not([highlight])')` finds *any* element that does not have the directive. * `DebugElement.styles` affords access to element styles even in the absence of a real browser, thanks to the `DebugElement` abstraction. But feel free to exploit the `nativeElement` when that seems easier or more clear than the abstraction. * Angular adds a directive to the injector of the element to which it is applied. The test for the default color uses the injector of the second `<h2>` to get its `HighlightDirective` instance and its `defaultColor`. * `DebugElement.properties` affords access to the artificial custom property that is set by the directive
{ "end_byte": 3624, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/attribute-directives.md" }
angular/adev/src/content/guide/testing/overview.md_0_6033
# Testing Testing your Angular application helps you check that your application is working as you expect. ## Set up testing The Angular CLI downloads and installs everything you need to test an Angular application with [Jasmine testing framework](https://jasmine.github.io). The project you create with the CLI is immediately ready to test. Just run the [`ng test`](cli/test) CLI command: <docs-code language="shell"> ng test </docs-code> The `ng test` command builds the application in *watch mode*, and launches the [Karma test runner](https://karma-runner.github.io). The console output looks like below: <docs-code language="shell"> 02 11 2022 09:08:28.605:INFO [karma-server]: Karma v6.4.1 server started at http://localhost:9876/ 02 11 2022 09:08:28.607:INFO [launcher]: Launching browsers Chrome with concurrency unlimited 02 11 2022 09:08:28.620:INFO [launcher]: Starting browser Chrome 02 11 2022 09:08:31.312:INFO [Chrome]: Connected on socket -LaEYvD2R7MdcS0-AAAB with id 31534482 Chrome: Executed 3 of 3 SUCCESS (0.193 secs / 0.172 secs) TOTAL: 3 SUCCESS </docs-code> The last line of the log shows that Karma ran three tests that all passed. The test output is displayed in the browser using [Karma Jasmine HTML Reporter](https://github.com/dfederm/karma-jasmine-html-reporter). <img alt="Jasmine HTML Reporter in the browser" src="assets/images/guide/testing/initial-jasmine-html-reporter.png"> Click on a test row to re-run just that test or click on a description to re-run the tests in the selected test group \("test suite"\). Meanwhile, the `ng test` command is watching for changes. To see this in action, make a small change to `app.component.ts` and save. The tests run again, the browser refreshes, and the new test results appear. ## Configuration The Angular CLI takes care of Jasmine and Karma configuration for you. It constructs the full configuration in memory, based on options specified in the `angular.json` file. If you want to customize Karma, you can create a `karma.conf.js` by running the following command: <docs-code language="shell"> ng generate config karma </docs-code> HELPFUL: Read more about Karma configuration in the [Karma configuration guide](http://karma-runner.github.io/6.4/config/configuration-file.html). ### Other test frameworks You can also unit test an Angular application with other testing libraries and test runners. Each library and runner has its own distinctive installation procedures, configuration, and syntax. ### Test file name and location Inside the `src/app` folder the Angular CLI generated a test file for the `AppComponent` named `app.component.spec.ts`. IMPORTANT: The test file extension **must be `.spec.ts`** so that tooling can identify it as a file with tests \(also known as a *spec* file\). The `app.component.ts` and `app.component.spec.ts` files are siblings in the same folder. The root file names \(`app.component`\) are the same for both files. Adopt these two conventions in your own projects for *every kind* of test file. #### Place your spec file next to the file it tests It's a good idea to put unit test spec files in the same folder as the application source code files that they test: * Such tests are painless to find * You see at a glance if a part of your application lacks tests * Nearby tests can reveal how a part works in context * When you move the source \(inevitable\), you remember to move the test * When you rename the source file \(inevitable\), you remember to rename the test file #### Place your spec files in a test folder Application integration specs can test the interactions of multiple parts spread across folders and modules. They don't really belong to any part in particular, so they don't have a natural home next to any one file. It's often better to create an appropriate folder for them in the `tests` directory. Of course specs that test the test helpers belong in the `test` folder, next to their corresponding helper files. ## Testing in continuous integration One of the best ways to keep your project bug-free is through a test suite, but you might forget to run tests all the time. Continuous integration \(CI\) servers let you set up your project repository so that your tests run on every commit and pull request. To test your Angular CLI application in Continuous integration \(CI\) run the following command: <docs-code language="shell"> ng test --no-watch --no-progress --browsers=ChromeHeadless </docs-code> ## More information on testing After you've set up your application for testing, you might find the following testing guides useful. | | Details | |:--- |:--- | | [Code coverage](guide/testing/code-coverage) | How much of your app your tests are covering and how to specify required amounts. | | [Testing services](guide/testing/services) | How to test the services your application uses. | | [Basics of testing components](guide/testing/components-basics) | Basics of testing Angular components. | | [Component testing scenarios](guide/testing/components-scenarios) | Various kinds of component testing scenarios and use cases. | | [Testing attribute directives](guide/testing/attribute-directives) | How to test your attribute directives. | | [Testing pipes](guide/testing/pipes) | How to test pipes. | | [Debugging tests](guide/testing/debugging) | Common testing bugs. | | [Testing utility APIs](guide/testing/utility-apis) | Angular testing features. |
{ "end_byte": 6033, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/overview.md" }
angular/adev/src/content/guide/testing/pipes.md_0_1383
# Testing Pipes You can test [pipes](guide/templates/pipes) without the Angular testing utilities. ## Testing the `TitleCasePipe` A pipe class has one method, `transform`, that manipulates the input value into a transformed output value. The `transform` implementation rarely interacts with the DOM. Most pipes have no dependence on Angular other than the `@Pipe` metadata and an interface. Consider a `TitleCasePipe` that capitalizes the first letter of each word. Here's an implementation with a regular expression. <docs-code header="app/shared/title-case.pipe.ts" path="adev/src/content/examples/testing/src/app/shared/title-case.pipe.ts"/> Anything that uses a regular expression is worth testing thoroughly. Use simple Jasmine to explore the expected cases and the edge cases. <docs-code header="app/shared/title-case.pipe.spec.ts" path="adev/src/content/examples/testing/src/app/shared/title-case.pipe.spec.ts" visibleRegion="excerpt"/> ## Writing DOM tests to support a pipe test These are tests of the pipe *in isolation*. They can't tell if the `TitleCasePipe` is working properly as applied in the application components. Consider adding component tests such as this one: <docs-code header="app/hero/hero-detail.component.spec.ts (pipe test)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="title-case-pipe"/>
{ "end_byte": 1383, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/pipes.md" }
angular/adev/src/content/guide/testing/components-basics.md_0_9094
# Basics of testing components A component, unlike all other parts of an Angular application, combines an HTML template and a TypeScript class. The component truly is the template and the class *working together*. To adequately test a component, you should test that they work together as intended. Such tests require creating the component's host element in the browser DOM, as Angular does, and investigating the component class's interaction with the DOM as described by its template. The Angular `TestBed` facilitates this kind of testing as you'll see in the following sections. But in many cases, *testing the component class alone*, without DOM involvement, can validate much of the component's behavior in a straightforward, more obvious way. ## Component DOM testing A component is more than just its class. A component interacts with the DOM and with other components. Classes alone cannot tell you if the component is going to render properly, respond to user input and gestures, or integrate with its parent and child components. * Is `Lightswitch.clicked()` bound to anything such that the user can invoke it? * Is the `Lightswitch.message` displayed? * Can the user actually select the hero displayed by `DashboardHeroComponent`? * Is the hero name displayed as expected \(such as uppercase\)? * Is the welcome message displayed by the template of `WelcomeComponent`? These might not be troubling questions for the preceding simple components illustrated. But many components have complex interactions with the DOM elements described in their templates, causing HTML to appear and disappear as the component state changes. To answer these kinds of questions, you have to create the DOM elements associated with the components, you must examine the DOM to confirm that component state displays properly at the appropriate times, and you must simulate user interaction with the screen to determine whether those interactions cause the component to behave as expected. To write these kinds of test, you'll use additional features of the `TestBed` as well as other testing helpers. ### CLI-generated tests The CLI creates an initial test file for you by default when you ask it to generate a new component. For example, the following CLI command generates a `BannerComponent` in the `app/banner` folder \(with inline template and styles\): <docs-code language="shell"> ng generate component banner --inline-template --inline-style --module app </docs-code> It also generates an initial test file for the component, `banner-external.component.spec.ts`, that looks like this: <docs-code header="app/banner/banner-external.component.spec.ts (initial)" path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v1"/> HELPFUL: Because `compileComponents` is asynchronous, it uses the [`waitForAsync`](api/core/testing/waitForAsync) utility function imported from `@angular/core/testing`. Refer to the [waitForAsync](guide/testing/components-scenarios#waitForAsync) section for more details. ### Reduce the setup Only the last three lines of this file actually test the component and all they do is assert that Angular can create the component. The rest of the file is boilerplate setup code anticipating more advanced tests that *might* become necessary if the component evolves into something substantial. You'll learn about these advanced test features in the following sections. For now, you can radically reduce this test file to a more manageable size: <docs-code header="app/banner/banner-initial.component.spec.ts (minimal)" path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v2"/> In this example, the metadata object passed to `TestBed.configureTestingModule` simply declares `BannerComponent`, the component to test. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="configureTestingModule"/> HELPFUL: There's no need to declare or import anything else. The default test module is pre-configured with something like the `BrowserModule` from `@angular/platform-browser`. Later you'll call `TestBed.configureTestingModule()` with imports, providers, and more declarations to suit your testing needs. Optional `override` methods can further fine-tune aspects of the configuration. ### `createComponent()` After configuring `TestBed`, you call its `createComponent()` method. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="createComponent"/> `TestBed.createComponent()` creates an instance of the `BannerComponent`, adds a corresponding element to the test-runner DOM, and returns a [`ComponentFixture`](#componentfixture). IMPORTANT: Do not re-configure `TestBed` after calling `createComponent`. The `createComponent` method freezes the current `TestBed` definition, closing it to further configuration. You cannot call any more `TestBed` configuration methods, not `configureTestingModule()`, nor `get()`, nor any of the `override...` methods. If you try, `TestBed` throws an error. ### `ComponentFixture` The [ComponentFixture](api/core/testing/ComponentFixture) is a test harness for interacting with the created component and its corresponding element. Access the component instance through the fixture and confirm it exists with a Jasmine expectation: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="componentInstance"/> ### `beforeEach()` You will add more tests as this component evolves. Rather than duplicate the `TestBed` configuration for each test, you refactor to pull the setup into a Jasmine `beforeEach()` and some supporting variables: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v3"/> Now add a test that gets the component's element from `fixture.nativeElement` and looks for the expected text. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v4-test-2"/> ### `nativeElement` The value of `ComponentFixture.nativeElement` has the `any` type. Later you'll encounter the `DebugElement.nativeElement` and it too has the `any` type. Angular can't know at compile time what kind of HTML element the `nativeElement` is or if it even is an HTML element. The application might be running on a *non-browser platform*, such as the server or a [Web Worker](https://developer.mozilla.org/docs/Web/API/Web_Workers_API), where the element might have a diminished API or not exist at all. The tests in this guide are designed to run in a browser so a `nativeElement` value will always be an `HTMLElement` or one of its derived classes. Knowing that it is an `HTMLElement` of some sort, use the standard HTML `querySelector` to dive deeper into the element tree. Here's another test that calls `HTMLElement.querySelector` to get the paragraph element and look for the banner text: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v4-test-3"/> ### `DebugElement` The Angular *fixture* provides the component's element directly through the `fixture.nativeElement`. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="nativeElement"/> This is actually a convenience method, implemented as `fixture.debugElement.nativeElement`. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="debugElement-nativeElement"/> There's a good reason for this circuitous path to the element. The properties of the `nativeElement` depend upon the runtime environment. You could be running these tests on a *non-browser* platform that doesn't have a DOM or whose DOM-emulation doesn't support the full `HTMLElement` API. Angular relies on the `DebugElement` abstraction to work safely across *all supported platforms*. Instead of creating an HTML element tree, Angular creates a `DebugElement` tree that wraps the *native elements* for the runtime platform. The `nativeElement` property unwraps the `DebugElement` and returns the platform-specific element object. Because the sample tests for this guide are designed to run only in a browser, a `nativeElement` in these tests is always an `HTMLElement` whose familiar methods and properties you can explore within a test. Here's the previous test, re-implemented with `fixture.debugElement.nativeElement`: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v4-test-4"/> The `DebugElement` has other methods and properties that are useful in tests, as you'll see elsewhere in this guide. You import the `DebugElement` symbol from the Angular core library. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="import-debug-element"/>
{ "end_byte": 9094, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/components-basics.md" }
angular/adev/src/content/guide/testing/components-basics.md_9094_10895
### `By.css()` Although the tests in this guide all run in the browser, some applications might run on a different platform at least some of the time. For example, the component might render first on the server as part of a strategy to make the application launch faster on poorly connected devices. The server-side renderer might not support the full HTML element API. If it doesn't support `querySelector`, the previous test could fail. The `DebugElement` offers query methods that work for all supported platforms. These query methods take a *predicate* function that returns `true` when a node in the `DebugElement` tree matches the selection criteria. You create a *predicate* with the help of a `By` class imported from a library for the runtime platform. Here's the `By` import for the browser platform: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="import-by"/> The following example re-implements the previous test with `DebugElement.query()` and the browser's `By.css` method. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v4-test-5"/> Some noteworthy observations: * The `By.css()` static method selects `DebugElement` nodes with a [standard CSS selector](https://developer.mozilla.org/docs/Learn/CSS/Building_blocks/Selectors 'CSS selectors'). * The query returns a `DebugElement` for the paragraph. * You must unwrap that result to get the paragraph element. When you're filtering by CSS selector and only testing properties of a browser's *native element*, the `By.css` approach might be overkill. It's often more straightforward and clear to filter with a standard `HTMLElement` method such as `querySelector()` or `querySelectorAll()`.
{ "end_byte": 10895, "start_byte": 9094, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/components-basics.md" }
angular/adev/src/content/guide/testing/services.md_0_7685
# Testing services To check that your services are working as you intend, you can write tests specifically for them. Services are often the smoothest files to unit test. Here are some synchronous and asynchronous unit tests of the `ValueService` written without assistance from Angular testing utilities. <docs-code header="app/demo/demo.spec.ts" path="adev/src/content/examples/testing/src/app/demo/demo.spec.ts" visibleRegion="ValueService"/> ## Services with dependencies Services often depend on other services that Angular injects into the constructor. In many cases, you can create and *inject* these dependencies by hand while calling the service's constructor. The `MasterService` is a simple example: <docs-code header="app/demo/demo.ts" path="adev/src/content/examples/testing/src/app/demo/demo.ts" visibleRegion="MasterService"/> `MasterService` delegates its only method, `getValue`, to the injected `ValueService`. Here are several ways to test it. <docs-code header="app/demo/demo.spec.ts" path="adev/src/content/examples/testing/src/app/demo/demo.spec.ts" visibleRegion="MasterService"/> The first test creates a `ValueService` with `new` and passes it to the `MasterService` constructor. However, injecting the real service rarely works well as most dependent services are difficult to create and control. Instead, mock the dependency, use a dummy value, or create a [spy](https://jasmine.github.io/tutorials/your_first_suite#section-Spies) on the pertinent service method. HELPFUL: Prefer spies as they are usually the best way to mock services. These standard testing techniques are great for unit testing services in isolation. However, you almost always inject services into application classes using Angular dependency injection and you should have tests that reflect that usage pattern. Angular testing utilities make it straightforward to investigate how injected services behave. ## Testing services with the `TestBed` Your application relies on Angular [dependency injection (DI)](guide/di) to create services. When a service has a dependent service, DI finds or creates that dependent service. And if that dependent service has its own dependencies, DI finds-or-creates them as well. As a service *consumer*, you don't worry about any of this. You don't worry about the order of constructor arguments or how they're created. As a service *tester*, you must at least think about the first level of service dependencies but you *can* let Angular DI do the service creation and deal with constructor argument order when you use the `TestBed` testing utility to provide and create services. ## Angular `TestBed` The `TestBed` is the most important of the Angular testing utilities. The `TestBed` creates a dynamically-constructed Angular *test* module that emulates an Angular [@NgModule](guide/ngmodules). The `TestBed.configureTestingModule()` method takes a metadata object that can have most of the properties of an [@NgModule](guide/ngmodules). To test a service, you set the `providers` metadata property with an array of the services that you'll test or mock. <docs-code header="app/demo/demo.testbed.spec.ts (provide ValueService in beforeEach)" path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="value-service-before-each"/> Then inject it inside a test by calling `TestBed.inject()` with the service class as the argument. HELPFUL: `TestBed.get()` was deprecated as of Angular version 9. To help minimize breaking changes, Angular introduces a new function called `TestBed.inject()`, which you should use instead. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="value-service-inject-it"/> Or inside the `beforeEach()` if you prefer to inject the service as part of your setup. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="value-service-inject-before-each"> </docs-code> When testing a service with a dependency, provide the mock in the `providers` array. In the following example, the mock is a spy object. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="master-service-before-each"/> The test consumes that spy in the same way it did earlier. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="master-service-it"/> ## Testing without `beforeEach()` Most test suites in this guide call `beforeEach()` to set the preconditions for each `it()` test and rely on the `TestBed` to create classes and inject services. There's another school of testing that never calls `beforeEach()` and prefers to create classes explicitly rather than use the `TestBed`. Here's how you might rewrite one of the `MasterService` tests in that style. Begin by putting re-usable, preparatory code in a *setup* function instead of `beforeEach()`. <docs-code header="app/demo/demo.spec.ts (setup)" path="adev/src/content/examples/testing/src/app/demo/demo.spec.ts" visibleRegion="no-before-each-setup"/> The `setup()` function returns an object literal with the variables, such as `masterService`, that a test might reference. You don't define *semi-global* variables \(for example, `let masterService: MasterService`\) in the body of the `describe()`. Then each test invokes `setup()` in its first line, before continuing with steps that manipulate the test subject and assert expectations. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.spec.ts" visibleRegion="no-before-each-test"/> Notice how the test uses [*destructuring assignment*](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to extract the setup variables that it needs. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.spec.ts" visibleRegion="no-before-each-setup-call"/> Many developers feel this approach is cleaner and more explicit than the traditional `beforeEach()` style. Although this testing guide follows the traditional style and the default [CLI schematics](https://github.com/angular/angular-cli) generate test files with `beforeEach()` and `TestBed`, feel free to adopt *this alternative approach* in your own projects. ## Testing HTTP services Data services that make HTTP calls to remote servers typically inject and delegate to the Angular [`HttpClient`](guide/http/testing) service for XHR calls. You can test a data service with an injected `HttpClient` spy as you would test any service with a dependency. <docs-code header="app/model/hero.service.spec.ts (tests with spies)" path="adev/src/content/examples/testing/src/app/model/hero.service.spec.ts" visibleRegion="test-with-spies"/> IMPORTANT: The `HeroService` methods return `Observables`. You must *subscribe* to an observable to \(a\) cause it to execute and \(b\) assert that the method succeeds or fails. The `subscribe()` method takes a success \(`next`\) and fail \(`error`\) callback. Make sure you provide *both* callbacks so that you capture errors. Neglecting to do so produces an asynchronous uncaught observable error that the test runner will likely attribute to a completely different test. ## `HttpClientTestingModule` Extended interactions between a data service and the `HttpClient` can be complex and difficult to mock with spies. The `HttpClientTestingModule` can make these testing scenarios more manageable. While the *code sample* accompanying this guide demonstrates `HttpClientTestingModule`, this page defers to the [Http guide](guide/http/testing), which covers testing with the `HttpClientTestingModule` in detail.
{ "end_byte": 7685, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/services.md" }
angular/adev/src/content/guide/testing/BUILD.bazel_0_3451
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "testing", srcs = glob([ "*.md", ]), data = [ "//adev/src/content/examples/testing:src/app/about/about.component.spec.ts", "//adev/src/content/examples/testing:src/app/about/about.component.ts", "//adev/src/content/examples/testing:src/app/app.component.html", "//adev/src/content/examples/testing:src/app/app.component.spec.ts", "//adev/src/content/examples/testing:src/app/banner/banner.component.detect-changes.spec.ts", "//adev/src/content/examples/testing:src/app/banner/banner.component.spec.ts", "//adev/src/content/examples/testing:src/app/banner/banner.component.ts", "//adev/src/content/examples/testing:src/app/banner/banner-external.component.spec.ts", "//adev/src/content/examples/testing:src/app/banner/banner-external.component.ts", "//adev/src/content/examples/testing:src/app/banner/banner-initial.component.spec.ts", "//adev/src/content/examples/testing:src/app/dashboard/dashboard.component.html", "//adev/src/content/examples/testing:src/app/dashboard/dashboard.component.spec.ts", "//adev/src/content/examples/testing:src/app/dashboard/dashboard.component.ts", "//adev/src/content/examples/testing:src/app/dashboard/dashboard-hero.component.spec.ts", "//adev/src/content/examples/testing:src/app/dashboard/dashboard-hero.component.ts", "//adev/src/content/examples/testing:src/app/demo/async-helper.spec.ts", "//adev/src/content/examples/testing:src/app/demo/demo.spec.ts", "//adev/src/content/examples/testing:src/app/demo/demo.testbed.spec.ts", "//adev/src/content/examples/testing:src/app/demo/demo.ts", "//adev/src/content/examples/testing:src/app/hero/hero-detail.component.html", "//adev/src/content/examples/testing:src/app/hero/hero-detail.component.spec.ts", "//adev/src/content/examples/testing:src/app/hero/hero-detail.component.ts", "//adev/src/content/examples/testing:src/app/hero/hero-detail.service.ts", "//adev/src/content/examples/testing:src/app/hero/hero-list.component.spec.ts", "//adev/src/content/examples/testing:src/app/model/hero.service.spec.ts", "//adev/src/content/examples/testing:src/app/shared/canvas.component.spec.ts", "//adev/src/content/examples/testing:src/app/shared/canvas.component.ts", "//adev/src/content/examples/testing:src/app/shared/highlight.directive.spec.ts", "//adev/src/content/examples/testing:src/app/shared/highlight.directive.ts", "//adev/src/content/examples/testing:src/app/shared/title-case.pipe.spec.ts", "//adev/src/content/examples/testing:src/app/shared/title-case.pipe.ts", "//adev/src/content/examples/testing:src/app/twain/twain.component.marbles.spec.ts", "//adev/src/content/examples/testing:src/app/twain/twain.component.spec.ts", "//adev/src/content/examples/testing:src/app/twain/twain.component.ts", "//adev/src/content/examples/testing:src/app/welcome/welcome.component.spec.ts", "//adev/src/content/examples/testing:src/app/welcome/welcome.component.ts", "//adev/src/content/examples/testing:src/testing/async-observable-helpers.ts", "//adev/src/content/examples/testing:src/testing/index.ts", ], visibility = ["//adev:__subpackages__"], )
{ "end_byte": 3451, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/BUILD.bazel" }
angular/adev/src/content/guide/testing/utility-apis.md_0_14225
# Testing Utility APIs This page describes the most useful Angular testing features. The Angular testing utilities include the `TestBed`, the `ComponentFixture`, and a handful of functions that control the test environment. The [`TestBed`](#testbed-api-summary) and [`ComponentFixture`](#component-fixture-api-summary) classes are covered separately. Here's a summary of the stand-alone functions, in order of likely utility: | Function | Details | |:--- |:--- | | `waitForAsync` | Runs the body of a test \(`it`\) or setup \(`beforeEach`\) function within a special *async test zone*. See [waitForAsync](guide/testing/components-scenarios#waitForAsync). | | `fakeAsync` | Runs the body of a test \(`it`\) within a special *fakeAsync test zone*, enabling a linear control flow coding style. See [fakeAsync](guide/testing/components-scenarios#fake-async). | | `tick` | Simulates the passage of time and the completion of pending asynchronous activities by flushing both *timer* and *micro-task* queues within the *fakeAsync test zone*. The curious, dedicated reader might enjoy this lengthy blog post, ["*Tasks, microtasks, queues and schedules*"](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules). Accepts an optional argument that moves the virtual clock forward by the specified number of milliseconds, clearing asynchronous activities scheduled within that timeframe. See [tick](guide/testing/components-scenarios#tick). | | `inject` | Injects one or more services from the current `TestBed` injector into a test function. It cannot inject a service provided by the component itself. See discussion of the [debugElement.injector](guide/testing/components-scenarios#get-injected-services). | | `discardPeriodicTasks` | When a `fakeAsync()` test ends with pending timer event *tasks* \(queued `setTimeOut` and `setInterval` callbacks\), the test fails with a clear error message. <br /> In general, a test should end with no queued tasks. When pending timer tasks are expected, call `discardPeriodicTasks` to flush the *task* queue and avoid the error. | | `flushMicrotasks` | When a `fakeAsync()` test ends with pending *micro-tasks* such as unresolved promises, the test fails with a clear error message. <br /> In general, a test should wait for micro-tasks to finish. When pending microtasks are expected, call `flushMicrotasks` to flush the *micro-task* queue and avoid the error. | | `ComponentFixtureAutoDetect` | A provider token for a service that turns on [automatic change detection](guide/testing/components-scenarios#automatic-change-detection). | | `getTestBed` | Gets the current instance of the `TestBed`. Usually unnecessary because the static class methods of the `TestBed` class are typically sufficient. The `TestBed` instance exposes a few rarely used members that are not available as static methods. | ## `TestBed` class summary The `TestBed` class is one of the principal Angular testing utilities. Its API is quite large and can be overwhelming until you've explored it, a little at a time. Read the early part of this guide first to get the basics before trying to absorb the full API. The module definition passed to `configureTestingModule` is a subset of the `@NgModule` metadata properties. <docs-code language="javascript"> type TestModuleMetadata = { providers?: any[]; declarations?: any[]; imports?: any[]; schemas?: Array<SchemaMetadata | any[]>; }; </docs-code> Each override method takes a `MetadataOverride<T>` where `T` is the kind of metadata appropriate to the method, that is, the parameter of an `@NgModule`, `@Component`, `@Directive`, or `@Pipe`. <docs-code language="javascript"> type MetadataOverride<T> = { add?: Partial<T>; remove?: Partial<T>; set?: Partial<T>; }; </docs-code> The `TestBed` API consists of static class methods that either update or reference a *global* instance of the `TestBed`. Internally, all static methods cover methods of the current runtime `TestBed` instance, which is also returned by the `getTestBed()` function. Call `TestBed` methods *within* a `beforeEach()` to ensure a fresh start before each individual test. Here are the most important static methods, in order of likely utility. | Methods | Details | |:--- |:--- | | `configureTestingModule` | The testing shims \(`karma-test-shim`, `browser-test-shim`\) establish the [initial test environment](guide/testing) and a default testing module. The default testing module is configured with basic declaratives and some Angular service substitutes that every tester needs. <br /> Call `configureTestingModule` to refine the testing module configuration for a particular set of tests by adding and removing imports, declarations \(of components, directives, and pipes\), and providers. | | `compileComponents` | Compile the testing module asynchronously after you've finished configuring it. You **must** call this method if *any* of the testing module components have a `templateUrl` or `styleUrls` because fetching component template and style files is necessarily asynchronous. See [compileComponents](guide/testing/components-scenarios#calling-compilecomponents). <br /> After calling `compileComponents`, the `TestBed` configuration is frozen for the duration of the current spec. | | `createComponent<T>` | Create an instance of a component of type `T` based on the current `TestBed` configuration. After calling `createComponent`, the `TestBed` configuration is frozen for the duration of the current spec. | | `overrideModule` | Replace metadata for the given `NgModule`. Recall that modules can import other modules. The `overrideModule` method can reach deeply into the current testing module to modify one of these inner modules. | | `overrideComponent` | Replace metadata for the given component class, which could be nested deeply within an inner module. | | `overrideDirective` | Replace metadata for the given directive class, which could be nested deeply within an inner module. | | `overridePipe` | Replace metadata for the given pipe class, which could be nested deeply within an inner module. | | `inject` | Retrieve a service from the current `TestBed` injector. The `inject` function is often adequate for this purpose. But `inject` throws an error if it can't provide the service. <br /> What if the service is optional? <br /> The `TestBed.inject()` method takes an optional second parameter, the object to return if Angular can't find the provider \(`null` in this example\): <docs-code header="app/demo/demo.testbed.spec.ts" path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="testbed-get-w-null"/> After calling `TestBed.inject`, the `TestBed` configuration is frozen for the duration of the current spec. | | `initTestEnvironment` | Initialize the testing environment for the entire test run. <br /> The testing shims \(`karma-test-shim`, `browser-test-shim`\) call it for you so there is rarely a reason for you to call it yourself. <br /> Call this method *exactly once*. To change this default in the middle of a test run, call `resetTestEnvironment` first. <br /> Specify the Angular compiler factory, a `PlatformRef`, and a default Angular testing module. Alternatives for non-browser platforms are available in the general form `@angular/platform-<platform_name>/testing/<platform_name>`. | | `resetTestEnvironment` | Reset the initial test environment, including the default testing module. | A few of the `TestBed` instance methods are not covered by static `TestBed` *class* methods. These are rarely needed.
{ "end_byte": 14225, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/utility-apis.md" }
angular/adev/src/content/guide/testing/utility-apis.md_14225_27047
## The `ComponentFixture` The `TestBed.createComponent<T>` creates an instance of the component `T` and returns a strongly typed `ComponentFixture` for that component. The `ComponentFixture` properties and methods provide access to the component, its DOM representation, and aspects of its Angular environment. ### `ComponentFixture` properties Here are the most important properties for testers, in order of likely utility. | Properties | Details | |:--- |:--- | | `componentInstance` | The instance of the component class created by `TestBed.createComponent`. | | `debugElement` | The `DebugElement` associated with the root element of the component. <br /> The `debugElement` provides insight into the component and its DOM element during test and debugging. It's a critical property for testers. The most interesting members are covered [below](#debug-element-details). | | `nativeElement` | The native DOM element at the root of the component. | | `changeDetectorRef` | The `ChangeDetectorRef` for the component. <br /> The `ChangeDetectorRef` is most valuable when testing a component that has the `ChangeDetectionStrategy.OnPush` method or the component's change detection is under your programmatic control. | ### `ComponentFixture` methods The *fixture* methods cause Angular to perform certain tasks on the component tree. Call these method to trigger Angular behavior in response to simulated user action. Here are the most useful methods for testers. | Methods | Details | |:--- |:--- | | `detectChanges` | Trigger a change detection cycle for the component. <br /> Call it to initialize the component \(it calls `ngOnInit`\) and after your test code, change the component's data bound property values. Angular can't see that you've changed `personComponent.name` and won't update the `name` binding until you call `detectChanges`. <br /> Runs `checkNoChanges` afterwards to confirm that there are no circular updates unless called as `detectChanges(false)`; | | `autoDetectChanges` | Set this to `true` when you want the fixture to detect changes automatically. <br /> When autodetect is `true`, the test fixture calls `detectChanges` immediately after creating the component. Then it listens for pertinent zone events and calls `detectChanges` accordingly. When your test code modifies component property values directly, you probably still have to call `fixture.detectChanges` to trigger data binding updates. <br /> The default is `false`. Testers who prefer fine control over test behavior tend to keep it `false`. | | `checkNoChanges` | Do a change detection run to make sure there are no pending changes. Throws an exceptions if there are. | | `isStable` | If the fixture is currently *stable*, returns `true`. If there are async tasks that have not completed, returns `false`. | | `whenStable` | Returns a promise that resolves when the fixture is stable. <br /> To resume testing after completion of asynchronous activity or asynchronous change detection, hook that promise. See [whenStable](guide/testing/components-scenarios#when-stable). | | `destroy` | Trigger component destruction. | #### `DebugElement` The `DebugElement` provides crucial insights into the component's DOM representation. From the test root component's `DebugElement` returned by `fixture.debugElement`, you can walk \(and query\) the fixture's entire element and component subtrees. Here are the most useful `DebugElement` members for testers, in approximate order of utility: | Members | Details | |:--- |:--- | | `nativeElement` | The corresponding DOM element in the browser | | `query` | Calling `query(predicate: Predicate<DebugElement>)` returns the first `DebugElement` that matches the [predicate](#query-predicate) at any depth in the subtree. | | `queryAll` | Calling `queryAll(predicate: Predicate<DebugElement>)` returns all `DebugElements` that matches the [predicate](#query-predicate) at any depth in subtree. | | `injector` | The host dependency injector. For example, the root element's component instance injector. | | `componentInstance` | The element's own component instance, if it has one. | | `context` | An object that provides parent context for this element. Often an ancestor component instance that governs this element. <br /> When an element is repeated within `*ngFor`, the context is an `NgForOf` whose `$implicit` property is the value of the row instance value. For example, the `hero` in `*ngFor="let hero of heroes"`. | | `children` | The immediate `DebugElement` children. Walk the tree by descending through `children`. `DebugElement` also has `childNodes`, a list of `DebugNode` objects. `DebugElement` derives from `DebugNode` objects and there are often more nodes than elements. Testers can usually ignore plain nodes. | | `parent` | The `DebugElement` parent. Null if this is the root element. | | `name` | The element tag name, if it is an element. | | `triggerEventHandler` | Triggers the event by its name if there is a corresponding listener in the element's `listeners` collection. The second parameter is the *event object* expected by the handler. See [triggerEventHandler](guide/testing/components-scenarios#trigger-event-handler). <br /> If the event lacks a listener or there's some other problem, consider calling `nativeElement.dispatchEvent(eventObject)`. | | `listeners` | The callbacks attached to the component's `@Output` properties and/or the element's event properties. | | `providerTokens` | This component's injector lookup tokens. Includes the component itself plus the tokens that the component lists in its `providers` metadata. | | `source` | Where to find this element in the source component template. | | `references` | Dictionary of objects associated with template local variables \(for example, `#foo`\), keyed by the local variable name. | The `DebugElement.query(predicate)` and `DebugElement.queryAll(predicate)` methods take a predicate that filters the source element's subtree for matching `DebugElement`. The predicate is any method that takes a `DebugElement` and returns a *truthy* value. The following example finds all `DebugElements` with a reference to a template local variable named "content": <docs-code header="app/demo/demo.testbed.spec.ts" path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="custom-predicate"/> The Angular `By` class has three static methods for common predicates: | Static method | Details | |:--- |:--- | | `By.all` | Return all elements | | `By.css(selector)` | Return elements with matching CSS selectors | | `By.directive(directive)` | Return elements that Angular matched to an instance of the directive class | <docs-code header="app/hero/hero-list.component.spec.ts" path="adev/src/content/examples/testing/src/app/hero/hero-list.component.spec.ts" visibleRegion="by"/>
{ "end_byte": 27047, "start_byte": 14225, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/utility-apis.md" }
angular/adev/src/content/guide/testing/code-coverage.md_0_2050
# Find out how much code you're testing The Angular CLI can run unit tests and create code coverage reports. Code coverage reports show you any parts of your code base that might not be properly tested by your unit tests. To generate a coverage report run the following command in the root of your project. <docs-code language="shell"> ng test --no-watch --code-coverage </docs-code> When the tests are complete, the command creates a new `/coverage` directory in the project. Open the `index.html` file to see a report with your source code and code coverage values. If you want to create code-coverage reports every time you test, set the following option in the Angular CLI configuration file, `angular.json`: <docs-code language="json"> "test": { "options": { "codeCoverage": true } } </docs-code> ## Code coverage enforcement The code coverage percentages let you estimate how much of your code is tested. If your team decides on a set minimum amount to be unit tested, enforce this minimum with the Angular CLI. For example, suppose you want the code base to have a minimum of 80% code coverage. To enable this, open the [Karma](https://karma-runner.github.io) test platform configuration file, `karma.conf.js`, and add the `check` property in the `coverageReporter:` key. <docs-code language="javascript"> coverageReporter: { dir: require('path').join(__dirname, './coverage/<project-name>'), subdir: '.', reporters: [ { type: 'html' }, { type: 'text-summary' } ], check: { global: { statements: 80, branches: 80, functions: 80, lines: 80 } } } </docs-code> HELPFUL: Read more about creating and fine tuning Karma configuration in the [testing guide](guide/testing#configuration). The `check` property causes the tool to enforce a minimum of 80% code coverage when the unit tests are run in the project. Read more on coverage configuration options in the [karma coverage documentation](https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md).
{ "end_byte": 2050, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/code-coverage.md" }
angular/adev/src/content/guide/testing/debugging.md_0_822
# Debugging tests If your tests aren't working as you expect them to, you can inspect and debug them in the browser. Debug specs in the browser in the same way that you debug an application. 1. Reveal the Karma browser window. See [Set up testing](guide/testing#set-up-testing) if you need help with this step. 1. Click the **DEBUG** button to open a new browser tab and re-run the tests. 1. Open the browser's **Developer Tools**. On Windows, press `Ctrl-Shift-I`. On macOS, press `Command-Option-I`. 1. Pick the **Sources** section. 1. Press `Control/Command-P`, and then start typing the name of your test file to open it. 1. Set a breakpoint in the test. 1. Refresh the browser, and notice how it stops at the breakpoint. <img alt="Karma debugging" src="assets/images/guide/testing/karma-1st-spec-debug.png">
{ "end_byte": 822, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/debugging.md" }
angular/adev/src/content/guide/testing/components-scenarios.md_0_7030
# Component testing scenarios This guide explores common component testing use cases. ## Component binding In the example application, the `BannerComponent` presents static title text in the HTML template. After a few changes, the `BannerComponent` presents a dynamic title by binding to the component's `title` property like this. <docs-code header="app/banner/banner.component.ts" path="adev/src/content/examples/testing/src/app/banner/banner.component.ts" visibleRegion="component"/> As minimal as this is, you decide to add a test to confirm that component actually displays the right content where you think it should. ### Query for the `<h1>` You'll write a sequence of tests that inspect the value of the `<h1>` element that wraps the *title* property interpolation binding. You update the `beforeEach` to find that element with a standard HTML `querySelector` and assign it to the `h1` variable. <docs-code header="app/banner/banner.component.spec.ts (setup)" path="adev/src/content/examples/testing/src/app/banner/banner.component.spec.ts" visibleRegion="setup"/> ### `createComponent()` does not bind data For your first test you'd like to see that the screen displays the default `title`. Your instinct is to write a test that immediately inspects the `<h1>` like this: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner.component.spec.ts" visibleRegion="expect-h1-default-v1"/> *That test fails* with the message: <docs-code language="javascript"> expected '' to contain 'Test Tour of Heroes'. </docs-code> Binding happens when Angular performs **change detection**. In production, change detection kicks in automatically when Angular creates a component or the user enters a keystroke, for example. The `TestBed.createComponent` does not trigger change detection by default; a fact confirmed in the revised test: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner.component.spec.ts" visibleRegion="test-w-o-detect-changes"/> ### `detectChanges()` You can tell the `TestBed` to perform data binding by calling `fixture.detectChanges()`. Only then does the `<h1>` have the expected title. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner.component.spec.ts" visibleRegion="expect-h1-default"/> Delayed change detection is intentional and useful. It gives the tester an opportunity to inspect and change the state of the component *before Angular initiates data binding and calls [lifecycle hooks](guide/components/lifecycle)*. Here's another test that changes the component's `title` property *before* calling `fixture.detectChanges()`. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner.component.spec.ts" visibleRegion="after-change"/> ### Automatic change detection The `BannerComponent` tests frequently call `detectChanges`. Many testers prefer that the Angular test environment run change detection automatically like it does in production. That's possible by configuring the `TestBed` with the `ComponentFixtureAutoDetect` provider. First import it from the testing utility library: <docs-code header="app/banner/banner.component.detect-changes.spec.ts (import)" path="adev/src/content/examples/testing/src/app/banner/banner.component.detect-changes.spec.ts" visibleRegion="import-ComponentFixtureAutoDetect"/> Then add it to the `providers` array of the testing module configuration: <docs-code header="app/banner/banner.component.detect-changes.spec.ts (AutoDetect)" path="adev/src/content/examples/testing/src/app/banner/banner.component.detect-changes.spec.ts" visibleRegion="auto-detect"/> HELPFUL: You can also use the `fixture.autoDetectChanges()` function instead if you only want to enable automatic change detection after making updates to the state of the fixture's component. In addition, automatic change detection is on by default when using `provideExperimentalZonelessChangeDetection` and turning it off is not recommended. Here are three tests that illustrate how automatic change detection works. <docs-code header="app/banner/banner.component.detect-changes.spec.ts (AutoDetect Tests)" path="adev/src/content/examples/testing/src/app/banner/banner.component.detect-changes.spec.ts" visibleRegion="auto-detect-tests"/> The first test shows the benefit of automatic change detection. The second and third test reveal an important limitation. The Angular testing environment does not run change detection synchronously when updates happen inside the test case that changed the component's `title`. The test must call `await fixture.whenStable` to wait for another of change detection. HELPFUL: Angular does not know about direct updates to values that are not signals. The easiest way to ensure that change detection will be scheduled is to use signals for values read in the template. ### Change an input value with `dispatchEvent()` To simulate user input, find the input element and set its `value` property. But there is an essential, intermediate step. Angular doesn't know that you set the input element's `value` property. It won't read that property until you raise the element's `input` event by calling `dispatchEvent()`. The following example demonstrates the proper sequence. <docs-code header="app/hero/hero-detail.component.spec.ts (pipe test)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="title-case-pipe"/> ## Component with external files The preceding `BannerComponent` is defined with an *inline template* and *inline css*, specified in the `@Component.template` and `@Component.styles` properties respectively. Many components specify *external templates* and *external css* with the `@Component.templateUrl` and `@Component.styleUrls` properties respectively, as the following variant of `BannerComponent` does. <docs-code header="app/banner/banner-external.component.ts (metadata)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.ts" visibleRegion="metadata"/> This syntax tells the Angular compiler to read the external files during component compilation. That's not a problem when you run the CLI `ng test` command because it *compiles the application before running the tests*. However, if you run the tests in a **non-CLI environment**, tests of this component might fail. For example, if you run the `BannerComponent` tests in a web coding environment such as [plunker](https://plnkr.co), you'll see a message like this one: <docs-code hideCopy language="shell"> Error: This test module uses the component BannerComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test. </docs-code> You get this test failure message when the runtime environment compiles the source code *during the tests themselves*. To correct the problem, call `compileComponents()` as explained in the following [Calling compileComponents](#calling-compilecomponents) section.
{ "end_byte": 7030, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/components-scenarios.md" }
angular/adev/src/content/guide/testing/components-scenarios.md_7030_10529
## Component with a dependency Components often have service dependencies. The `WelcomeComponent` displays a welcome message to the logged-in user. It knows who the user is based on a property of the injected `UserService`: <docs-code header="app/welcome/welcome.component.ts" path="adev/src/content/examples/testing/src/app/welcome/welcome.component.ts"/> The `WelcomeComponent` has decision logic that interacts with the service, logic that makes this component worth testing. ### Provide service test doubles A *component-under-test* doesn't have to be provided with real services. Injecting the real `UserService` could be difficult. The real service might ask the user for login credentials and attempt to reach an authentication server. These behaviors can be hard to intercept. Be aware that using test doubles makes the test behave differently from production so use them sparingly. ### Get injected services The tests need access to the `UserService` injected into the `WelcomeComponent`. Angular has a hierarchical injection system. There can be injectors at multiple levels, from the root injector created by the `TestBed` down through the component tree. The safest way to get the injected service, the way that ***always works***, is to **get it from the injector of the *component-under-test***. The component injector is a property of the fixture's `DebugElement`. <docs-code header="WelcomeComponent's injector" path="adev/src/content/examples/testing/src/app/welcome/welcome.component.spec.ts" visibleRegion="injected-service"/> HELPFUL: This is _usually_ not necessary. Services are often provided in the root or the TestBed overrides and can be retrieved more easily with `TestBed.inject()` (see below). ### `TestBed.inject()` This is easier to remember and less verbose than retrieving a service using the fixture's `DebugElement`. In this test suite, the *only* provider of `UserService` is the root testing module, so it is safe to call `TestBed.inject()` as follows: <docs-code header="TestBed injector" path="adev/src/content/examples/testing/src/app/welcome/welcome.component.spec.ts" visibleRegion="inject-from-testbed" /> HELPFUL: For a use case in which `TestBed.inject()` does not work, see the [*Override component providers*](#override-component-providers) section that explains when and why you must get the service from the component's injector instead. ### Final setup and tests Here's the complete `beforeEach()`, using `TestBed.inject()`: <docs-code header="app/welcome/welcome.component.spec.ts" path="adev/src/content/examples/testing/src/app/welcome/welcome.component.spec.ts" visibleRegion="setup"/> And here are some tests: <docs-code header="app/welcome/welcome.component.spec.ts" path="adev/src/content/examples/testing/src/app/welcome/welcome.component.spec.ts" visibleRegion="tests"/> The first is a sanity test; it confirms that the `UserService` is called and working. HELPFUL: The withContext function \(for example, `'expected name'`\) is an optional failure label. If the expectation fails, Jasmine appends this label to the expectation failure message. In a spec with multiple expectations, it can help clarify what went wrong and which expectation failed. The remaining tests confirm the logic of the component when the service returns different values. The second test validates the effect of changing the user name. The third test checks that the component displays the proper message when there is no logged-in user.
{ "end_byte": 10529, "start_byte": 7030, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/components-scenarios.md" }
angular/adev/src/content/guide/testing/components-scenarios.md_10529_19042
## Component with async service In this sample, the `AboutComponent` template hosts a `TwainComponent`. The `TwainComponent` displays Mark Twain quotes. <docs-code header="app/twain/twain.component.ts (template)" path="adev/src/content/examples/testing/src/app/twain/twain.component.ts" visibleRegion="template" /> HELPFUL: The value of the component's `quote` property passes through an `AsyncPipe`. That means the property returns either a `Promise` or an `Observable`. In this example, the `TwainComponent.getQuote()` method tells you that the `quote` property returns an `Observable`. <docs-code header="app/twain/twain.component.ts (getQuote)" path="adev/src/content/examples/testing/src/app/twain/twain.component.ts" visibleRegion="get-quote"/> The `TwainComponent` gets quotes from an injected `TwainService`. The component starts the returned `Observable` with a placeholder value \(`'...'`\), before the service can return its first quote. The `catchError` intercepts service errors, prepares an error message, and returns the placeholder value on the success channel. These are all features you'll want to test. ### Testing with a spy When testing a component, only the service's public API should matter. In general, tests themselves should not make calls to remote servers. They should emulate such calls. The setup in this `app/twain/twain.component.spec.ts` shows one way to do that: <docs-code header="app/twain/twain.component.spec.ts (setup)" path="adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts" visibleRegion="setup"/> Focus on the spy. <docs-code path="adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts" visibleRegion="spy"/> The spy is designed such that any call to `getQuote` receives an observable with a test quote. Unlike the real `getQuote()` method, this spy bypasses the server and returns a synchronous observable whose value is available immediately. You can write many useful tests with this spy, even though its `Observable` is synchronous. HELPFUL: It is best to limit the usage of spies to only what is necessary for the test. Creating mocks or spies for more than what's necessary can be brittle. As the component and injectable evolves, the unrelated tests can fail because they no longer mock enough behaviors that would otherwise not affect the test. ### Async test with `fakeAsync()` To use `fakeAsync()` functionality, you must import `zone.js/testing` in your test setup file. If you created your project with the Angular CLI, `zone-testing` is already imported in `src/test.ts`. The following test confirms the expected behavior when the service returns an `ErrorObservable`. <docs-code path="adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts" visibleRegion="error-test"/> HELPFUL: The `it()` function receives an argument of the following form. <docs-code language="javascript"> fakeAsync(() => { /*test body*/ }) </docs-code> The `fakeAsync()` function enables a linear coding style by running the test body in a special `fakeAsync test zone`. The test body appears to be synchronous. There is no nested syntax \(like a `Promise.then()`\) to disrupt the flow of control. HELPFUL: Limitation: The `fakeAsync()` function won't work if the test body makes an `XMLHttpRequest` \(XHR\) call. XHR calls within a test are rare, but if you need to call XHR, see the [`waitForAsync()`](#waitForAsync) section. IMPORTANT: Be aware that asynchronous tasks that happen inside the `fakeAsync` zone need to be manually executed with `flush` or `tick`. If you attempt to wait for them to complete (i.e. using `fixture.whenStable`) without using the `fakeAsync` test helpers to advance time, your test will likely fail. See below for more information. ### The `tick()` function You do have to call [tick()](api/core/testing/tick) to advance the virtual clock. Calling [tick()](api/core/testing/tick) simulates the passage of time until all pending asynchronous activities finish. In this case, it waits for the observable's `setTimeout()`. The [tick()](api/core/testing/tick) function accepts `millis` and `tickOptions` as parameters. The `millis` parameter specifies how much the virtual clock advances and defaults to `0` if not provided. For example, if you have a `setTimeout(fn, 100)` in a `fakeAsync()` test, you need to use `tick(100)` to trigger the fn callback. The optional `tickOptions` parameter has a property named `processNewMacroTasksSynchronously`. The `processNewMacroTasksSynchronously` property represents whether to invoke new generated macro tasks when ticking and defaults to `true`. <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-tick"/> The [tick()](api/core/testing/tick) function is one of the Angular testing utilities that you import with `TestBed`. It's a companion to `fakeAsync()` and you can only call it within a `fakeAsync()` body. ### tickOptions In this example, you have a new macro task, the nested `setTimeout` function. By default, when the `tick` is setTimeout, `outside` and `nested` will both be triggered. <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-tick-new-macro-task-sync"/> In some case, you don't want to trigger the new macro task when ticking. You can use `tick(millis, {processNewMacroTasksSynchronously: false})` to not invoke a new macro task. <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-tick-new-macro-task-async"/> ### Comparing dates inside fakeAsync() `fakeAsync()` simulates passage of time, which lets you calculate the difference between dates inside `fakeAsync()`. <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-date"/> ### jasmine.clock with fakeAsync() Jasmine also provides a `clock` feature to mock dates. Angular automatically runs tests that are run after `jasmine.clock().install()` is called inside a `fakeAsync()` method until `jasmine.clock().uninstall()` is called. `fakeAsync()` is not needed and throws an error if nested. By default, this feature is disabled. To enable it, set a global flag before importing `zone-testing`. If you use the Angular CLI, configure this flag in `src/test.ts`. <docs-code language="typescript"> [window as any]('&lowbar;&lowbar;zone&lowbar;symbol__fakeAsyncPatchLock') = true; import 'zone.js/testing'; </docs-code> <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-clock"/> ### Using the RxJS scheduler inside fakeAsync() You can also use RxJS scheduler in `fakeAsync()` just like using `setTimeout()` or `setInterval()`, but you need to import `zone.js/plugins/zone-patch-rxjs-fake-async` to patch RxJS scheduler. <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-rxjs"/> ### Support more macroTasks By default, `fakeAsync()` supports the following macro tasks. * `setTimeout` * `setInterval` * `requestAnimationFrame` * `webkitRequestAnimationFrame` * `mozRequestAnimationFrame` If you run other macro tasks such as `HTMLCanvasElement.toBlob()`, an *"Unknown macroTask scheduled in fake async test"* error is thrown. <docs-code-multifile> <docs-code header="src/app/shared/canvas.component.spec.ts (failing)" path="adev/src/content/examples/testing/src/app/shared/canvas.component.spec.ts" visibleRegion="without-toBlob-macrotask"/> <docs-code header="src/app/shared/canvas.component.ts" path="adev/src/content/examples/testing/src/app/shared/canvas.component.ts" visibleRegion="main"/> </docs-code-multifile> If you want to support such a case, you need to define the macro task you want to support in `beforeEach()`. For example: <docs-code header="src/app/shared/canvas.component.spec.ts (excerpt)" path="adev/src/content/examples/testing/src/app/shared/canvas.component.spec.ts" visibleRegion="enable-toBlob-macrotask"/> HELPFUL: In order to make the `<canvas>` element Zone.js-aware in your app, you need to import the `zone-patch-canvas` patch \(either in `polyfills.ts` or in the specific file that uses `<canvas>`\): <docs-code header="src/polyfills.ts or src/app/shared/canvas.component.ts" path="adev/src/content/examples/testing/src/app/shared/canvas.component.ts" visibleRegion="import-canvas-patch"/>
{ "end_byte": 19042, "start_byte": 10529, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/components-scenarios.md" }
angular/adev/src/content/guide/testing/components-scenarios.md_19042_28043
### Async observables You might be satisfied with the test coverage of these tests. However, you might be troubled by the fact that the real service doesn't quite behave this way. The real service sends requests to a remote server. A server takes time to respond and the response certainly won't be available immediately as in the previous two tests. Your tests will reflect the real world more faithfully if you return an *asynchronous* observable from the `getQuote()` spy like this. <docs-code path="adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts" visibleRegion="async-setup"/> ### Async observable helpers The async observable was produced by an `asyncData` helper. The `asyncData` helper is a utility function that you'll have to write yourself, or copy this one from the sample code. <docs-code header="testing/async-observable-helpers.ts" path="adev/src/content/examples/testing/src/testing/async-observable-helpers.ts" visibleRegion="async-data"/> This helper's observable emits the `data` value in the next turn of the JavaScript engine. The [RxJS `defer()` operator](http://reactivex.io/documentation/operators/defer.html) returns an observable. It takes a factory function that returns either a promise or an observable. When something subscribes to *defer*'s observable, it adds the subscriber to a new observable created with that factory. The `defer()` operator transforms the `Promise.resolve()` into a new observable that, like `HttpClient`, emits once and completes. Subscribers are unsubscribed after they receive the data value. There's a similar helper for producing an async error. <docs-code path="adev/src/content/examples/testing/src/testing/async-observable-helpers.ts" visibleRegion="async-error"/> ### More async tests Now that the `getQuote()` spy is returning async observables, most of your tests will have to be async as well. Here's a `fakeAsync()` test that demonstrates the data flow you'd expect in the real world. <docs-code path="adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts" visibleRegion="fake-async-test"/> Notice that the quote element displays the placeholder value \(`'...'`\) after `ngOnInit()`. The first quote hasn't arrived yet. To flush the first quote from the observable, you call [tick()](api/core/testing/tick). Then call `detectChanges()` to tell Angular to update the screen. Then you can assert that the quote element displays the expected text. ### Async test without `fakeAsync()` Here's the previous `fakeAsync()` test, re-written with the `async`. <docs-code path="adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts" visibleRegion="async-test"/> ### `whenStable` The test must wait for the `getQuote()` observable to emit the next quote. Instead of calling [tick()](api/core/testing/tick), it calls `fixture.whenStable()`. The `fixture.whenStable()` returns a promise that resolves when the JavaScript engine's task queue becomes empty. In this example, the task queue becomes empty when the observable emits the first quote. ## Component with inputs and outputs A component with inputs and outputs typically appears inside the view template of a host component. The host uses a property binding to set the input property and an event binding to listen to events raised by the output property. The testing goal is to verify that such bindings work as expected. The tests should set input values and listen for output events. The `DashboardHeroComponent` is a tiny example of a component in this role. It displays an individual hero provided by the `DashboardComponent`. Clicking that hero tells the `DashboardComponent` that the user has selected the hero. The `DashboardHeroComponent` is embedded in the `DashboardComponent` template like this: <docs-code header="app/dashboard/dashboard.component.html (excerpt)" path="adev/src/content/examples/testing/src/app/dashboard/dashboard.component.html" visibleRegion="dashboard-hero"/> The `DashboardHeroComponent` appears in an `*ngFor` repeater, which sets each component's `hero` input property to the looping value and listens for the component's `selected` event. Here's the component's full definition: <docs-code header="app/dashboard/dashboard-hero.component.ts (component)" path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.ts" visibleRegion="component"/> While testing a component this simple has little intrinsic value, it's worth knowing how. Use one of these approaches: * Test it as used by `DashboardComponent` * Test it as a standalone component * Test it as used by a substitute for `DashboardComponent` The immediate goal is to test the `DashboardHeroComponent`, not the `DashboardComponent`, so, try the second and third options. ### Test `DashboardHeroComponent` standalone Here's the meat of the spec file setup. <docs-code header="app/dashboard/dashboard-hero.component.spec.ts (setup)" path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="setup"/> Notice how the setup code assigns a test hero \(`expectedHero`\) to the component's `hero` property, emulating the way the `DashboardComponent` would set it using the property binding in its repeater. The following test verifies that the hero name is propagated to the template using a binding. <docs-code path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="name-test"/> Because the [template](#dashboard-hero-component) passes the hero name through the Angular `UpperCasePipe`, the test must match the element value with the upper-cased name. ### Clicking Clicking the hero should raise a `selected` event that the host component \(`DashboardComponent` presumably\) can hear: <docs-code path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="click-test"/> The component's `selected` property returns an `EventEmitter`, which looks like an RxJS synchronous `Observable` to consumers. The test subscribes to it *explicitly* just as the host component does *implicitly*. If the component behaves as expected, clicking the hero's element should tell the component's `selected` property to emit the `hero` object. The test detects that event through its subscription to `selected`. ### `triggerEventHandler` The `heroDe` in the previous test is a `DebugElement` that represents the hero `<div>`. It has Angular properties and methods that abstract interaction with the native element. This test calls the `DebugElement.triggerEventHandler` with the "click" event name. The "click" event binding responds by calling `DashboardHeroComponent.click()`. The Angular `DebugElement.triggerEventHandler` can raise *any data-bound event* by its *event name*. The second parameter is the event object passed to the handler. The test triggered a "click" event. <docs-code path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="trigger-event-handler"/> In this case, the test correctly assumes that the runtime event handler, the component's `click()` method, doesn't care about the event object. HELPFUL: Other handlers are less forgiving. For example, the `RouterLink` directive expects an object with a `button` property that identifies which mouse button, if any, was pressed during the click. The `RouterLink` directive throws an error if the event object is missing. ### Click the element The following test alternative calls the native element's own `click()` method, which is perfectly fine for *this component*. <docs-code path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="click-test-2"/> ### `click()` helper Clicking a button, an anchor, or an arbitrary HTML element is a common test task. Make that consistent and straightforward by encapsulating the *click-triggering* process in a helper such as the following `click()` function: <docs-code header="testing/index.ts (click helper)" path="adev/src/content/examples/testing/src/testing/index.ts" visibleRegion="click-event"/> The first parameter is the *element-to-click*. If you want, pass a custom event object as the second parameter. The default is a partial [left-button mouse event object](https://developer.mozilla.org/docs/Web/API/MouseEvent/button) accepted by many handlers including the `RouterLink` directive. IMPORTANT: The `click()` helper function is **not** one of the Angular testing utilities. It's a function defined in *this guide's sample code*. All of the sample tests use it. If you like it, add it to your own collection of helpers. Here's the previous test, rewritten using the click helper. <docs-code header="app/dashboard/dashboard-hero.component.spec.ts (test with click helper)" path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="click-test-3"/>
{ "end_byte": 28043, "start_byte": 19042, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/components-scenarios.md" }
angular/adev/src/content/guide/testing/components-scenarios.md_28043_33800
## Component inside a test host The previous tests played the role of the host `DashboardComponent` themselves. But does the `DashboardHeroComponent` work correctly when properly data-bound to a host component? <docs-code header="app/dashboard/dashboard-hero.component.spec.ts (test host)" path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="test-host"/> The test host sets the component's `hero` input property with its test hero. It binds the component's `selected` event with its `onSelected` handler, which records the emitted hero in its `selectedHero` property. Later, the tests will be able to check `selectedHero` to verify that the `DashboardHeroComponent.selected` event emitted the expected hero. The setup for the `test-host` tests is similar to the setup for the stand-alone tests: <docs-code header="app/dashboard/dashboard-hero.component.spec.ts (test host setup)" path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="test-host-setup"/> This testing module configuration shows three important differences: * It *imports* both the `DashboardHeroComponent` and the `TestHostComponent` * It *creates* the `TestHostComponent` instead of the `DashboardHeroComponent` * The `TestHostComponent` sets the `DashboardHeroComponent.hero` with a binding The `createComponent` returns a `fixture` that holds an instance of `TestHostComponent` instead of an instance of `DashboardHeroComponent`. Creating the `TestHostComponent` has the side effect of creating a `DashboardHeroComponent` because the latter appears within the template of the former. The query for the hero element \(`heroEl`\) still finds it in the test DOM, albeit at greater depth in the element tree than before. The tests themselves are almost identical to the stand-alone version: <docs-code header="app/dashboard/dashboard-hero.component.spec.ts (test-host)" path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="test-host-tests"/> Only the selected event test differs. It confirms that the selected `DashboardHeroComponent` hero really does find its way up through the event binding to the host component. ## Routing component A *routing component* is a component that tells the `Router` to navigate to another component. The `DashboardComponent` is a *routing component* because the user can navigate to the `HeroDetailComponent` by clicking on one of the *hero buttons* on the dashboard. Angular provides test helpers to reduce boilerplate and more effectively test code which depends HttpClient. The `provideRouter` function can be used directly in the test module as well. <docs-code header="app/dashboard/dashboard.component.spec.ts" path="adev/src/content/examples/testing/src/app/dashboard/dashboard.component.spec.ts" visibleRegion="router-harness"/> The following test clicks the displayed hero and confirms that we navigate to the expected URL. <docs-code header="app/dashboard/dashboard.component.spec.ts (navigate test)" path="adev/src/content/examples/testing/src/app/dashboard/dashboard.component.spec.ts" visibleRegion="navigate-test"/> ## Routed components A *routed component* is the destination of a `Router` navigation. It can be trickier to test, especially when the route to the component *includes parameters*. The `HeroDetailComponent` is a *routed component* that is the destination of such a route. When a user clicks a *Dashboard* hero, the `DashboardComponent` tells the `Router` to navigate to `heroes/:id`. The `:id` is a route parameter whose value is the `id` of the hero to edit. The `Router` matches that URL to a route to the `HeroDetailComponent`. It creates an `ActivatedRoute` object with the routing information and injects it into a new instance of the `HeroDetailComponent`. Here's the `HeroDetailComponent` constructor: <docs-code header="app/hero/hero-detail.component.ts (constructor)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.ts" visibleRegion="ctor"/> The `HeroDetail` component needs the `id` parameter so it can fetch the corresponding hero using the `HeroDetailService`. The component has to get the `id` from the `ActivatedRoute.paramMap` property which is an `Observable`. It can't just reference the `id` property of the `ActivatedRoute.paramMap`. The component has to *subscribe* to the `ActivatedRoute.paramMap` observable and be prepared for the `id` to change during its lifetime. <docs-code header="app/hero/hero-detail.component.ts (ngOnInit)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.ts" visibleRegion="ng-on-init"/> Tests can explore how the `HeroDetailComponent` responds to different `id` parameter values by navigating to different routes. ### Testing with the `RouterTestingHarness` Here's a test demonstrating the component's behavior when the observed `id` refers to an existing hero: <docs-code header="app/hero/hero-detail.component.spec.ts (existing id)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="route-good-id"/> HELPFUL: In the following section, the `createComponent()` method and `page` object are discussed. Rely on your intuition for now. When the `id` cannot be found, the component should re-route to the `HeroListComponent`. The test suite setup provided the same router harness [described above](#routing-component). This test expects the component to try to navigate to the `HeroListComponent`. <docs-code header="app/hero/hero-detail.component.spec.ts (bad id)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="route-bad-id"/>
{ "end_byte": 33800, "start_byte": 28043, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/components-scenarios.md" }
angular/adev/src/content/guide/testing/components-scenarios.md_33800_41003
## Nested component tests Component templates often have nested components, whose templates might contain more components. The component tree can be very deep and sometimes the nested components play no role in testing the component at the top of the tree. The `AppComponent`, for example, displays a navigation bar with anchors and their `RouterLink` directives. <docs-code header="app/app.component.html" path="adev/src/content/examples/testing/src/app/app.component.html"/> To validate the links but not the navigation, you don't need the `Router` to navigate and you don't need the `<router-outlet>` to mark where the `Router` inserts *routed components*. The `BannerComponent` and `WelcomeComponent` \(indicated by `<app-banner>` and `<app-welcome>`\) are also irrelevant. Yet any test that creates the `AppComponent` in the DOM also creates instances of these three components and, if you let that happen, you'll have to configure the `TestBed` to create them. If you neglect to declare them, the Angular compiler won't recognize the `<app-banner>`, `<app-welcome>`, and `<router-outlet>` tags in the `AppComponent` template and will throw an error. If you declare the real components, you'll also have to declare *their* nested components and provide for *all* services injected in *any* component in the tree. This section describes two techniques for minimizing the setup. Use them, alone or in combination, to stay focused on testing the primary component. ### Stubbing unneeded components In the first technique, you create and declare stub versions of the components and directive that play little or no role in the tests. <docs-code header="app/app.component.spec.ts (stub declaration)" path="adev/src/content/examples/testing/src/app/app.component.spec.ts" visibleRegion="component-stubs"/> The stub selectors match the selectors for the corresponding real components. But their templates and classes are empty. Then declare them in the `TestBed` configuration next to the components, directives, and pipes that need to be real. <docs-code header="app/app.component.spec.ts (TestBed stubs)" path="adev/src/content/examples/testing/src/app/app.component.spec.ts" visibleRegion="testbed-stubs"/> The `AppComponent` is the test subject, so of course you declare the real version. The rest are stubs. ### `NO_ERRORS_SCHEMA` In the second approach, add `NO_ERRORS_SCHEMA` to the `TestBed.schemas` metadata. <docs-code header="app/app.component.spec.ts (NO_ERRORS_SCHEMA)" path="adev/src/content/examples/testing/src/app/app.component.spec.ts" visibleRegion="no-errors-schema"/> The `NO_ERRORS_SCHEMA` tells the Angular compiler to ignore unrecognized elements and attributes. The compiler recognizes the `<app-root>` element and the `routerLink` attribute because you declared a corresponding `AppComponent` and `RouterLink` in the `TestBed` configuration. But the compiler won't throw an error when it encounters `<app-banner>`, `<app-welcome>`, or `<router-outlet>`. It simply renders them as empty tags and the browser ignores them. You no longer need the stub components. ### Use both techniques together These are techniques for *Shallow Component Testing*, so-named because they reduce the visual surface of the component to just those elements in the component's template that matter for tests. The `NO_ERRORS_SCHEMA` approach is the easier of the two but don't overuse it. The `NO_ERRORS_SCHEMA` also prevents the compiler from telling you about the missing components and attributes that you omitted inadvertently or misspelled. You could waste hours chasing phantom bugs that the compiler would have caught in an instant. The *stub component* approach has another advantage. While the stubs in *this* example were empty, you could give them stripped-down templates and classes if your tests need to interact with them in some way. In practice you will combine the two techniques in the same setup, as seen in this example. <docs-code header="app/app.component.spec.ts (mixed setup)" path="adev/src/content/examples/testing/src/app/app.component.spec.ts" visibleRegion="mixed-setup"/> The Angular compiler creates the `BannerStubComponent` for the `<app-banner>` element and applies the `RouterLink` to the anchors with the `routerLink` attribute, but it ignores the `<app-welcome>` and `<router-outlet>` tags. ### `By.directive` and injected directives A little more setup triggers the initial data binding and gets references to the navigation links: <docs-code header="app/app.component.spec.ts (test setup)" path="adev/src/content/examples/testing/src/app/app.component.spec.ts" visibleRegion="test-setup"/> Three points of special interest: * Locate the anchor elements with an attached directive using `By.directive` * The query returns `DebugElement` wrappers around the matching elements * Each `DebugElement` exposes a dependency injector with the specific instance of the directive attached to that element The `AppComponent` links to validate are as follows: <docs-code header="app/app.component.html (navigation links)" path="adev/src/content/examples/testing/src/app/app.component.html" visibleRegion="links"/> Here are some tests that confirm those links are wired to the `routerLink` directives as expected: <docs-code header="app/app.component.spec.ts (selected tests)" path="adev/src/content/examples/testing/src/app/app.component.spec.ts" visibleRegion="tests"/> ## Use a `page` object The `HeroDetailComponent` is a simple view with a title, two hero fields, and two buttons. But there's plenty of template complexity even in this simple form. <docs-code path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.html" header="app/hero/hero-detail.component.html"/> Tests that exercise the component need … * To wait until a hero arrives before elements appear in the DOM * A reference to the title text * A reference to the name input box to inspect and set it * References to the two buttons so they can click them Even a small form such as this one can produce a mess of tortured conditional setup and CSS element selection. Tame the complexity with a `Page` class that handles access to component properties and encapsulates the logic that sets them. Here is such a `Page` class for the `hero-detail.component.spec.ts` <docs-code header="app/hero/hero-detail.component.spec.ts (Page)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="page"/> Now the important hooks for component manipulation and inspection are neatly organized and accessible from an instance of `Page`. A `createComponent` method creates a `page` object and fills in the blanks once the `hero` arrives. <docs-code header="app/hero/hero-detail.component.spec.ts (createComponent)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="create-component"/> Here are a few more `HeroDetailComponent` tests to reinforce the point. <docs-code header="app/hero/hero-detail.component.spec.ts (selected tests)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="selected-tests"/> ##
{ "end_byte": 41003, "start_byte": 33800, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/components-scenarios.md" }
angular/adev/src/content/guide/testing/components-scenarios.md_41003_49344
Calling `compileComponents()` HELPFUL: Ignore this section if you *only* run tests with the CLI `ng test` command because the CLI compiles the application before running the tests. If you run tests in a **non-CLI environment**, the tests might fail with a message like this one: <docs-code hideCopy language="shell"> Error: This test module uses the component BannerComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test. </docs-code> The root of the problem is at least one of the components involved in the test specifies an external template or CSS file as the following version of the `BannerComponent` does. <docs-code header="app/banner/banner-external.component.ts (external template & css)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.ts"/> The test fails when the `TestBed` tries to create the component. <docs-code avoid header="app/banner/banner-external.component.spec.ts (setup that fails)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.spec.ts" visibleRegion="setup-may-fail"/> Recall that the application hasn't been compiled. So when you call `createComponent()`, the `TestBed` compiles implicitly. That's not a problem when the source code is in memory. But the `BannerComponent` requires external files that the compiler must read from the file system, an inherently *asynchronous* operation. If the `TestBed` were allowed to continue, the tests would run and fail mysteriously before the compiler could finish. The preemptive error message tells you to compile explicitly with `compileComponents()`. ### `compileComponents()` is async You must call `compileComponents()` within an asynchronous test function. CRITICAL: If you neglect to make the test function async (for example, forget to use `waitForAsync()` as described), you'll see this error message <docs-code hideCopy language="shell"> Error: ViewDestroyedError: Attempt to use a destroyed view </docs-code> A typical approach is to divide the setup logic into two separate `beforeEach()` functions: | Functions | Details | | :-------------------------- | :--------------------------- | | Asynchronous `beforeEach()` | Compiles the components | | Synchronous `beforeEach()` | Performs the remaining setup | ### The async `beforeEach` Write the first async `beforeEach` like this. <docs-code header="app/banner/banner-external.component.spec.ts (async beforeEach)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.spec.ts" visibleRegion="async-before-each"/> The `TestBed.configureTestingModule()` method returns the `TestBed` class so you can chain calls to other `TestBed` static methods such as `compileComponents()`. In this example, the `BannerComponent` is the only component to compile. Other examples configure the testing module with multiple components and might import application modules that hold yet more components. Any of them could require external files. The `TestBed.compileComponents` method asynchronously compiles all components configured in the testing module. IMPORTANT: Do not re-configure the `TestBed` after calling `compileComponents()`. Calling `compileComponents()` closes the current `TestBed` instance to further configuration. You cannot call any more `TestBed` configuration methods, not `configureTestingModule()` nor any of the `override...` methods. The `TestBed` throws an error if you try. Make `compileComponents()` the last step before calling `TestBed.createComponent()`. ### The synchronous `beforeEach` The second, synchronous `beforeEach()` contains the remaining setup steps, which include creating the component and querying for elements to inspect. <docs-code header="app/banner/banner-external.component.spec.ts (synchronous beforeEach)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.spec.ts" visibleRegion="sync-before-each"/> Count on the test runner to wait for the first asynchronous `beforeEach` to finish before calling the second. ### Consolidated setup You can consolidate the two `beforeEach()` functions into a single, async `beforeEach()`. The `compileComponents()` method returns a promise so you can perform the synchronous setup tasks *after* compilation by moving the synchronous code after the `await` keyword, where the promise has been resolved. <docs-code header="app/banner/banner-external.component.spec.ts (one beforeEach)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.spec.ts" visibleRegion="one-before-each"/> ### `compileComponents()` is harmless There's no harm in calling `compileComponents()` when it's not required. The component test file generated by the CLI calls `compileComponents()` even though it is never required when running `ng test`. The tests in this guide only call `compileComponents` when necessary. ## Setup with module imports Earlier component tests configured the testing module with a few `declarations` like this: <docs-code header="app/dashboard/dashboard-hero.component.spec.ts (configure TestBed)" path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="config-testbed"/> The `DashboardComponent` is simple. It needs no help. But more complex components often depend on other components, directives, pipes, and providers and these must be added to the testing module too. Fortunately, the `TestBed.configureTestingModule` parameter parallels the metadata passed to the `@NgModule` decorator which means you can also specify `providers` and `imports`. The `HeroDetailComponent` requires a lot of help despite its small size and simple construction. In addition to the support it receives from the default testing module `CommonModule`, it needs: * `NgModel` and friends in the `FormsModule` to enable two-way data binding * The `TitleCasePipe` from the `shared` folder * The Router services * The Hero data access services One approach is to configure the testing module from the individual pieces as in this example: <docs-code header="app/hero/hero-detail.component.spec.ts (FormsModule setup)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="setup-forms-module"/> HELPFUL: Notice that the `beforeEach()` is asynchronous and calls `TestBed.compileComponents` because the `HeroDetailComponent` has an external template and css file. As explained in [Calling `compileComponents()`](#calling-compilecomponents), these tests could be run in a non-CLI environment where Angular would have to compile them in the browser. ### Import a shared module Because many application components need the `FormsModule` and the `TitleCasePipe`, the developer created a `SharedModule` to combine these and other frequently requested parts. The test configuration can use the `SharedModule` too as seen in this alternative setup: <docs-code header="app/hero/hero-detail.component.spec.ts (SharedModule setup)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="setup-shared-module"/> It's a bit tighter and smaller, with fewer import statements, which are not shown in this example. ### Import a feature module The `HeroDetailComponent` is part of the `HeroModule` [Feature Module](guide/ngmodules/feature-modules) that aggregates more of the interdependent pieces including the `SharedModule`. Try a test configuration that imports the `HeroModule` like this one: <docs-code header="app/hero/hero-detail.component.spec.ts (HeroModule setup)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="setup-hero-module"/> Only the *test doubles* in the `providers` remain. Even the `HeroDetailComponent` declaration is gone. In fact, if you try to declare it, Angular will throw an error because `HeroDetailComponent` is declared in both the `HeroModule` and the `DynamicTestModule` created by the `TestBed`. HELPFUL: Importing the component's feature module can be the best way to configure tests when there are many mutual dependencies within the module and the module is small, as feature modules tend to be. ##
{ "end_byte": 49344, "start_byte": 41003, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/components-scenarios.md" }
angular/adev/src/content/guide/testing/components-scenarios.md_49344_54092
Override component providers The `HeroDetailComponent` provides its own `HeroDetailService`. <docs-code header="app/hero/hero-detail.component.ts (prototype)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.ts" visibleRegion="prototype"/> It's not possible to stub the component's `HeroDetailService` in the `providers` of the `TestBed.configureTestingModule`. Those are providers for the *testing module*, not the component. They prepare the dependency injector at the *fixture level*. Angular creates the component with its *own* injector, which is a *child* of the fixture injector. It registers the component's providers \(the `HeroDetailService` in this case\) with the child injector. A test cannot get to child injector services from the fixture injector. And `TestBed.configureTestingModule` can't configure them either. Angular has created new instances of the real `HeroDetailService` all along! HELPFUL: These tests could fail or timeout if the `HeroDetailService` made its own XHR calls to a remote server. There might not be a remote server to call. Fortunately, the `HeroDetailService` delegates responsibility for remote data access to an injected `HeroService`. <docs-code header="app/hero/hero-detail.service.ts (prototype)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.service.ts" visibleRegion="prototype"/> The [previous test configuration](#import-a-feature-module) replaces the real `HeroService` with a `TestHeroService` that intercepts server requests and fakes their responses. What if you aren't so lucky. What if faking the `HeroService` is hard? What if `HeroDetailService` makes its own server requests? The `TestBed.overrideComponent` method can replace the component's `providers` with easy-to-manage *test doubles* as seen in the following setup variation: <docs-code header="app/hero/hero-detail.component.spec.ts (Override setup)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="setup-override"/> Notice that `TestBed.configureTestingModule` no longer provides a fake `HeroService` because it's [not needed](#spy-stub). ### The `overrideComponent` method Focus on the `overrideComponent` method. <docs-code header="app/hero/hero-detail.component.spec.ts (overrideComponent)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="override-component-method"/> It takes two arguments: the component type to override \(`HeroDetailComponent`\) and an override metadata object. The [override metadata object](guide/testing/utility-apis#metadata-override-object) is a generic defined as follows: <docs-code language="javascript"> type MetadataOverride<T> = { add?: Partial<T>; remove?: Partial<T>; set?: Partial<T>; }; </docs-code> A metadata override object can either add-and-remove elements in metadata properties or completely reset those properties. This example resets the component's `providers` metadata. The type parameter, `T`, is the kind of metadata you'd pass to the `@Component` decorator: <docs-code language="javascript"> selector?: string; template?: string; templateUrl?: string; providers?: any[]; … </docs-code> ### Provide a *spy stub* (`HeroDetailServiceSpy`) This example completely replaces the component's `providers` array with a new array containing a `HeroDetailServiceSpy`. The `HeroDetailServiceSpy` is a stubbed version of the real `HeroDetailService` that fakes all necessary features of that service. It neither injects nor delegates to the lower level `HeroService` so there's no need to provide a test double for that. The related `HeroDetailComponent` tests will assert that methods of the `HeroDetailService` were called by spying on the service methods. Accordingly, the stub implements its methods as spies: <docs-code header="app/hero/hero-detail.component.spec.ts (HeroDetailServiceSpy)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="hds-spy"/> ### The override tests Now the tests can control the component's hero directly by manipulating the spy-stub's `testHero` and confirm that service methods were called. <docs-code header="app/hero/hero-detail.component.spec.ts (override tests)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="override-tests"/> ### More overrides The `TestBed.overrideComponent` method can be called multiple times for the same or different components. The `TestBed` offers similar `overrideDirective`, `overrideModule`, and `overridePipe` methods for digging into and replacing parts of these other classes. Explore the options and combinations on your own.
{ "end_byte": 54092, "start_byte": 49344, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/testing/components-scenarios.md" }
angular/adev/src/content/guide/components/lifecycle.md_0_8541
# Component Lifecycle Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. A component's **lifecycle** is the sequence of steps that happen between the component's creation and its destruction. Each step represents a different part of Angular's process for rendering components and checking them for updates over time. In your components, you can implement **lifecycle hooks** to run code during these steps. Lifecycle hooks that relate to a specific component instance are implemented as methods on your component class. Lifecycle hooks that relate the Angular application as a whole are implemented as functions that accept a callback. A component's lifecycle is tightly connected to how Angular checks your components for changes over time. For the purposes of understanding this lifecycle, you only need to know that Angular walks your application tree from top to bottom, checking template bindings for changes. The lifecycle hooks described below run while Angular is doing this traversal. This traversal visits each component exactly once, so you should always avoid making further state changes in the middle of the process. ## Summary <div class="docs-table docs-scroll-track-transparent"> <table> <tr> <td><strong>Phase</strong></td> <td><strong>Method</strong></td> <td><strong>Summary</strong></td> </tr> <tr> <td>Creation</td> <td><code>constructor</code></td> <td> <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor" target="_blank"> Standard JavaScript class constructor </a>. Runs when Angular instantiates the component. </td> </tr> <tr> <td rowspan="7">Change<p>Detection</td> <td><code>ngOnInit</code> </td> <td>Runs once after Angular has initialized all the component's inputs.</td> </tr> <tr> <td><code>ngOnChanges</code></td> <td>Runs every time the component's inputs have changed.</td> </tr> <tr> <td><code>ngDoCheck</code></td> <td>Runs every time this component is checked for changes.</td> </tr> <tr> <td><code>ngAfterContentInit</code></td> <td>Runs once after the component's <em>content</em> has been initialized.</td> </tr> <tr> <td><code>ngAfterContentChecked</code></td> <td>Runs every time this component content has been checked for changes.</td> </tr> <tr> <td><code>ngAfterViewInit</code></td> <td>Runs once after the component's <em>view</em> has been initialized.</td> </tr> <tr> <td><code>ngAfterViewChecked</code></td> <td>Runs every time the component's view has been checked for changes.</td> </tr> <tr> <td rowspan="2">Rendering</td> <td><code>afterNextRender</code></td> <td>Runs once the next time that <strong>all</strong> components have been rendered to the DOM.</td> </tr> <tr> <td><code>afterRender</code></td> <td>Runs every time <strong>all</strong> components have been rendered to the DOM.</td> </tr> <tr> <td>Destruction</td> <td><code>ngOnDestroy</code></td> <td>Runs once before the component is destroyed.</td> </tr> </table> </div> ### ngOnInit The `ngOnInit` method runs after Angular has initialized all the components inputs with their initial values. A component's `ngOnInit` runs exactly once. This step happens _before_ the component's own template is initialized. This means that you can update the component's state based on its initial input values. ### ngOnChanges The `ngOnChanges` method runs after any component inputs have changed. This step happens _before_ the component's own template is checked. This means that you can update the component's state based on its initial input values. During initialization, the first `ngOnChanges` runs before `ngOnInit`. #### Inspecting changes The `ngOnChanges` method accepts one `SimpleChanges` argument. This object is a [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type) mapping each component input name to a `SimpleChange` object. Each `SimpleChange` contains the input's previous value, its current value, and a flag for whether this is the first time the input has changed. ```ts @Component({ /* ... */ }) export class UserProfile { @Input() name: string = ''; ngOnChanges(changes: SimpleChanges) { for (const inputName in changes) { const inputValues = changes[inputName]; console.log(`Previous ${inputName} == ${inputValues.previousValue}`); console.log(`Current ${inputName} == ${inputValues.currentValue}`); console.log(`Is first ${inputName} change == ${inputValues.firstChange}`); } } } ``` If you provide an `alias` for any input properties, the `SimpleChanges` Record still uses the TypeScript property name as a key, rather than the alias. ### ngOnDestroy The `ngOnDestroy` method runs once just before a component is destroyed. Angular destroys a component when it is no longer shown on the page, such as being hidden by `NgIf` or upon navigating to another page. #### DestroyRef As an alternative to the `ngOnDestroy` method, you can inject an instance of `DestroyRef`. You can register a callback to be invoked upon the component's destruction by calling the `onDestroy` method of `DestroyRef`. ```ts @Component({ /* ... */ }) export class UserProfile { constructor(private destroyRef: DestroyRef) { destroyRef.onDestroy(() => { console.log('UserProfile destruction'); }); } } ``` You can pass the `DestroyRef` instance to functions or classes outside your component. Use this pattern if you have other code that should run some cleanup behavior when the component is destroyed. You can also use `DestroyRef` to keep setup code close to cleanup code, rather than putting all cleanup code in the `ngOnDestroy` method. ### ngDoCheck The `ngDoCheck` method runs before every time Angular checks a component's template for changes. You can use this lifecycle hook to manually check for state changes outside of Angular's normal change detection, manually updating the component's state. This method runs very frequently and can significantly impact your page's performance. Avoid defining this hook whenever possible, only using it when you have no alternative. During initialization, the first `ngDoCheck` runs after `ngOnInit`. ### ngAfterContentInit The `ngAfterContentInit` method runs once after all the children nested inside the component (its _content_) have been initialized. You can use this lifecycle hook to read the results of [content queries](guide/components/queries#content-queries). While you can access the initialized state of these queries, attempting to change any state in this method results in an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100) ### ngAfterContentChecked The `ngAfterContentChecked` method runs every time the children nested inside the component (its _content_) have been checked for changes. This method runs very frequently and can significantly impact your page's performance. Avoid defining this hook whenever possible, only using it when you have no alternative. While you can access the updated state of [content queries](guide/components/queries#content-queries) here, attempting to change any state in this method results in an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100). ### ngAfterViewInit The `ngAfterViewInit` method runs once after all the children in the component's template (its _view_) have been initialized. You can use this lifecycle hook to read the results of [view queries](guide/components/queries#view-queries). While you can access the initialized state of these queries, attempting to change any state in this method results in an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100) ### ngAfterViewChecked The `ngAfterViewChecked` method runs every time the children in the component's template (its _view_) have been checked for changes. This method runs very frequently and can significantly impact your page's performance. Avoid defining this hook whenever possible, only using it when you have no alternative. While you can access the updated state of [view queries](guide/components/queries#view-queries) here, attempting to change any state in this method results in an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100).
{ "end_byte": 8541, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/lifecycle.md" }
angular/adev/src/content/guide/components/lifecycle.md_8541_13769
### afterRender and afterNextRender The `afterRender` and `afterNextRender` functions let you register a **render callback** to be invoked after Angular has finished rendering _all components_ on the page into the DOM. These functions are different from the other lifecycle hooks described in this guide. Rather than a class method, they are standalone functions that accept a callback. The execution of render callbacks are not tied to any specific component instance, but instead an application-wide hook. `afterRender` and `afterNextRender` must be called in an [injection context](guide/di/dependency-injection-context), typically a component's constructor. You can use render callbacks to perform manual DOM operations. See [Using DOM APIs](guide/components/dom-apis) for guidance on working with the DOM in Angular. Render callbacks do not run during server-side rendering or during build-time pre-rendering. #### afterRender phases When using `afterRender` or `afterNextRender`, you can optionally split the work into phases. The phase gives you control over the sequencing of DOM operations, letting you sequence _write_ operations before _read_ operations in order to minimize [layout thrashing](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing). In order to communicate across phases, a phase function may return a result value that can be accessed in the next phase. ```ts import {Component, ElementRef, afterNextRender} from '@angular/core'; @Component({...}) export class UserProfile { private prevPadding = 0; private elementHeight = 0; constructor(elementRef: ElementRef) { const nativeElement = elementRef.nativeElement; afterNextRender({ // Use the `Write` phase to write to a geometric property. write: () => { const padding = computePadding(); const changed = padding !== prevPadding; if (changed) { nativeElement.style.padding = padding; } return changed; // Communicate whether anything changed to the read phase. }, // Use the `Read` phase to read geometric properties after all writes have occurred. read: (didWrite) => { if (didWrite) { this.elementHeight = nativeElement.getBoundingClientRect().height; } } }); } } ``` There are four phases, run in the following order: | Phase | Description | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `earlyRead` | Use this phase to read any layout-affecting DOM properties and styles that are strictly necessary for subsequent calculation. Avoid this phase if possible, preferring the `write` and `read` phases. | | `mixedReadWrite` | Default phase. Use for any operations need to both read and write layout-affecting properties and styles. Avoid this phase if possible, preferring the explicit `write` and `read` phases. | | `write` | Use this phase to write layout-affecting DOM properties and styles. | | `read` | Use this phase to read any layout-affecting DOM properties. | ## Lifecycle interfaces Angular provides a TypeScript interface for each lifecycle method. You can optionally import and `implement` these interfaces to ensure that your implementation does not have any typos or misspellings. Each interface has the same name as the corresponding method without the `ng` prefix. For example, the interface for `ngOnInit` is `OnInit`. ```ts @Component({ /* ... */ }) export class UserProfile implements OnInit { ngOnInit() { /* ... */ } } ``` ## Execution order The following diagrams show the execution order of Angular's lifecycle hooks. ### During initialization ```mermaid graph TD; id[constructor]-->CHANGE; subgraph CHANGE [Change detection] direction TB ngOnChanges-->ngOnInit; ngOnInit-->ngDoCheck; ngDoCheck-->ngAfterContentInit; ngDoCheck-->ngAfterViewInit ngAfterContentInit-->ngAfterContentChecked ngAfterViewInit-->ngAfterViewChecked end CHANGE--Rendering-->afterRender ``` ### Subsequent updates ```mermaid graph TD; subgraph CHANGE [Change detection] direction TB ngOnChanges-->ngDoCheck ngDoCheck-->ngAfterContentChecked; ngDoCheck-->ngAfterViewChecked end CHANGE--Rendering-->afterRender ``` ### Ordering with directives When you put one or more directives on the same element as a component, either in a template or with the `hostDirectives` property, the framework does not guarantee any ordering of a given lifecycle hook between the component and the directives on a single element. Never depend on an observed ordering, as this may change in later versions of Angular.
{ "end_byte": 13769, "start_byte": 8541, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/lifecycle.md" }
angular/adev/src/content/guide/components/queries.md_0_6598
# Referencing component children with queries Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. A component can define **queries** that find child elements and read values from their injectors. Developers most commonly use queries to retrieve references to child components, directives, DOM elements, and more. There are two categories of query: **view queries** and **content queries.** ## View queries View queries retrieve results from the elements in the component's _view_ — the elements defined in the component's own template. You can query for a single result with the `@ViewChild` decorator. <docs-code language="angular-ts" highlight="[14, 16, 17, 18]"> @Component({ selector: 'custom-card-header', ... }) export class CustomCardHeader { text: string; } @Component({ selector: 'custom-card', template: '<custom-card-header>Visit sunny California!</custom-card-header>', }) export class CustomCard { @ViewChild(CustomCardHeader) header: CustomCardHeader; ngAfterViewInit() { console.log(this.header.text); } } </docs-code> In this example, the `CustomCard` component queries for a child `CustomCardHeader` and accesses the result in `ngAfterViewInit`. If the query does not find a result, its value is `undefined`. This may occur if the target element is hidden by `NgIf`. Angular keeps the result of `@ViewChild` up to date as your application state changes. **View query results become available in the `ngAfterViewInit` lifecycle method**. Before this point, the value is `undefined`. See the [Lifecycle](guide/components/lifecycle) section for details on the component lifecycle. You can also query for multiple results with the `@ViewChildren` decorator. <docs-code language="angular-ts" highlight="[17, 19, 20, 21, 22, 23]"> @Component({ selector: 'custom-card-action', ..., }) export class CustomCardAction { text: string; } @Component({ selector: 'custom-card', template: ` <custom-card-action>Save</custom-card-action> <custom-card-action>Cancel</custom-card-action> `, }) export class CustomCard { @ViewChildren(CustomCardAction) actions: QueryList<CustomCardAction>; ngAfterViewInit() { this.actions.forEach(action => { console.log(action.text); }); } } </docs-code> `@ViewChildren` creates a `QueryList` object that contains the query results. You can subscribe to changes to the query results over time via the `changes` property. **Queries never pierce through component boundaries.** View queries can only retrieve results from the component's template. ## Content queries Content queries retrieve results from the elements in the component's _content_— the elements nested inside the component in the template where it's used. You can query for a single result with the `@ContentChild` decorator. <docs-code language="angular-ts" highlight="[14, 16, 17, 18, 25]"> @Component({ selector: 'custom-toggle', ... }) export class CustomToggle { text: string; } @Component({ selector: 'custom-expando', ... }) export class CustomExpando { @ContentChild(CustomToggle) toggle: CustomToggle; ngAfterContentInit() { console.log(this.toggle.text); } } @Component({ selector: 'user-profile', template: ` <custom-expando> <custom-toggle>Show</custom-toggle> </custom-expando> ` }) export class UserProfile { } </docs-code> In this example, the `CustomExpando` component queries for a child `CustomToggle` and accesses the result in `ngAfterContentInit`. If the query does not find a result, its value is `undefined`. This may occur if the target element is absent or hidden by `NgIf`. Angular keeps the result of `@ContentChild` up to date as your application state changes. By default, content queries find only _direct_ children of the component and do not traverse into descendants. **Content query results become available in the `ngAfterContentInit` lifecycle method**. Before this point, the value is `undefined`. See the [Lifecycle](guide/components/lifecycle) section for details on the component lifecycle. You can also query for multiple results with the `@ContentChildren` decorator. <docs-code language="angular-ts" highlight="[14, 16, 17, 18, 19, 20]"> @Component({ selector: 'custom-menu-item', ... }) export class CustomMenuItem { text: string; } @Component({ selector: 'custom-menu', ..., }) export class CustomMenu { @ContentChildren(CustomMenuItem) items: QueryList<CustomMenuItem>; ngAfterContentInit() { this.items.forEach(item => { console.log(item.text); }); } } @Component({ selector: 'user-profile', template: ` <custom-menu> <custom-menu-item>Cheese</custom-menu-item> <custom-menu-item>Tomato</custom-menu-item> </custom-menu> ` }) export class UserProfile { } </docs-code> `@ContentChildren` creates a `QueryList` object that contains the query results. You can subscribe to changes to the query results over time via the `changes` property. **Queries never pierce through component boundaries.** Content queries can only retrieve results from the same template as the component itself. ## Query locators This first parameter for each query decorator is its **locator**. Most of the time, you want to use a component or directive as your locator. You can alternatively specify a string locator corresponding to a [template reference variable](guide/templates/variables#template-reference-variables). ```angular-ts @Component({ ..., template: ` <button #save>Save</button> <button #cancel>Cancel</button> ` }) export class ActionBar { @ViewChild('save') saveButton: ElementRef<HTMLButtonElement>; } ``` If more than one element defines the same template reference variable, the query retrieves the first matching element. Angular does not support CSS selectors as query locators. ### Queries and the injector tree Tip: See [Dependency Injection](guide/di) for background on providers and Angular's injection tree. For more advanced cases, you can use any `ProviderToken` as a locator. This lets you locate elements based on component and directive providers. ```angular-ts const SUB_ITEM = new InjectionToken<string>('sub-item'); @Component({ ..., providers: [{provide: SUB_ITEM, useValue: 'special-item'}], }) export class SpecialItem { } @Component({...}) export class CustomList { @ContentChild(SUB_ITEM) subItemType: string; } ``` The above example uses an `InjectionToken` as a locator, but you can use any `ProviderToken` to locate specific elements. ## Q
{ "end_byte": 6598, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/queries.md" }
angular/adev/src/content/guide/components/queries.md_6598_10285
uery options All query decorators accept an options object as a second parameter. These options control how the query finds its results. ### Static queries `@ViewChild` and `@ContentChild` queries accept the `static` option. ```angular-ts @Component({ selector: 'custom-card', template: '<custom-card-header>Visit sunny California!</custom-card-header>', }) export class CustomCard { @ViewChild(CustomCardHeader, {static: true}) header: CustomCardHeader; ngOnInit() { console.log(this.header.text); } } ``` By setting `static: true`, you guarantee to Angular that the target of this query is _always_ present and is not conditionally rendered. This makes the result available earlier, in the `ngOnInit` lifecycle method. Static query results do not update after initialization. The `static` option is not available for `@ViewChildren` and `@ContentChildren` queries. ### Content descendants By default, content queries find only _direct_ children of the component and do not traverse into descendants. <docs-code language="angular-ts" highlight="[13, 14, 15, 16]"> @Component({ selector: 'custom-expando', ... }) export class CustomExpando { @ContentChild(CustomToggle) toggle: CustomToggle; } @Component({ selector: 'user-profile', template: ` <custom-expando> <some-other-component> <!-- custom-toggle will not be found! --> <custom-toggle>Show</custom-toggle> </some-other-component> </custom-expando> ` }) export class UserProfile { } </docs-code> In the example above, `CustomExpando` cannot find `<custom-toggle>` because it is not a direct child of `<custom-expando>`. By setting `descendants: true`, you configure the query to traverse all descendants in the same template. Queries, however, _never_ pierce into components to traverse elements in other templates. View queries do not have this option because they _always_ traverse into descendants. ### Reading specific values from an element's injector By default, the query locator indicates both the element you're searching for and the value retrieved. You can alternatively specify the `read` option to retrieve a different value from the element matched by the locator. ```ts @Component({...}) export class CustomExpando { @ContentChild(ExpandoContent, {read: TemplateRef}) toggle: TemplateRef; } ``` The above example, locates an element with the directive `ExpandoContent` and retrieves the `TemplateRef` associated with that element. Developers most commonly use `read` to retrieve `ElementRef` and `TemplateRef`. ## Using QueryList `@ViewChildren` and `@ContentChildren` both provide a `QueryList` object that contains a list of results. `QueryList` offers a number of convenience APIs for working with results in an array-like manner, such as `map`, `reduce`, and `forEach`. You can get an array of the current results by calling `toArray`. You can subscribe to the `changes` property to do something any time the results change. ## Common query pitfalls When using queries, common pitfalls can make your code harder to understand and maintain. Always maintain a single source of truth for state shared between multiple components. This avoids scenarios where repeated state in different components becomes out of sync. Avoid directly writing state to child components. This pattern can lead to brittle code that is hard to understand and is prone to [ExpressionChangedAfterItHasBeenChecked](errors/NG0100) errors. Never directly write state to parent or ancestor components. This pattern can lead to brittle code that is hard to understand and is prone to [ExpressionChangedAfterItHasBeenChecked](errors/NG0100) errors.
{ "end_byte": 10285, "start_byte": 6598, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/queries.md" }
angular/adev/src/content/guide/components/inputs.md_0_6829
# Accepting data with input properties Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Tip: If you're familiar with other web frameworks, input properties are similar to _props_. When creating a component, you can mark specific class properties as **bindable** by adding the `@Input` decorator on the property: <docs-code language="ts" highlight="[3]"> @Component({...}) export class CustomSlider { @Input() value = 0; } </docs-code> This lets you bind to the property in a template: ```angular-html <custom-slider [value]="50" /> ``` Angular refers to properties marked with the `@Input` decorator as **inputs**. When using a component, you pass data to it by setting its inputs. **Angular records inputs statically at compile-time**. Inputs cannot be added or removed at run-time. When extending a component class, **inputs are inherited by the child class.** **Input names are case-sensitive.** ## Customizing inputs The `@Input` decorator accepts a config object that lets you change the way that input works. ### Required inputs You can specify the `required` option to enforce that a given input must always have a value. <docs-code language="ts" highlight="[3]"> @Component({...}) export class CustomSlider { @Input({required: true}) value = 0; } </docs-code> If you try to use a component without specifying all of its required inputs, Angular reports an error at build-time. ### Input transforms You can specify a `transform` function to change the value of an input when it's set by Angular. <docs-code language="ts" highlight="[6]"> @Component({ selector: 'custom-slider', ... }) export class CustomSlider { @Input({transform: trimString}) label = ''; } function trimString(value: string | undefined) { return value?.trim() ?? ''; } </docs-code> ```angular-html <custom-slider [label]="systemVolume" /> ``` In the example above, whenever the value of `systemVolume` changes, Angular runs `trimString` and sets `label` to the result. The most common use-case for input transforms is to accept a wider range of value types in templates, often including `null` and `undefined`. **Input transform function must be statically analyzable at build-time.** You cannot set transform functions conditionally or as the result of an expression evaluation. **Input transform functions should always be [pure functions](https://en.wikipedia.org/wiki/Pure_function).** Relying on state outside of the transform function can lead to unpredictable behavior. #### Type checking When you specify an input transform, the type of the transform function's parameter determines the types of values that can be set to the input in a template. <docs-code language="ts"> @Component({...}) export class CustomSlider { @Input({transform: appendPx}) widthPx: string = ''; } function appendPx(value: number) { return `${value}px`; } </docs-code> In the example above, the `widthPx` input accepts a `number` while the property on the class is a `string`. #### Built-in transformations Angular includes two built-in transform functions for the two most common scenarios: coercing values to boolean and numbers. <docs-code language="ts"> import {Component, Input, booleanAttribute, numberAttribute} from '@angular/core'; @Component({...}) export class CustomSlider { @Input({transform: booleanAttribute}) disabled = false; @Input({transform: numberAttribute}) number = 0; } </docs-code> `booleanAttribute` imitates the behavior of standard HTML [boolean attributes](https://developer.mozilla.org/docs/Glossary/Boolean/HTML), where the _presence_ of the attribute indicates a "true" value. However, Angular's `booleanAttribute` treats the literal string `"false"` as the boolean `false`. `numberAttribute` attempts to parse the given value to a number, producing `NaN` if parsing fails. ### Input aliases You can specify the `alias` option to change the name of an input in templates. <docs-code language="ts" highlight="[3]"> @Component({...}) export class CustomSlider { @Input({alias: 'sliderValue'}) value = 0; } </docs-code> ```angular-html <custom-slider [sliderValue]="50" /> ``` This alias does not affect usage of the property in TypeScript code. While you should generally avoid aliasing inputs for components, this feature can be useful for renaming properties while preserving an alias for the original name or for avoiding collisions with the name of native DOM element properties. The `@Input` decorator also accepts the alias as its first parameter in place of the config object. ## Inputs with getters and setters A property implemented with a getter and setter can be an input: <docs-code language="ts"> export class CustomSlider { @Input() get value(): number { return this.internalValue; } set value(newValue: number) { this.internalValue = newValue; } private internalValue = 0; } </docs-code> You can even create a _write-only_ input by only defining a public setter: <docs-code language="ts"> export class CustomSlider { @Input() set value(newValue: number) { this.internalValue = newValue; } private internalValue = 0; } </docs-code> Prefer using <span style="text-decoration:underline;">input transforms</span> instead of getters and setters if possible. Avoid complex or costly getters and setters. Angular may invoke an input's setter multiple times, which may negatively impact application performance if the setter performs any costly behaviors, such as DOM manipulation. ## Specify inputs in the `@Component` decorator In addition to the `@Input` decorator, you can also specify a component's inputs with the `inputs` property in the `@Component` decorator. This can be useful when a component inherits a property from a base class: <docs-code language="ts" highlight="[4]"> // `CustomSlider` inherits the `disabled` property from `BaseSlider`. @Component({ ..., inputs: ['disabled'], }) export class CustomSlider extends BaseSlider { } </docs-code> You can additionally specify an input alias in the `inputs` list by putting the alias after a colon in the string: <docs-code language="ts" highlight="[4]"> // `CustomSlider` inherits the `disabled` property from `BaseSlider`. @Component({ ..., inputs: ['disabled: sliderDisabled'], }) export class CustomSlider extends BaseSlider { } </docs-code> ## Choosing input names Avoid choosing input names that collide with properties on DOM elements like HTMLElement. Name collisions introduce confusion about whether the bound property belongs to the component or the DOM element. Avoid adding prefixes for component inputs like you would with component selectors. Since a given element can only host one component, any custom properties can be assumed to belong to the component.
{ "end_byte": 6829, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/inputs.md" }
angular/adev/src/content/guide/components/inheritance.md_0_2640
# Inheritance Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Angular components are TypeScript classes and participate in standard JavaScript inheritance semantics. A component can extend any base class: ```ts export class ListboxBase { value: string; } @Component({ ... }) export class CustomListbox extends ListboxBase { // CustomListbox inherits the `value` property. } ``` ## Extending other components and directives When a component extends another component or a directive, it inherits all the metadata defined in the base class's decorator and the base class's decorated members. This includes the selector, template, styles, host bindings, inputs, outputs, lifecycle methods, and any other settings. ```angular-ts @Component({ selector: 'base-listbox', template: ` ... `, host: { '(keydown)': 'handleKey($event)', }, }) export class ListboxBase { @Input() value: string; handleKey(event: KeyboardEvent) { /* ... */ } } @Component({ selector: 'custom-listbox', template: ` ... `, host: { '(click)': 'focusActiveOption()', }, }) export class CustomListbox extends ListboxBase { @Input() disabled = false; focusActiveOption() { /* ... */ } } ``` In the example above, `CustomListbox` inherits all the information associated with `ListboxBase`, overriding the selector and template with its own values. `CustomListbox` has two inputs (`value` and `disabled`) and two event listeners (`keydown` and `click`). Child classes end up with the _union_ of all of their ancestors' inputs, outputs, and host bindings and their own. ### Forwarding injected dependencies If a base class relies on dependency injection, the child class must explicitly pass these dependencies to `super`. ```ts @Component({ ... }) export class ListboxBase { constructor(private element: ElementRef) { } } @Component({ ... }) export class CustomListbox extends ListboxBase { constructor(element: ElementRef) { super(element); } } ``` ### Overriding lifecycle methods If a base class defines a lifecycle method, such as `ngOnInit`, a child class that also implements `ngOnInit` _overrides_ the base class's implementation. If you want to preserve the base class's lifecycle method, explicitly call the method with `super`: ```ts @Component({ ... }) export class ListboxBase { protected isInitialized = false; ngOnInit() { this.isInitialized = true; } } @Component({ ... }) export class CustomListbox extends ListboxBase { override ngOnInit() { super.ngOnInit(); /* ... */ } } ```
{ "end_byte": 2640, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/inheritance.md" }
angular/adev/src/content/guide/components/outputs.md_0_3564
# Custom events with outputs Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Angular components can define custom events by assigning a property to a new `EventEmitter` and adding the `@Output` decorator: <docs-code language="ts" highlight=""> @Component({...}) export class ExpandablePanel { @Output() panelClosed = new EventEmitter<void>(); } </docs-code> ```angular-html <expandable-panel (panelClosed)="savePanelState()" /> ``` You can emit an event by calling the `emit` method on the `EventEmitter`: <docs-code language="ts" highlight=""> this.panelClosed.emit(); </docs-code> Angular refers to properties marked with the `@Output` decorator as **outputs**. You can use outputs to pass data to other components, similar to native browser events like `click`. **Angular custom events do not bubble up the DOM**. **Output names are case-sensitive.** When extending a component class, **outputs are inherited by the child class.** ## Emitting event data You can pass event data when calling `emit`: <docs-code language="ts" highlight=""> // You can emit primitive values. this.valueChanged.emit(7); // You can emit custom event objects this.thumbDropped.emit({ pointerX: 123, pointerY: 456, }) </docs-code> When defining an event listener in a template, you can access the event data from the `$event` variable: ```angular-html <custom-slider (valueChanged)="logValue($event)" /> ``` ## Customizing output names The `@Output` decorator accepts a parameter that lets you specify a different name for the event in a template: <docs-code language="ts" highlight=""> @Component({...}) export class CustomSlider { @Output('valueChanged') changed = new EventEmitter<number>(); } </docs-code> ```angular-html <custom-slider (valueChanged)="saveVolume()" /> ``` This alias does not affect usage of the property in TypeScript code. While you should generally avoid aliasing outputs for components, this feature can be useful for renaming properties while preserving an alias for the original name or for avoiding collisions with the name of native DOM events. ## Specify outputs in the `@Component` decorator In addition to the `@Output` decorator, you can also specify a component's outputs with the `outputs` property in the `@Component` decorator. This can be useful when a component inherits a property from a base class: <docs-code language="ts" highlight=""> // `CustomSlider` inherits the `valueChanged` property from `BaseSlider`. @Component({ ..., outputs: ['valueChanged'], }) export class CustomSlider extends BaseSlider {} </docs-code> You can additionally specify an output alias in the `outputs` list by putting the alias after a colon in the string: <docs-code language="ts" highlight=""> // `CustomSlider` inherits the `valueChanged` property from `BaseSlider`. @Component({ ..., outputs: ['valueChanged: volumeChanged'], }) export class CustomSlider extends BaseSlider {} </docs-code> ## Choosing event names Avoid choosing output names that collide with events on DOM elements like HTMLElement. Name collisions introduce confusion about whether the bound property belongs to the component or the DOM element. Avoid adding prefixes for component outputs like you would with component selectors. Since a given element can only host one component, any custom properties can be assumed to belong to the component. Always use [camelCase](https://en.wikipedia.org/wiki/Camel_case) output names. Avoid prefixing output names with "on".
{ "end_byte": 3564, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/outputs.md" }
angular/adev/src/content/guide/components/advanced-configuration.md_0_2088
# Advanced component configuration Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. ## ChangeDetectionStrategy The `@Component` decorator accepts a `changeDetection` option that controls the component's **change detection mode**. There are two change detection mode options. **`ChangeDetectionStrategy.Default`** is, unsurprisingly, the default strategy. In this mode, Angular checks whether the component's DOM needs an update whenever any activity may have occurred application-wide. Activities that trigger this checking include user interaction, network response, timers, and more. **`ChangeDetectionStrategy.OnPush`** is an optional mode that reduces the amount of checking Angular needs to perform. In this mode, the framework only checks if a component's DOM needs an update when: - A component input has changes as a result of a binding in a template, or - An event listener in this component runs - The component is explicitly marked for check, via `ChangeDetectorRef.markForCheck` or something which wraps it, like `AsyncPipe`. Additionally, when an OnPush component is checked, Angular _also_ checks all of its ancestor components, traversing upwards through the application tree. ## PreserveWhitespaces By default, Angular removes and collapses superfluous whitespace in templates, most commonly from newlines and indentation. You can change this setting by explicitly setting `preserveWhitespaces` to `true` in a component's metadata. ## Custom element schemas By default, Angular throws an error when it encounters an unknown HTML element. You can disable this behavior for a component by including `CUSTOM_ELEMENTS_SCHEMA` in the `schemas` property in your component metadata. ```angular-ts import {Component, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; @Component({ ..., schemas: [CUSTOM_ELEMENTS_SCHEMA], template: '<some-unknown-component></some-unknown-component>' }) export class ComponentWithCustomElements { } ``` Angular does not support any other schemas at this time.
{ "end_byte": 2088, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/advanced-configuration.md" }
angular/adev/src/content/guide/components/output-function.md_0_3725
# Function-based outputs The `output()` function declares an output in a directive or component. Outputs allow you to emit values to parent components. <docs-code language="ts" highlight="[[5], [8]]"> import {Component, output} from '@angular/core'; @Component({...}) export class MyComp { nameChange = output<string>() // OutputEmitterRef<string> setNewName(newName: string) { this.nameChange.emit(newName); } } </docs-code> An output is automatically recognized by Angular whenever you use the `output` function as an initializer of a class member. Parent components can listen to outputs in templates by using the event binding syntax. ```angular-html <my-comp (nameChange)="showNewName($event)" /> ``` ## Aliasing an output Angular uses the class member name as the name of the output. You can alias outputs to change their public name to be different. ```typescript class MyComp { nameChange = output({alias: 'ngxNameChange'}); } ``` This allows users to bind to your output using `(ngxNameChange)`, while inside your component you can access the output emitter using `this.nameChange`. ## Subscribing programmatically Consumers may create your component dynamically with a reference to a `ComponentRef`. In those cases, parents can subscribe to outputs by directly accessing the property of type `OutputRef`. ```ts const myComp = viewContainerRef.createComponent(...); myComp.instance.nameChange.subscribe(newName => { console.log(newName); }); ``` Angular will automatically clean up the subscription when `myComp` is destroyed. Alternatively, an object with a function to explicitly unsubscribe earlier is returned. ## Using RxJS observables as source In some cases, you may want to emit output values based on RxJS observables. Angular provides a way to use RxJS observables as source for outputs. The `outputFromObservable` function is a compiler primitive, similar to the `output()` function, and declares outputs that are driven by RxJS observables. <docs-code language="ts" highlight="[7]"> import {Directive} from '@angular/core'; import {outputFromObservable} from '@angular/core/rxjs-interop'; @Directive(...) class MyDir { nameChange$ = this.dataService.get(); // Observable<Data> nameChange = outputFromObservable(this.nameChange$); } </docs-code> Angular will forward subscriptions to the observable, but will stop forwarding values when the owning directive is destroyed. In the example above, if `MyDir` is destroyed, `nameChange` will no longer emit values. HELPFUL: Most of the time, using `output()` is sufficient and you can emit values imperatively. ## Converting an output to an observable You can subscribe to outputs by calling `.subscribe` method on `OutputRef`. In other cases, Angular provides a helper function that converts an `OutputRef` to an observable. <docs-code language="ts" highlight="[11]"> import {outputToObservable} from '@angular/core/rxjs-interop'; @Component(...) class MyComp { nameChange = output<string>(); } // Instance reference to `MyComp`. const myComp: MyComp; outputToObservable(this.myComp.instance.nameChange) // Observable<string> .pipe(...) .subscribe(...); </docs-code> ## Why you should use `output()` over decorator-based `@Output()`? The `output()` function provides numerous benefits over decorator-based `@Output` and `EventEmitter`: 1. Simpler mental model and API: <br/>• No concept of error channel, completion channels, or other APIs from RxJS. <br/>• Outputs are simple emitters. You can emit values using the `.emit` function. 2. More accurate types. <br/>• `OutputEmitterRef.emit(value)` is now correctly typed, while `EventEmitter` has broken types and can cause runtime errors.
{ "end_byte": 3725, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/output-function.md" }
angular/adev/src/content/guide/components/content-projection.md_0_6316
# Content projection with ng-content Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. You often need to create components that act as containers for different types of content. For example, you may want to create a custom card component: ```angular-ts @Component({ selector: 'custom-card', template: '<div class="card-shadow"> <!-- card content goes here --> </div>', }) export class CustomCard {/* ... */} ``` **You can use the `<ng-content>` element as a placeholder to mark where content should go**: ```angular-ts @Component({ selector: 'custom-card', template: '<div class="card-shadow"> <ng-content></ng-content> </div>', }) export class CustomCard {/* ... */} ``` Tip: `<ng-content>` works similarly to [the native `<slot>` element](https://developer.mozilla.org/docs/Web/HTML/Element/slot), but with some Angular-specific functionality. When you use a component with `<ng-content>`, any children of the component host element are rendered, or **projected**, at the location of that `<ng-content>`: ```angular-ts // Component source @Component({ selector: 'custom-card', template: ` <div class="card-shadow"> <ng-content /> </div> `, }) export class CustomCard {/* ... */} ``` ```angular-html <!-- Using the component --> <custom-card> <p>This is the projected content</p> </custom-card> ``` ```angular-html <!-- The rendered DOM --> <custom-card> <div class="card-shadow"> <p>This is the projected content</p> </div> </custom-card> ``` Angular refers to any children of a component passed this way as that component's **content**. This is distinct from the component's **view**, which refers to the elements defined in the component's template. **The `<ng-content>` element is neither a component nor DOM element**. Instead, it is a special placeholder that tells Angular where to render content. Angular's compiler processes all `<ng-content>` elements at build-time. You cannot insert, remove, or modify `<ng-content>` at run time. You cannot add directives, styles, or arbitrary attributes to `<ng-content>`. You should not conditionally include `<ng-content>` with `@if`, `@for`, or `@switch`. Angular always instantiates and creates DOM nodes for content rendered to a `<ng-content>` placeholder, even if that `<ng-content>` placeholder is hidden. For conditional rendering of component content, see [Template fragments](api/core/ng-template). ## Multiple content placeholders Angular supports projecting multiple different elements into different `<ng-content>` placeholders based on CSS selector. Expanding the card example from above, you could create two placeholders for a card title and a card body by using the `select` attribute: ```angular-html <!-- Component template --> <div class="card-shadow"> <ng-content select="card-title"></ng-content> <div class="card-divider"></div> <ng-content select="card-body"></ng-content> </div> ``` ```angular-html <!-- Using the component --> <custom-card> <card-title>Hello</card-title> <card-body>Welcome to the example</card-body> </custom-card> ``` ```angular-html <!-- Rendered DOM --> <custom-card> <div class="card-shadow"> <card-title>Hello</card-title> <div class="card-divider"></div> <card-body>Welcome to the example</card-body> </div> </custom-card> ``` The `<ng-content>` placeholder supports the same CSS selectors as [component selectors](guide/components/selectors). If you include one or more `<ng-content>` placeholders with a `select` attribute and one `<ng-content>` placeholder without a `select` attribute, the latter captures all elements that did not match a `select` attribute: ```angular-html <!-- Component template --> <div class="card-shadow"> <ng-content select="card-title"></ng-content> <div class="card-divider"></div> <!-- capture anything except "card-title" --> <ng-content></ng-content> </div> ``` ```angular-html <!-- Using the component --> <custom-card> <card-title>Hello</card-title> <img src="..." /> <p>Welcome to the example</p> </custom-card> ``` ```angular-html <!-- Rendered DOM --> <custom-card> <div class="card-shadow"> <card-title>Hello</card-title> <div class="card-divider"></div> <img src="..." /> <p>Welcome to the example></p> </div> </custom-card> ``` If a component does not include an `<ng-content>` placeholder without a `select` attribute, any elements that don't match one of the component's placeholders do not render into the DOM. ## Fallback content Angular can show *fallback content* for a component's `<ng-content>` placeholder if that component doesn't have any matching child content. You can specify fallback content by adding child content to the `<ng-content>` element itself. ```angular-html <!-- Component template --> <div class="card-shadow"> <ng-content select="card-title">Default Title</ng-content> <div class="card-divider"></div> <ng-content select="card-body">Default Body</ng-content> </div> ``` ```angular-html <!-- Using the component --> <custom-card> <card-title>Hello</card-title> <!-- No card-body provided --> </custom-card> ``` ```angular-html <!-- Rendered DOM --> <custom-card> <div class="card-shadow"> Hello <div class="card-divider"></div> Default Body </div> </custom-card> ``` ## Aliasing content for projection Angular supports a special attribute, `ngProjectAs`, that allows you to specify a CSS selector on any element. Whenever an element with `ngProjectAs` is checked against an `<ng-content>` placeholder, Angular compares against the `ngProjectAs` value instead of the element's identity: ```angular-html <!-- Component template --> <div class="card-shadow"> <ng-content select="card-title"></ng-content> <div class="card-divider"></div> <ng-content></ng-content> </div> ``` ```angular-html <!-- Using the component --> <custom-card> <h3 ngProjectAs="card-title">Hello</h3> <p>Welcome to the example</p> </custom-card> ``` ```angular-html <!-- Rendered DOM --> <custom-card> <div class="card-shadow"> <h3>Hello</h3> <div class="card-divider"></div> <p>Welcome to the example></p> </div> </custom-card> ``` `ngProjectAs` supports only static values and cannot be bound to dynamic expressions.
{ "end_byte": 6316, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/content-projection.md" }
angular/adev/src/content/guide/components/anatomy-of-components.md_0_4131
<docs-decorative-header title="Anatomy of a component" imgSrc="adev/src/assets/images/components.svg"> <!-- markdownlint-disable-line --> </docs-decorative-header> Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Every component must have: * A TypeScript class with _behaviors_ such as handling user input and fetching data from a server * An HTML template that controls what renders into the DOM * A [CSS selector](https://developer.mozilla.org/docs/Learn/CSS/Building_blocks/Selectors) that defines how the component is used in HTML You provide Angular-specific information for a component by adding a `@Component` [decorator](https://www.typescriptlang.org/docs/handbook/decorators.html) on top of the TypeScript class: <docs-code language="angular-ts" highlight="[1, 2, 3, 4]"> @Component({ selector: 'profile-photo', template: `<img src="profile-photo.jpg" alt="Your profile photo">`, }) export class ProfilePhoto { } </docs-code> For full details on writing Angular templates, see the [Templates guide](guide/templates). The object passed to the `@Component` decorator is called the component's **metadata**. This includes the `selector`, `template`, and other properties described throughout this guide. Components can optionally include a list of CSS styles that apply to that component's DOM: <docs-code language="angular-ts" highlight="[4]"> @Component({ selector: 'profile-photo', template: `<img src="profile-photo.jpg" alt="Your profile photo">`, styles: `img { border-radius: 50%; }`, }) export class ProfilePhoto { } </docs-code> By default, a component's styles only affect elements defined in that component's template. See [Styling Components](guide/components/styling) for details on Angular's approach to styling. You can alternatively choose to write your template and styles in separate files: <docs-code language="angular-ts" highlight="[3, 4]"> @Component({ selector: 'profile-photo', templateUrl: 'profile-photo.html', styleUrl: 'profile-photo.css', }) export class ProfilePhoto { } </docs-code> This can help separate the concerns of _presentation_ from _behavior_ in your project. You can choose one approach for your entire project, or you decide which to use for each component. Both `templateUrl` and `styleUrl` are relative to the directory in which the component resides. ## Using components Every component defines a [CSS selector](https://developer.mozilla.org/docs/Learn/CSS/Building_blocks/Selectors): <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: 'profile-photo', ... }) export class ProfilePhoto { } </docs-code> See [Component Selectors](guide/components/selectors) for details about which types of selectors Angular supports and guidance on choosing a selector. You use a component by creating a matching HTML element in the template of _other_ components: <docs-code language="angular-ts" highlight="[4]"> @Component({ selector: 'user-profile', template: ` <profile-photo /> <button>Upload a new profile photo</button>`, ..., }) export class UserProfile { } </docs-code> See [Importing and using components](guide/components/importing) for details on how to reference and use other components in your template. Angular creates an instance of the component for every matching HTML element it encounters. The DOM element that matches a component's selector is referred to as that component's **host element**. The contents of a component's template are rendered inside its host element. The DOM rendered by a component, corresponding to that component's template, is called that component's **view**. In composing components in this way, **you can think of your Angular application as a tree of components**. ```mermaid flowchart TD A[AccountSettings]-->B A-->C B[UserProfile]-->D B-->E C[PaymentInfo] D[ProfilePic] E[UserBio] ``` This tree structure is important to understanding several other Angular concepts, including [dependency injection](guide/di) and [child queries](guide/components/queries).
{ "end_byte": 4131, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/anatomy-of-components.md" }
angular/adev/src/content/guide/components/importing.md_0_1165
# Importing and using components Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Angular supports two ways of making a component available to other components: as a standalone component or in an `NgModule`. ## Standalone components A **standalone component** is a component that sets `standalone: true` in its component metadata. Standalone components directly import other components, directives, and pipes used in their templates: <docs-code language="angular-ts" highlight="[2, [8, 9]]"> @Component({ standalone: true, selector: 'profile-photo', }) export class ProfilePhoto { } @Component({ standalone: true, imports: [ProfilePhoto], template: `<profile-photo />` }) export class UserProfile { } </docs-code> Standalone components are directly importable into other standalone components. The Angular team recommends using standalone components for all new development. ## NgModules Angular code that predates standalone components uses `NgModule` as a mechanism for importing and using other components. See the full [`NgModule` guide](guide/ngmodules) for details.
{ "end_byte": 1165, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/importing.md" }
angular/adev/src/content/guide/components/BUILD.bazel_0_286
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "components", srcs = glob([ "*.md", ]), data = [ "//adev/src/assets/images:components.svg", ], mermaid_blocks = True, visibility = ["//adev:__subpackages__"], )
{ "end_byte": 286, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/BUILD.bazel" }
angular/adev/src/content/guide/components/host-elements.md_0_3334
# Component host elements Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Angular creates an instance of a component for every HTML element that matches the component's selector. The DOM element that matches a component's selector is that component's **host element**. The contents of a component's template are rendered inside its host element. ```angular-ts // Component source @Component({ selector: 'profile-photo', template: ` <img src="profile-photo.jpg" alt="Your profile photo" /> `, }) export class ProfilePhoto {} ``` ```angular-html <!-- Using the component --> <h3>Your profile photo</h3> <profile-photo /> <button>Upload a new profile photo</button> ``` ```angular-html <!-- Rendered DOM --> <h3>Your profile photo</h3> <profile-photo> <img src="profile-photo.jpg" alt="Your profile photo" /> </profile-photo> <button>Upload a new profile photo</button> ``` In the above example, `<profile-photo>` is the host element of the `ProfilePhoto` component. ## Binding to the host element A component can bind properties, attributes, and events to its host element. This behaves identically to bindings on elements inside the component's template, but instead defined with the `host` property in the `@Component` decorator: ```angular-ts @Component({ ..., host: { 'role': 'slider', '[attr.aria-valuenow]': 'value', '[class.active]': 'isActive()', '[tabIndex]': 'disabled ? -1 : 0', '(keydown)': 'updateValue($event)', }, }) export class CustomSlider { value: number = 0; disabled: boolean = false; isActive = signal(false); updateValue(event: KeyboardEvent) { /* ... */ } /* ... */ } ``` ## The `@HostBinding` and `@HostListener` decorators You can alternatively bind to the host element by applying the `@HostBinding` and `@HostListener` decorator to class members. `@HostBinding` lets you bind host properties and attributes to properties and methods: ```angular-ts @Component({ /* ... */ }) export class CustomSlider { @HostBinding('attr.aria-valuenow') value: number = 0; @HostBinding('tabIndex') getTabIndex() { return this.disabled ? -1 : 0; } /* ... */ } ``` `@HostListener` lets you bind event listeners to the host element. The decorator accepts an event name and an optional array of arguments: ```ts export class CustomSlider { @HostListener('keydown', ['$event']) updateValue(event: KeyboardEvent) { /* ... */ } } ``` **Always prefer using the `host` property over `@HostBinding` and `@HostListener`.** These decorators exist exclusively for backwards compatibility. ## Binding collisions When you use a component in a template, you can add bindings to that component instance's element. The component may _also_ define host bindings for the same properties or attributes. ```angular-ts @Component({ ..., host: { 'role': 'presentation', '[id]': 'id', } }) export class ProfilePhoto { /* ... */ } ``` ```angular-html <profile-photo role="group" [id]="otherId" /> ``` In cases like this, the following rules determine which value wins: - If both values are static, the instance binding wins. - If one value is static and the other dynamic, the dynamic value wins. - If both values are dynamic, the component's host binding wins.
{ "end_byte": 3334, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/host-elements.md" }
angular/adev/src/content/guide/components/selectors.md_0_6247
# Component selectors Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Every component defines a [CSS selector](https://developer.mozilla.org/docs/Web/CSS/CSS_selectors) that determines how the component is used: <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: 'profile-photo', ... }) export class ProfilePhoto { } </docs-code> You use a component by creating a matching HTML element in the templates of _other_ components: <docs-code language="angular-ts" highlight="[3]"> @Component({ template: ` <profile-photo /> <button>Upload a new profile photo</button>`, ..., }) export class UserProfile { } </docs-code> **Angular matches selectors statically at compile-time**. Changing the DOM at run-time, either via Angular bindings or with DOM APIs, does not affect the components rendered. **An element can match exactly one component selector.** If multiple component selectors match a single element, Angular reports an error. **Component selectors are case-sensitive.** ## Types of selectors Angular supports a limited subset of [basic CSS selector types](https://developer.mozilla.org/docs/Web/CSS/CSS_Selectors) in component selectors: | **Selector type** | **Description** | **Examples** | | ------------------ | --------------------------------------------------------------------------------------------------------------- | ----------------------------- | | Type selector | Matches elements based on their HTML tag name, or node name. | `profile-photo` | | Attribute selector | Matches elements based on the presence of an HTML attribute and, optionally, an exact value for that attribute. | `[dropzone]` `[type="reset"]` | | Class selector | Matches elements based on the presence of a CSS class. | `.menu-item` | For attribute values, Angular supports matching an exact attribute value with the equals (`=`) operator. Angular does not support other attribute value operators. Angular component selectors do not support combinators, including the [descendant combinator](https://developer.mozilla.org/docs/Web/CSS/Descendant_combinator) or [child combinator](https://developer.mozilla.org/docs/Web/CSS/Child_combinator). Angular component selectors do not support specifying [namespaces](https://developer.mozilla.org/docs/Web/SVG/Namespaces_Crash_Course). ### The `:not` pseudo-class Angular supports [the `:not` pseudo-class](https://developer.mozilla.org/docs/Web/CSS/:not). You can append this pseudo-class to any other selector to narrow which elements a component's selector matches. For example, you could define a `[dropzone]` attribute selector and prevent matching `textarea` elements: <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: '[dropzone]:not(textarea)', ... }) export class DropZone { } </docs-code> Angular does not support any other pseudo-classes or pseudo-elements in component selectors. ### Combining selectors You can combine multiple selectors by concatenating them. For example, you can match `<button>` elements that specify `type="reset"`: <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: 'button[type="reset"]', ... }) export class ResetButton { } </docs-code> You can also define multiple selectors with a comma-separated list: <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: 'drop-zone, [dropzone]', ... }) export class DropZone { } </docs-code> Angular creates a component for each element that matches _any_ of the selectors in the list. ## Choosing a selector The vast majority of components should use a custom element name as their selector. All custom element names should include a hyphen as described by [the HTML specification](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name). By default, Angular reports an error if it encounters a custom tag name that does not match any available components, preventing bugs due to mistyped component names. See [Advanced component configuration](guide/components/advanced-configuration) for details on using [native custom elements](https://developer.mozilla.org/docs/Web/Web_Components) in Angular templates. ### Selector prefixes The Angular team recommends using a short, consistent prefix for all the custom components defined inside your project. For example, if you were to build YouTube with Angular, you might prefix your components with `yt-`, with components like `yt-menu`, `yt-player`, etc. Namespacing your selectors like this makes it immediately clear where a particular component comes from. By default, the Angular CLI uses `app-`. Angular uses the `ng` selector prefix for its own framework APIs. Never use `ng` as a selector prefix for your own custom components. ### When to use an attribute selector You should consider an attribute selector when you want to create a component on a standard native element. For example, if you want to create a custom button component, you can take advantage of the standard `<button>` element by using an attribute selector: <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: 'button[yt-upload]', ... }) export class YouTubeUploadButton { } </docs-code> This approach allows consumers of the component to directly use all the element's standard APIs without extra work. This is especially valuable for ARIA attributes such as `aria-label`. Angular does not report errors when it encounters custom attributes that don't match an available component. When using components with attribute selectors, consumers may forget to import the component or its NgModule, resulting in the component not rendering. See [Importing and using components](guide/components/importing) for more information. Components that define attribute selectors should use lowercase, dash-case attributes. You can follow the same prefixing recommendation described above.
{ "end_byte": 6247, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/selectors.md" }
angular/adev/src/content/guide/components/styling.md_0_5133
# Styling components Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Components can optionally include CSS styles that apply to that component's DOM: <docs-code language="angular-ts" highlight="[4]"> @Component({ selector: 'profile-photo', template: `<img src="profile-photo.jpg" alt="Your profile photo">`, styles: ` img { border-radius: 50%; } `, }) export class ProfilePhoto { } </docs-code> You can also choose to write your styles in separate files: <docs-code language="angular-ts" highlight="[4]"> @Component({ selector: 'profile-photo', templateUrl: 'profile-photo.html', styleUrl: 'profile-photo.css', }) export class ProfilePhoto { } </docs-code> When Angular compiles your component, these styles are emitted with your component's JavaScript output. This means that component styles participate in the JavaScript module system. When you render an Angular component, the framework automatically includes its associated styles, even when lazy-loading a component. Angular works with any tool that outputs CSS, including [Sass](https://sass-lang.com), [less](https://lesscss.org), and [stylus](https://stylus-lang.com). ## Style scoping Every component has a **view encapsulation** setting that determines how the framework scopes a component's styles. There are three view encapsulation modes: `Emulated`, `ShadowDom`, and `None`. You can specify the mode in the `@Component` decorator: <docs-code language="angular-ts" highlight="[3]"> @Component({ ..., encapsulation: ViewEncapsulation.None, }) export class ProfilePhoto { } </docs-code> ### ViewEncapsulation.Emulated By default, Angular uses emulated encapsulation so that a component's styles only apply to elements defined in that component's template. In this mode, the framework generates a unique HTML attribute for each component instance, adds that attribute to elements in the component's template, and inserts that attribute into the CSS selectors defined in your component's styles. This mode ensures that a component's styles do not leak out and affect other components. However, global styles defined outside of a component may still affect elements inside a component with emulated encapsulation. In emulated mode, Angular supports the [`:host`](https://developer.mozilla.org/docs/Web/CSS/:host) and [`:host-context()`](https://developer.mozilla.org/docs/Web/CSS/:host-context) pseudo classes without using [Shadow DOM](https://developer.mozilla.org/docs/Web/Web_Components/Using_shadow_DOM). During compilation, the framework transforms these pseudo classes into attributes so it doesn't comply with these native pseudo classes' rules at runtime (e.g. browser compatibility, specificity). Angular's emulated encapsulation mode does not support any other pseudo classes related to Shadow DOM, such as `::shadow` or `::part`. #### `::ng-deep` Angular's emulated encapsulation mode supports a custom pseudo class, `::ng-deep`. Applying this pseudo class to a CSS rule disables encapsulation for that rule, effectively turning it into a global style. **The Angular team strongly discourages new use of `::ng-deep`**. These APIs remain exclusively for backwards compatibility. ### ViewEncapsulation.ShadowDom This mode scopes styles within a component by using [the web standard Shadow DOM API](https://developer.mozilla.org/docs/Web/Web_Components/Using_shadow_DOM). When enabling this mode, Angular attaches a shadow root to the component's host element and renders the component's template and styles into the corresponding shadow tree. This mode strictly guarantees that _only_ that component's styles apply to elements in the component's template. Global styles cannot affect elements in a shadow tree and styles inside the shadow tree cannot affect elements outside of that shadow tree. Enabling `ShadowDom` encapsulation, however, impacts more than style scoping. Rendering the component in a shadow tree affects event propagation, interaction with [the `<slot>` API](https://developer.mozilla.org/docs/Web/Web_Components/Using_templates_and_slots), and how browser developer tools show elements. Always understand the full implications of using Shadow DOM in your application before enabling this option. ### ViewEncapsulation.None This mode disables all style encapsulation for the component. Any styles associated with the component behave as global styles. ## Defining styles in templates You can use the `<style>` element in a component's template to define additional styles. The component's view encapsulation mode applies to styles defined this way. Angular does not support bindings inside of style elements. ## Referencing external style files Component templates can use [the `<link>` element](https://developer.mozilla.org/docs/Web/HTML/Element/link) to reference CSS files. Additionally, your CSS may use [the `@import`at-rule](https://developer.mozilla.org/docs/Web/CSS/@import) to reference CSS files. Angular treats these references as _external_ styles. External styles are not affected by emulated view encapsulation.
{ "end_byte": 5133, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/styling.md" }
angular/adev/src/content/guide/components/dom-apis.md_0_3683
# Using DOM APIs Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Angular handles most DOM creation, updates, and removals for you. However, you might rarely need to directly interact with a component's DOM. Components can inject ElementRef to get a reference to the component's host element: ```ts @Component({...}) export class ProfilePhoto { constructor(elementRef: ElementRef) { console.log(elementRef.nativeElement); } } ``` The `nativeElement` property references the host [Element](https://developer.mozilla.org/docs/Web/API/Element) instance. You can use Angular's `afterRender` and `afterNextRender` functions to register a **render callback** that runs when Angular has finished rendering the page. ```ts @Component({...}) export class ProfilePhoto { constructor(elementRef: ElementRef) { afterRender(() => { // Focus the first input element in this component. elementRef.nativeElement.querySelector('input')?.focus(); }); } } ``` `afterRender` and `afterNextRender` must be called in an _injection context_, typically a component's constructor. **Avoid direct DOM manipulation whenever possible.** Always prefer expressing your DOM's structure in component templates and updating that DOM with bindings. **Render callbacks never run during server-side rendering or build-time pre-rendering.** **Never directly manipulate the DOM inside of other Angular lifecycle hooks**. Angular does not guarantee that a component's DOM is fully rendered at any point other than in render callbacks. Further, reading or modifying the DOM during other lifecycle hooks can negatively impact page performance by causing [layout thrashing](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing). ## Using a component's renderer Components can inject an instance of `Renderer2` to perform certain DOM manipulations that are tied to other Angular features. Any DOM elements created by a component's `Renderer2` participate in that component's [style encapsulation](guide/components/styling#style-scoping). Certain `Renderer2` APIs also tie into Angular's animation system. You can use the `setProperty` method to update synthetic animation properties and the `listen` method to add event listeners for synthetic animation events. See the [Animations](guide/animations) guide for details. Aside from these two narrow use-cases, there is no difference between using `Renderer2` and native DOM APIs. `Renderer2` APIs do not support DOM manipulation in server-side rendering or build-time pre-rendering contexts. ## When to use DOM APIs While Angular handles most rendering concerns, some behaviors may still require using DOM APIs. Some common use cases include: - Managing element focus - Measuring element geometry, such as with `getBoundingClientRect` - Reading an element's text content - Setting up native observers such as [`MutationObserver`](https://developer.mozilla.org/docs/Web/API/MutationObserver), [`ResizeObserver`](https://developer.mozilla.org/docs/Web/API/ResizeObserver), or [`IntersectionObserver`](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API). Avoid inserting, removing, and modifying DOM elements. In particular, **never directly set an element's `innerHTML` property**, which can make your application vulnerable to [cross-site scripting (XSS) exploits](https://developer.mozilla.org/docs/Glossary/Cross-site_scripting). Angular's template bindings, including bindings for `innerHTML`, include safeguards that help protect against XSS attacks. See the [Security guide](best-practices/security) for details.
{ "end_byte": 3683, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/dom-apis.md" }
angular/adev/src/content/guide/components/programmatic-rendering.md_0_3614
# Programmatically rendering components Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. In addition to using a component directly in a template, you can also dynamically render components. There are two main ways to dynamically render a component: in a template with `NgComponentOutlet`, or in your TypeScript code with `ViewContainerRef`. ## Using NgComponentOutlet `NgComponentOutlet` is a structural directive that dynamically renders a given component in a template. ```angular-ts @Component({ ... }) export class AdminBio { /* ... */ } @Component({ ... }) export class StandardBio { /* ... */ } @Component({ ..., template: ` <p>Profile for {{user.name}}</p> <ng-container *ngComponentOutlet="getBioComponent()" /> ` }) export class CustomDialog { @Input() user: User; getBioComponent() { return this.user.isAdmin ? AdminBio : StandardBio; } } ``` See the [NgComponentOutlet API reference](api/common/NgComponentOutlet) for more information on the directive's capabilities. ## Using ViewContainerRef A **view container** is a node in Angular's component tree that can contain content. Any component or directive can inject `ViewContainerRef` to get a reference to a view container corresponding to that component or directive's location in the DOM. You can use the `createComponent`method on `ViewContainerRef` to dynamically create and render a component. When you create a new component with a `ViewContainerRef`, Angular appends it into the DOM as the next sibling of the component or directive that injected the `ViewContainerRef`. ```angular-ts @Component({ selector: 'leaf-content', template: ` This is the leaf content `, }) export class LeafContent {} @Component({ selector: 'outer-container', template: ` <p>This is the start of the outer container</p> <inner-item /> <p>This is the end of the outer container</p> `, }) export class OuterContainer {} @Component({ selector: 'inner-item', template: ` <button (click)="loadContent()">Load content</button> `, }) export class InnerItem { constructor(private viewContainer: ViewContainerRef) {} loadContent() { this.viewContainer.createComponent(LeafContent); } } ``` In the example above, clicking the "Load content" button results in the following DOM structure ```angular-html <outer-container> <p>This is the start of the outer container</p> <inner-item> <button>Load content</button> </inner-item> <leaf-content>This is the leaf content</leaf-content> <p>This is the end of the outer container</p> </outer-container> ``` ## Lazy-loading components You can use both of the approaches described above, `NgComponentOutlet` and `ViewContainerRef`, to render components that are lazy-loaded with a standard JavaScript [dynamic import](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/import). ```angular-ts @Component({ ..., template: ` <section> <h2>Basic settings</h2> <basic-settings /> </section> <section> <h2>Advanced settings</h2> <button (click)="loadAdvanced()" *ngIf="!advancedSettings"> Load advanced settings </button> <ng-container *ngComponentOutlet="advancedSettings" /> </section> ` }) export class AdminSettings { advancedSettings: {new(): AdminSettings} | undefined; async loadAdvanced() { this.advancedSettings = await import('path/to/advanced_settings.js'); } } ``` The example above loads and displays the `AdvancedSettings` upon receiving a button click.
{ "end_byte": 3614, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/components/programmatic-rendering.md" }
angular/adev/src/content/guide/http/overview.md_0_917
# Understanding communicating with backend services using HTTP Most front-end applications need to communicate with a server over the HTTP protocol, to download or upload data and access other back-end services. Angular provides a client HTTP API for Angular applications, the `HttpClient` service class in `@angular/common/http`. ## HTTP client service features The HTTP client service offers the following major features: * The ability to request [typed response values](guide/http/making-requests#fetching-json-data) * Streamlined [error handling](guide/http/making-requests#handling-request-failure) * Request and response [interception](guide/http/interceptors) * Robust [testing utilities](guide/http/testing) ## What's next <docs-pill-row> <docs-pill href="guide/http/setup" title="Setting up HttpClient"/> <docs-pill href="guide/http/making-requests" title="Making HTTP requests"/> </docs-pill-row>
{ "end_byte": 917, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/http/overview.md" }
angular/adev/src/content/guide/http/setup.md_0_5357
# Setting up `HttpClient` Before you can use `HttpClient` in your app, you must configure it using [dependency injection](guide/di). ## Providing `HttpClient` through dependency injection `HttpClient` is provided using the `provideHttpClient` helper function, which most apps include in the application `providers` in `app.config.ts`. <docs-code language="ts"> export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), ] }; </docs-code> If your app is using NgModule-based bootstrap instead, you can include `provideHttpClient` in the providers of your app's NgModule: <docs-code language="ts"> @NgModule({ providers: [ provideHttpClient(), ], // ... other application configuration }) export class AppModule {} </docs-code> You can then inject the `HttpClient` service as a dependency of your components, services, or other classes: <docs-code language="ts"> @Injectable({providedIn: 'root'}) export class ConfigService { constructor(private http: HttpClient) { // This service can now make HTTP requests via `this.http`. } } </docs-code> ## Configuring features of `HttpClient` `provideHttpClient` accepts a list of optional feature configurations, to enable or configure the behavior of different aspects of the client. This section details the optional features and their usages. ### `withFetch` <docs-code language="ts"> export const appConfig: ApplicationConfig = { providers: [ provideHttpClient( withFetch(), ), ] }; </docs-code> By default, `HttpClient` uses the [`XMLHttpRequest`](https://developer.mozilla.org/docs/Web/API/XMLHttpRequest) API to make requests. The `withFetch` feature switches the client to use the [`fetch`](https://developer.mozilla.org/docs/Web/API/Fetch_API) API instead. `fetch` is a more modern API and is available in a few environments where `XMLHttpRequest` is not supported. It does have a few limitations, such as not producing upload progress events. ### `withInterceptors(...)` `withInterceptors` configures the set of interceptor functions which will process requests made through `HttpClient`. See the [interceptor guide](guide/http/interceptors) for more information. ### `withInterceptorsFromDi()` `withInterceptorsFromDi` includes the older style of class-based interceptors in the `HttpClient` configuration. See the [interceptor guide](guide/http/interceptors) for more information. HELPFUL: Functional interceptors (through `withInterceptors`) have more predictable ordering and we recommend them over DI-based interceptors. ### `withRequestsMadeViaParent()` By default, when you configure `HttpClient` using `provideHttpClient` within a given injector, this configuration overrides any configuration for `HttpClient` which may be present in the parent injector. When you add `withRequestsMadeViaParent()`, `HttpClient` is configured to instead pass requests up to the `HttpClient` instance in the parent injector, once they've passed through any configured interceptors at this level. This is useful if you want to _add_ interceptors in a child injector, while still sending the request through the parent injector's interceptors as well. CRITICAL: You must configure an instance of `HttpClient` above the current injector, or this option is not valid and you'll get a runtime error when you try to use it. ### `withJsonpSupport()` Including `withJsonpSupport` enables the `.jsonp()` method on `HttpClient`, which makes a GET request via the [JSONP convention](https://en.wikipedia.org/wiki/JSONP) for cross-domain loading of data. HELPFUL: Prefer using [CORS](https://developer.mozilla.org/docs/Web/HTTP/CORS) to make cross-domain requests instead of JSONP when possible. ### `withXsrfConfiguration(...)` Including this option allows for customization of `HttpClient`'s built-in XSRF security functionality. See the [security guide](best-practices/security) for more information. ### `withNoXsrfProtection()` Including this option disables `HttpClient`'s built-in XSRF security functionality. See the [security guide](best-practices/security) for more information. ## `HttpClientModule`-based configuration Some applications may configure `HttpClient` using the older API based on NgModules. This table lists the NgModules available from `@angular/common/http` and how they relate to the provider configuration functions above. | **NgModule** | `provideHttpClient()` equivalent | | --------------------------------------- | --------------------------------------------- | | `HttpClientModule` | `provideHttpClient(withInterceptorsFromDi())` | | `HttpClientJsonpModule` | `withJsonpSupport()` | | `HttpClientXsrfModule.withOptions(...)` | `withXsrfConfiguration(...)` | | `HttpClientXsrfModule.disable()` | `withNoXsrfProtection()` | <docs-callout important title="Use caution when using HttpClientModule in multiple injectors"> When `HttpClientModule` is present in multiple injectors, the behavior of interceptors is poorly defined and depends on the exact options and provider/import ordering. Prefer `provideHttpClient` for multi-injector configurations, as it has more stable behavior. See the `withRequestsMadeViaParent` feature above. </docs-callout>
{ "end_byte": 5357, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/http/setup.md" }
angular/adev/src/content/guide/http/making-requests.md_0_7458
# Making HTTP requests `HttpClient` has methods corresponding to the different HTTP verbs used to make requests, both to load data and to apply mutations on the server. Each method returns an [RxJS `Observable`](https://rxjs.dev/guide/observable) which, when subscribed, sends the request and then emits the results when the server responds. Note: `Observable`s created by `HttpClient` may be subscribed any number of times and will make a new backend request for each subscription. Through an options object passed to the request method, various properties of the request and the returned response type can be adjusted. ## Fetching JSON data Fetching data from a backend often requires making a GET request using the [`HttpClient.get()`](api/common/http/HttpClient#get) method. This method takes two arguments: the string endpoint URL from which to fetch, and an *optional options* object to configure the request. For example, to fetch configuration data from a hypothetical API using the `HttpClient.get()` method: <docs-code language="ts"> http.get<Config>('/api/config').subscribe(config => { // process the configuration. }); </docs-code> Note the generic type argument which specifies that the data returned by the server will be of type `Config`. This argument is optional, and if you omit it then the returned data will have type `any`. Tip: If the data has an unknown shape, then a safer alternative to `any` is to use the `unknown` type as the response type. CRITICAL: The generic type of request methods is a type **assertion** about the data returned by the server. `HttpClient` does not verify that the actual return data matches this type. ## Fetching other types of data By default, `HttpClient` assumes that servers will return JSON data. When interacting with a non-JSON API, you can tell `HttpClient` what response type to expect and return when making the request. This is done with the `responseType` option. | **`responseType` value** | **Returned response type** | | - | - | | `'json'` (default) | JSON data of the given generic type | | `'text'` | string data | | `'arraybuffer'` | [`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing the raw response bytes | | `'blob'` | [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) instance | For example, you can ask `HttpClient` to download the raw bytes of a `.jpeg` image into an `ArrayBuffer`: <docs-code language="ts"> http.get('/images/dog.jpg', {responseType: 'arraybuffer'}).subscribe(buffer => { console.log('The image is ' + buffer.byteLength + ' bytes large'); }); </docs-code> <docs-callout important title="Literal value for `responseType`"> Because the value of `responseType` affects the type returned by `HttpClient`, it must have a literal type and not a `string` type. This happens automatically if the options object passed to the request method is a literal object, but if you're extracting the request options out into a variable or helper method you might need to explicitly specify it as a literal, such as `responseType: 'text' as const`. </docs-callout> ## Mutating server state Server APIs which perform mutations often require making POST requests with a request body specifying the new state or the change to be made. The [`HttpClient.post()`](api/common/http/HttpClient#post) method behaves similarly to `get()`, and accepts an additional `body` argument before its options: <docs-code language="ts"> http.post<Config>('/api/config', newConfig).subscribe(config => { console.log('Updated config:', config); }); </docs-code> Many different types of values can be provided as the request's `body`, and `HttpClient` will serialize them accordingly: | **`body` type** | **Serialized as** | | - | - | | string | Plain text | | number, boolean, array, or plain object | JSON | | [`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | raw data from the buffer | | [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) | raw data with the `Blob`'s content type | | [`FormData`](https://developer.mozilla.org/docs/Web/API/FormData) | `multipart/form-data` encoded data | | [`HttpParams`](api/common/http/HttpParams) or [`URLSearchParams`](https://developer.mozilla.org/docs/Web/API/URLSearchParams) | `application/x-www-form-urlencoded` formatted string | IMPORTANT: Remember to `.subscribe()` to mutation request `Observable`s in order to actually fire the request. ## Setting URL parameters Specify request parameters that should be included in the request URL using the `params` option. Passing an object literal is the simplest way of configuring URL parameters: <docs-code language="ts"> http.get('/api/config', { params: {filter: 'all'}, }).subscribe(config => { // ... }); </docs-code> Alternatively, pass an instance of `HttpParams` if you need more control over the construction or serialization of the parameters. IMPORTANT: Instances of `HttpParams` are _immutable_ and cannot be directly changed. Instead, mutation methods such as `append()` return a new instance of `HttpParams` with the mutation applied. <docs-code language="ts"> const baseParams = new HttpParams().set('filter', 'all'); http.get('/api/config', { params: baseParams.set('details', 'enabled'), }).subscribe(config => { // ... }); </docs-code> You can instantiate `HttpParams` with a custom `HttpParameterCodec` that determines how `HttpClient` will encode the parameters into the URL. ## Setting request headers Specify request headers that should be included in the request using the `headers` option. Passing an object literal is the simplest way of configuring request headers: <docs-code language="ts"> http.get('/api/config', { headers: { 'X-Debug-Level': 'verbose', } }).subscribe(config => { // ... }); </docs-code> Alternatively, pass an instance of `HttpHeaders` if you need more control over the construction of headers IMPORTANT: Instances of `HttpHeaders` are _immutable_ and cannot be directly changed. Instead, mutation methods such as `append()` return a new instance of `HttpHeaders` with the mutation applied. <docs-code language="ts"> const baseHeaders = new HttpHeaders().set('X-Debug-Level', 'minimal'); http.get<Config>('/api/config', { headers: baseHeaders.set('X-Debug-Level', 'verbose'), }).subscribe(config => { // ... }); </docs-code> ## Interacting with the server response events For convenience, `HttpClient` by default returns an `Observable` of the data returned by the server (the response body). Occasionally it's desirable to examine the actual response, for example to retrieve specific response headers. To access the entire response, set the `observe` option to `'response'`: <docs-code language="ts"> http.get<Config>('/api/config', {observe: 'response'}).subscribe(res => { console.log('Response status:', res.status); console.log('Body:', res.body); }); </docs-code> <docs-callout important title="Literal value for `observe`"> Because the value of `observe` affects the type returned by `HttpClient`, it must have a literal type and not a `string` type. This happens automatically if the options object passed to the request method is a literal object, but if you're extracting the request options out into a variable or helper method you might need to explicitly specify it as a literal, such as `observe: 'response' as const`. </docs-callout>
{ "end_byte": 7458, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/http/making-requests.md" }
angular/adev/src/content/guide/http/making-requests.md_7458_14111
## Receiving raw progress events In addition to the response body or response object, `HttpClient` can also return a stream of raw _events_ corresponding to specific moments in the request lifecycle. These events include when the request is sent, when the response header is returned, and when the body is complete. These events can also include _progress events_ which report upload and download status for large request or response bodies. Progress events are disabled by default (as they have a performance cost) but can be enabled with the `reportProgress` option. Note: The optional `fetch` implementation of `HttpClient` does not report _upload_ progress events. To observe the event stream, set the `observe` option to `'events'`: <docs-code language="ts"> http.post('/api/upload', myData, { reportProgress: true, observe: 'events', }).subscribe(event => { switch (event.type) { case HttpEventType.UploadProgress: console.log('Uploaded ' + event.loaded + ' out of ' + event.total + ' bytes'); break; case HttpEventType.Response: console.log('Finished uploading!'); break; } }); </docs-code> <docs-callout important title="Literal value for `observe`"> Because the value of `observe` affects the type returned by `HttpClient`, it must have a literal type and not a `string` type. This happens automatically if the options object passed to the request method is a literal object, but if you're extracting the request options out into a variable or helper method you might need to explicitly specify it as a literal, such as `observe: 'events' as const`. </docs-callout> Each `HttpEvent` reported in the event stream has a `type` which distinguishes what the event represents: | **`type` value** | **Event meaning** | | - | - | | `HttpEventType.Sent` | The request has been dispatched to the server | | `HttpEventType.UploadProgress` | An `HttpUploadProgressEvent` reporting progress on uploading the request body | | `HttpEventType.ResponseHeader` | The head of the response has been received, including status and headers | | `HttpEventType.DownloadProgress` | An `HttpDownloadProgressEvent` reporting progress on downloading the response body | | `HttpEventType.Response` | The entire response has been received, including the response body | | `HttpEventType.User` | A custom event from an Http interceptor. ## Handling request failure There are two ways an HTTP request can fail: * A network or connection error can prevent the request from reaching the backend server. * The backend can receive the request but fail to process it, and return an error response. `HttpClient` captures both kinds of errors in an `HttpErrorResponse` which it returns through the `Observable`'s error channel. Network errors have a `status` code of `0` and an `error` which is an instance of [`ProgressEvent`](https://developer.mozilla.org/docs/Web/API/ProgressEvent). Backend errors have the failing `status` code returned by the backend, and the error response as the `error`. Inspect the response to identify the error's cause and the appropriate action to handle the error. The [RxJS library](https://rxjs.dev/) offers several operators which can be useful for error handling. You can use the `catchError` operator to transform an error response into a value for the UI. This value can tell the UI to display an error page or value, and capture the error's cause if necessary. Sometimes transient errors such as network interruptions can cause a request to fail unexpectedly, and simply retrying the request will allow it to succeed. RxJS provides several *retry* operators which automatically re-subscribe to a failed `Observable` under certain conditions. For example, the `retry()` operator will automatically attempt to re-subscribe a specified number of times. ## Http `Observable`s Each request method on `HttpClient` constructs and returns an `Observable` of the requested response type. Understanding how these `Observable`s work is important when using `HttpClient`. `HttpClient` produces what RxJS calls "cold" `Observable`s, meaning that no actual request happens until the `Observable` is subscribed. Only then is the request actually dispatched to the server. Subscribing to the same `Observable` multiple times will trigger multiple backend requests. Each subscription is independent. TIP: You can think of `HttpClient` `Observable`s as _blueprints_ for actual server requests. Once subscribed, unsubscribing will abort the in-progress request. This is very useful if the `Observable` is subscribed via the `async` pipe, as it will automatically cancel the request if the user navigates away from the current page. Additionally, if you use the `Observable` with an RxJS combinator like `switchMap`, this cancellation will clean up any stale requests. Once the response returns, `Observable`s from `HttpClient` usually complete (although interceptors can influence this). Because of the automatic completion, there is usually no risk of memory leaks if `HttpClient` subscriptions are not cleaned up. However, as with any async operation, we strongly recommend that you clean up subscriptions when the component using them is destroyed, as the subscription callback may otherwise run and encounter errors when it attempts to interact with the destroyed component. TIP: Using the `async` pipe or the `toSignal` operation to subscribe to `Observable`s ensures that subscriptions are disposed properly. ## Best practices While `HttpClient` can be injected and used directly from components, generally we recommend you create reusable, injectable services which isolate and encapsulate data access logic. For example, this `UserService` encapsulates the logic to request data for a user by their id: <docs-code language="ts"> @Injectable({providedIn: 'root'}) export class UserService { constructor(private http: HttpClient) {} getUser(id: string): Observable<User> { return this.http.get<User>(`/api/user/${id}`); } } </docs-code> Within a component, you can combine `@if` with the `async` pipe to render the UI for the data only after it's finished loading: <docs-code language="ts"> import { AsyncPipe } from '@angular/common'; @Component({ standalone: true, imports: [AsyncPipe], template: ` @if (user$ | async; as user) { <p>Name: {{ user.name }}</p> <p>Biography: {{ user.biography }}</p> } `, }) export class UserProfileComponent { @Input() userId!: string; user$!: Observable<User>; constructor(private userService: UserService) {} ngOnInit(): void { this.user$ = this.userService.getUser(this.userId); } } </docs-code>
{ "end_byte": 14111, "start_byte": 7458, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/http/making-requests.md" }
angular/adev/src/content/guide/http/testing.md_0_5909
# Test requests As for any external dependency, you must mock the HTTP backend so your tests can simulate interaction with a remote server. The `@angular/common/http/testing` library provides tools to capture requests made by the application, make assertions about them, and mock the responses to emulate your backend's behavior. The testing library is designed for a pattern in which the app executes code and makes requests first. The test then expects that certain requests have or have not been made, performs assertions against those requests, and finally provides responses by "flushing" each expected request. At the end, tests can verify that the app made no unexpected requests. ## Setup for testing To begin testing usage of `HttpClient`, configure `TestBed` and include `provideHttpClient()` and `provideHttpClientTesting()` in your test's setup. This configures `HttpClient` to use a test backend instead of the real network. It also provides `HttpTestingController`, which you'll use to interact with the test backend, set expectations about which requests have been made, and flush responses to those requests. `HttpTestingController` can be injected from `TestBed` once configured. Keep in mind to provide `provideHttpClient()` **before** `provideHttpClientTesting()`, as `provideHttpClientTesting()` will overwrite parts of `provideHttpCient()`. Doing it the other way around can potentially break your tests. <docs-code language="ts"> TestBed.configureTestingModule({ providers: [ // ... other test providers provideHttpClient(), provideHttpClientTesting(), ], }); const httpTesting = TestBed.inject(HttpTestingController); </docs-code> Now when your tests make requests, they will hit the testing backend instead of the normal one. You can use `httpTesting` to make assertions about those requests. ## Expecting and answering requests For example, you can write a test that expects a GET request to occur and provides a mock response: <docs-code language="ts"> TestBed.configureTestingModule({ providers: [ ConfigService, provideHttpClient(), provideHttpClientTesting(), ], }); const httpTesting = TestBed.inject(HttpTestingController); // Load `ConfigService` and request the current configuration. const service = TestBed.inject(ConfigService); const config$ = this.configService.getConfig<Config>(); // `firstValueFrom` subscribes to the `Observable`, which makes the HTTP request, // and creates a `Promise` of the response. const configPromise = firstValueFrom(config$); // At this point, the request is pending, and we can assert it was made // via the `HttpTestingController`: const req = httpTesting.expectOne('/api/config', 'Request to load the configuration'); // We can assert various properties of the request if desired. expect(req.request.method).toBe('GET'); // Flushing the request causes it to complete, delivering the result. req.flush(DEFAULT_CONFIG); // We can then assert that the response was successfully delivered by the `ConfigService`: expect(await configPromise).toEqual(DEFAULT_CONFIG); // Finally, we can assert that no other requests were made. httpTesting.verify(); </docs-code> Note: `expectOne` will fail if the test has made more than one request which matches the given criteria. As an alternative to asserting on `req.method`, you could instead use an expanded form of `expectOne` to also match the request method: <docs-code language="ts"> const req = httpTesting.expectOne({ method: 'GET', url: '/api/config', }, 'Request to load the configuration'); </docs-code> HELPFUL: The expectation APIs match against the full URL of requests, including any query parameters. The last step, verifying that no requests remain outstanding, is common enough for you to move it into an `afterEach()` step: <docs-code language="ts"> afterEach(() => { // Verify that none of the tests make any extra HTTP requests. TestBed.inject(HttpTestingController).verify(); }); </docs-code> ## Handling more than one request at once If you need to respond to duplicate requests in your test, use the `match()` API instead of `expectOne()`. It takes the same arguments but returns an array of matching requests. Once returned, these requests are removed from future matching and you are responsible for flushing and verifying them. <docs-code language="ts"> const allGetRequests = httpTesting.match({method: 'GET'}); foreach (const req of allGetRequests) { // Handle responding to each request. } </docs-code> ## Advanced matching All matching functions accept a predicate function for custom matching logic: <docs-code language="ts"> // Look for one request that has a request body. const requestsWithBody = httpTesting.expectOne(req => req.body !== null); </docs-code> The `expectNone` function asserts that no requests match the given criteria. <docs-code language="ts"> // Assert that no mutation requests have been issued. httpTesting.expectNone(req => req.method !== 'GET'); </docs-code> ## Testing error handling You should test your app's responses when HTTP requests fail. ### Backend errors To test handling of backend errors (when the server returns a non-successful status code), flush requests with an error response that emulates what your backend would return when a request fails. <docs-code language="ts"> const req = httpTesting.expectOne('/api/config'); req.flush('Failed!', {status: 500, statusText: 'Internal Server Error'}); // Assert that the application successfully handled the backend error. </docs-code> ### Network errors Requests can also fail due to network errors, which surface as `ProgressEvent` errors. These can be delivered with the `error()` method: <docs-code language="ts"> const req = httpTesting.expectOne('/api/config'); req.error(new ProgressEvent('network error!')); // Assert that the application successfully handled the network error. </docs-code>
{ "end_byte": 5909, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/http/testing.md" }
angular/adev/src/content/guide/http/BUILD.bazel_0_182
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "http", srcs = glob([ "*.md", ]), visibility = ["//adev:__subpackages__"], )
{ "end_byte": 182, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/http/BUILD.bazel" }
angular/adev/src/content/guide/http/interceptors.md_0_9590
# Interceptors `HttpClient` supports a form of middleware known as _interceptors_. TLDR: Interceptors are middleware that allows common patterns around retrying, caching, logging, and authentication to be abstracted away from individual requests. `HttpClient` supports two kinds of interceptors: functional and DI-based. Our recommendation is to use functional interceptors because they have more predictable behavior, especially in complex setups. Our examples in this guide use functional interceptors, and we cover [DI-based interceptors](#di-based-interceptors) in their own section at the end. ## Interceptors Interceptors are generally functions which you can run for each request, and have broad capabilities to affect the contents and overall flow of requests and responses. You can install multiple interceptors, which form an interceptor chain where each interceptor processes the request or response before forwarding it to the next interceptor in the chain. You can use interceptors to implement a variety of common patterns, such as: * Adding authentication headers to outgoing requests to a particular API. * Retrying failed requests with exponential backoff. * Caching responses for a period of time, or until invalidated by mutations. * Customizing the parsing of responses. * Measuring server response times and log them. * Driving UI elements such as a loading spinner while network operations are in progress. * Collecting and batch requests made within a certain timeframe. * Automatically failing requests after a configurable deadline or timeout. * Regularly polling the server and refreshing results. ## Defining an interceptor The basic form of an interceptor is a function which receives the outgoing `HttpRequest` and a `next` function representing the next processing step in the interceptor chain. For example, this `loggingInterceptor` will log the outgoing request URL to `console.log` before forwarding the request: <docs-code language="ts"> export function loggingInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> { console.log(req.url); return next(req); } </docs-code> In order for this interceptor to actually intercept requests, you must configure `HttpClient` to use it. ## Configuring interceptors You declare the set of interceptors to use when configuring `HttpClient` through dependency injection, by using the `withInterceptors` feature: <docs-code language="ts"> bootstrapApplication(AppComponent, {providers: [ provideHttpClient( withInterceptors([loggingInterceptor, cachingInterceptor]), ) ]}); </docs-code> The interceptors you configure are chained together in the order that you've listed them in the providers. In the above example, the `loggingInterceptor` would process the request and then forward it to the `cachingInterceptor`. ### Intercepting response events An interceptor may transform the `Observable` stream of `HttpEvent`s returned by `next` in order to access or manipulate the response. Because this stream includes all response events, inspecting the `.type` of each event may be necessary in order to identify the final response object. <docs-code language="ts"> export function loggingInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> { return next(req).pipe(tap(event => { if (event.type === HttpEventType.Response) { console.log(req.url, 'returned a response with status', event.status); } })); } </docs-code> Tip: Interceptors naturally associate responses with their outgoing requests, because they transform the response stream in a closure that captures the request object. ## Modifying requests Most aspects of `HttpRequest` and `HttpResponse` instances are _immutable_, and interceptors cannot directly modify them. Instead, interceptors apply mutations by cloning these objects using the `.clone()` operation, and specifying which properties should be mutated in the new instance. This might involve performing immutable updates on the value itself (like `HttpHeaders` or `HttpParams`). For example, to add a header to a request: <docs-code language="ts"> const reqWithHeader = req.clone({ headers: req.headers.set('X-New-Header', 'new header value'), }); </docs-code> This immutability allows most interceptors to be idempotent if the same `HttpRequest` is submitted to the interceptor chain multiple times. This can happen for a few reasons, including when a request is retried after failure. CRITICAL: The body of a request or response is **not** protected from deep mutations. If an interceptor must mutate the body, take care to handle running multiple times on the same request. ## Dependency injection in interceptors Interceptors are run in the _injection context_ of the injector which registered them, and can use Angular's `inject` API to retrieve dependencies. For example, suppose an application has a service called `AuthService`, which creates authentication tokens for outgoing requests. An interceptor can inject and use this service: <docs-code language="ts"> export function authInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn) { // Inject the current `AuthService` and use it to get an authentication token: const authToken = inject(AuthService).getAuthToken(); // Clone the request to add the authentication header. const newReq = req.clone({ headers: req.headers.append('X-Authentication-Token', authToken), }); return next(newReq); } </docs-code> ## Request and response metadata Often it's useful to include information in a request that's not sent to the backend, but is specifically meant for interceptors. `HttpRequest`s have a `.context` object which stores this kind of metadata as an instance of `HttpContext`. This object functions as a typed map, with keys of type `HttpContextToken`. To illustrate how this system works, let's use metadata to control whether a caching interceptor is enabled for a given request. ### Defining context tokens To store whether the caching interceptor should cache a particular request in that request's `.context` map, define a new `HttpContextToken` to act as a key: <docs-code language="ts"> export const CACHING_ENABLED = new HttpContextToken<boolean>(() => true); </docs-code> The provided function creates the default value for the token for requests that haven't explicitly set a value for it. Using a function ensures that if the token's value is an object or array, each request gets its own instance. ### Reading the token in an interceptor An interceptor can then read the token and choose to apply caching logic or not based on its value: <docs-code language="ts"> export function cachingInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> { if (req.context.get(CACHING_ENABLED)) { // apply caching logic return ...; } else { // caching has been disabled for this request return next(req); } } </docs-code> ### Setting context tokens when making a request When making a request via the `HttpClient` API, you can provide values for `HttpContextToken`s: <docs-code language="ts"> const data$ = http.get('/sensitive/data', { context: new HttpContext().set(CACHING_ENABLED, false), }); </docs-code> Interceptors can read these values from the `HttpContext` of the request. ### The request context is mutable Unlike other properties of `HttpRequest`s, the associated `HttpContext` is _mutable_. If an interceptor changes the context of a request that is later retried, the same interceptor will observe the context mutation when it runs again. This is useful for passing state across multiple retries if needed. ## Synthetic responses Most interceptors will simply invoke the `next` handler while transforming either the request or the response, but this is not strictly a requirement. This section discusses several of the ways in which an interceptor may incorporate more advanced behavior. Interceptors are not required to invoke `next`. They may instead choose to construct responses through some other mechanism, such as from a cache or by sending the request through an alternate mechanism. Constructing a response is possible using the `HttpResponse` constructor: <docs-code language="ts"> const resp = new HttpResponse({ body: 'response body', }); </docs-code> ## DI-based interceptors `HttpClient` also supports interceptors which are defined as injectable classes and configured through the DI system. The capabilities of DI-based interceptors are identical to those of functional interceptors, but the configuration mechanism is different. A DI-based interceptor is an injectable class which implements the `HttpInterceptor` interface: <docs-code language="ts"> @Injectable() export class LoggingInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, handler: HttpHandler): Observable<HttpEvent<any>> { console.log('Request URL: ' + req.url); return handler.handle(req); } } </docs-code> DI-based interceptors are configured through a dependency injection multi-provider: <docs-code language="ts"> bootstrapApplication(AppComponent, {providers: [ provideHttpClient( // DI-based interceptors must be explicitly enabled. withInterceptorsFromDi(), ), {provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true}, ]}); </docs-code> DI-based interceptors run in the order that their providers are registered. In an app with an extensive and hierarchical DI configuration, this order can be very hard to predict.
{ "end_byte": 9590, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/http/interceptors.md" }
angular/adev/src/content/guide/http/security.md_0_4210
# `HttpClient` security `HttpClient` includes built-in support for two common HTTP security mechanisms: XSSI protection and XSRF/CSRF protection. Tip: Also consider adopting a [Content Security Policy](https://developer.mozilla.org/docs/Web/HTTP/Headers/Content-Security-Policy) for your APIs. ## XSSI protection Cross-Site Script Inclusion (XSSI) is a form of [Cross-Site Scripting](https://en.wikipedia.org/wiki/Cross-site_scripting) attack where an attacker loads JSON data from your API endpoints as `<script>`s on a page they control. Different JavaScript techniques can then be used to access this data. A common technique to prevent XSSI is to serve JSON responses with a "non-executable prefix", commonly `)]}',\n`. This prefix prevents the JSON response from being interpreted as valid executable JavaScript. When the API is loaded as data, the prefix can be stripped before JSON parsing. `HttpClient` automatically strips this XSSI prefix (if present) when parsing JSON from a response. ## XSRF/CSRF protection [Cross-Site Request Forgery (XSRF or CSRF)](https://en.wikipedia.org/wiki/Cross-site_request_forgery) is an attack technique by which the attacker can trick an authenticated user into unknowingly executing actions on your website. `HttpClient` supports a [common mechanism](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Cookie-to-header_token) used to prevent XSRF attacks. When performing HTTP requests, an interceptor reads a token from a cookie, by default `XSRF-TOKEN`, and sets it as an HTTP header, `X-XSRF-TOKEN`. Because only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker. By default, an interceptor sends this header on all mutating requests (such as `POST`) to relative URLs, but not on GET/HEAD requests or on requests with an absolute URL. <docs-callout helpful title="Why not protect GET requests?"> CSRF protection is only needed for requests that can change state on the backend. By their nature, CSRF attacks cross domain boundaries, and the web's [same-origin policy](https://developer.mozilla.org/docs/Web/Security/Same-origin_policy) will prevent an attacking page from retrieving the results of authenticated GET requests. </docs-callout> To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called `XSRF-TOKEN` on either the page load or the first GET request. On subsequent requests the server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be sure that only code running on your domain could have sent the request. The token must be unique for each user and must be verifiable by the server; this prevents the client from making up its own tokens. Set the token to a digest of your site's authentication cookie with a salt for added security. To prevent collisions in environments where multiple Angular apps share the same domain or subdomain, give each application a unique cookie name. <docs-callout important title="HttpClient supports only the client half of the XSRF protection scheme"> Your backend service must be configured to set the cookie for your page, and to verify that the header is present on all eligible requests. Failing to do so renders Angular's default protection ineffective. </docs-callout> ### Configure custom cookie/header names If your backend service uses different names for the XSRF token cookie or header, use `withXsrfConfiguration` to override the defaults. Add it to the `provideHttpClient` call as follows: <docs-code language="ts"> export const appConfig: ApplicationConfig = { providers: [ provideHttpClient( withXsrfConfiguration({ cookieName: 'CUSTOM_XSRF_TOKEN', headerName: 'X-Custom-Xsrf-Header', }), ), ] }; </docs-code> ### Disabling XSRF protection If the built-in XSRF protection mechanism doesn't work for your application, you can disable it using the `withNoXsrfProtection` feature: <docs-code language="ts"> export const appConfig: ApplicationConfig = { providers: [ provideHttpClient( withNoXsrfProtection(), ), ] }; </docs-code>
{ "end_byte": 4210, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/http/security.md" }
angular/adev/src/content/guide/templates/defer.md_0_5220
# Deferred loading with `@defer` Deferrable views, also known as `@defer` blocks, reduce the initial bundle size of your application by deferring the loading of code that is not strictly necessary for the initial rendering of a page. This often results in a faster initial load and improvement in Core Web Vitals (CWV), primarily Largest Contentful Paint (LCP) and Time to First Byte (TTFB). To use this feature, you can declaratively wrap a section of your template in a @defer block: ```angular-html @defer { <large-component /> } ``` The code for any components, directives, and pipes inside of the `@defer` block is split into a separate JavaScript file and loaded only when necessary, after the rest of the template has been rendered. Deferrable views support a variety of triggers, prefetching options, and sub-blocks for placeholder, loading, and error state management. ## Which dependencies are deferred? Components, directives, pipes, and any component CSS styles can be deferred when loading an application. In order for the dependencies within a `@defer` block to be deferred, they need to meet two conditions: 1. **They must be standalone.** Non-stadalone dependencies cannot be deferred and are still eagerly loaded, even if they are inside of `@defer` blocks. 1. **They cannot be referenced outside of `@defer` blocks within the same file.** If they are referenced outside of the `@defer` block or referenced within ViewChild queries, the dependencies will be eagerly loaded. The _transitive_ dependencies of the components, directives and pipes used in the `@defer` block do not strictly need to be standalone; transitive dependencies can still be declared in an `NgModule` and participate in deferred loading. ## How to manage different stages of deferred loading `@defer` blocks have several sub blocks to allow you to gracefully handle different stages in the deferred loading process. ### `@defer` This is the primary block that defines the section of content that is lazily loaded. It is not rendered initially– deferred content loads and renders once the specified [trigger](/guide/defer#triggers) occurs or the `when` condition is met. By default, a @defer block is triggered when the browser state becomes [idle](/guide/defer#on-idle). ```angular-html @defer { <large-component /> } ``` ### Show placeholder content with `@placeholder` By default, defer blocks do not render any content before they are triggered. The `@placeholder` is an optional block that declares what content to show before the `@defer` block is triggered. ```angular-html @defer { <large-component /> } @placeholder { <p>Placeholder content</p> } ``` While optional, certain triggers may require the presence of either a `@placeholder` or a [template reference variable](/guide/templates/variables#template-reference-variables) to function. See the [Triggers](/guide/defer#triggers) section for more details. Angular replaces placeholder content with the main content once loading is complete. You can use any content in the placeholder section including plain HTML, components, directives, and pipes. Keep in mind the _dependencies of the placeholder block are eagerly loaded_. The `@placeholder` block accepts an optional parameter to specify the `minimum` amount of time that this placeholder should be shown after the placeholder content initially renders. ```angular-html @defer { <large-component /> } @placeholder (minimum 500ms) { <p>Placeholder content</p> } ``` This `minimum` parameter is specified in time increments of milliseconds (ms) or seconds (s). You can use this parameter to prevent fast flickering of placeholder content in the case that the deferred dependencies are fetched quickly. ### Show loading content with `@loading` The `@loading` block is an optional block that allows you to declare content that is shown while deferred dependencies are loading. It replaces the `@placeholder` block once loading is triggered. ```angular-html @defer { <large-component /> } @loading { <img alt="loading..." src="loading.gif" /> } @placeholder { <p>Placeholder content</p> } ``` Its dependencies are eagerly loaded (similar to `@placeholder`). The `@loading` block accepts two optional parameters to help prevent fast flickering of content that may occur when deferred dependencies are fetched quickly,: - `minimum` - the minimum amount of time that this placeholder should be shown - `after` - the amount of time to wait after loading begins before showing the loading template ```angular-html @defer { <large-component /> } @loading (after 100ms; minimum 1s) { <img alt="loading..." src="loading.gif" /> } ``` Both parameters are specified in time increments of milliseconds (ms) or seconds (s). In addition, the timers for both parameters begin immediately after the loading has been triggered. ### Show error state when deferred loading fails with `@error` The `@error` block is an optional block that displays if deferred loading fails. Similar to `@placeholder` and `@loading`, the dependencies of the @error block are eagerly loaded. ```angular-html @defer { <large-component /> } @error { <p>Failed to load large component.</p> } ``` ##
{ "end_byte": 5220, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/defer.md" }
angular/adev/src/content/guide/templates/defer.md_5220_14329
Controlling deferred content loading with triggers You can specify **triggers** that control when Angular loads and displays deferred content. When a `@defer` block is triggered, it replaces placeholder content with lazily loaded content. Multiple event triggers can be defined by separating them with a semicolon, `;` and will be evaluated as OR conditions. There are two types of triggers: `on` and `when`. ### `on` `on` specifies a condition for when the `@defer` block is triggered. The available triggers are as follows: | Trigger | Description | | ----------------------------- | ---------------------------------------------------------------------- | | [`idle`](#idle) | Triggers when the browser is idle. | | [`viewport`](#viewport) | Triggers when specified content enters the viewport | | [`interaction`](#interaction) | Triggers when the user interacts with specified element | | [`hover`](#hover) | Triggers when the mouse hovers over specified area | | [`immediate`](#immediate) | Triggers immediately after non-deferred content has finished rendering | | [`timer`](#timer) | Triggers after a specific duration | #### `idle` The `idle` trigger loads the deferred content once the browser has reached an idle state, based on requestIdleCallback. This is the default behavior with a defer block. ```angular-html <!-- @defer (on idle) --> @defer { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` #### `viewport` The `viewport` trigger loads the deferred content when the specified content enters the viewport using the [Intersection Observer API](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API). Observed content may be `@placeholder` content or an explicit element reference. By default, the `@defer` watches for the placeholder entering the viewport. Placeholders used this way must have a single root element. ```angular-html @defer (on viewport) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` Alternatively, you can specify a [template reference variable](/guide/templates/variables) in the same template as the `@defer` block as the element that is watched to enter the viewport. This variable is passed in as a parameter on the viewport trigger. ```angular-html <div #greeting>Hello!</div> @defer (on viewport(greeting)) { <greetings-cmp /> } ``` #### `interaction` The `interaction` trigger loads the deferred content when the user interacts with the specified element through `click` or `keydown` events. By default, the placeholder acts as the interaction element. Placeholders used this way must have a single root element. ```angular-html @defer (on interaction) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` Alternatively, you can specify a [template reference variable](/guide/templates/variables) in the same template as the `@defer` block as the element that is watched to enter the viewport. This variable is passed in as a parameter on the viewport trigger.Z ```angular-html <div #greeting>Hello!</div> @defer (on interaction(greeting)) { <greetings-cmp /> } ``` #### `hover` The `hover` trigger loads the deferred content when the mouse has hovered over the triggered area through the `mouseenter` and `focusin` events. By default, the placeholder acts as the interaction element. Placeholders used this way must have a single root element. ```angular-html @defer (on hover) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` Alternatively, you can specify a [template reference variable](/guide/templates/variables) in the same template as the `@defer` block as the element that is watched to enter the viewport. This variable is passed in as a parameter on the viewport trigger. ```angular-html <div #greeting>Hello!</div> @defer (on hover(greeting)) { <greetings-cmp /> } ``` #### `immediate` The `immediate` trigger loads the deferred content immediately. This means that the deferred block loads as soon as all other non-deferred content has finished rendering. ```angular-html @defer (on immediate) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` #### `timer` The `timer` trigger loads the deferred content after a specified duration. ```angular-html @defer (on timer(500ms)) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` The duration parameter must be specified in milliseconds (`ms`) or seconds (`s`). ### `when` The `when` trigger accepts a custom conditional expression and loads the deferred content when the condition becomes truthy. ```angular-html @defer (when condition) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` This is a one-time operation– the `@defer` block does not revert back to the placeholder if the condition changes to a falsy value after becoming truthy. ## Prefetching data with `prefetch` In addition to specifying a condition that determines when deferred content is shown, you can optionally specify a **prefetch trigger**. This trigger lets you load the JavaScript associated with the `@defer` block before the deferred content is shown. Prefetching enables more advanced behaviors, such as letting you start to prefetch resources before a user has actually seen or interacted with a defer block, but might interact with it soon, making the resources available faster. You can specify a prefetch trigger similarly to the block's main trigger, but prefixed with the `prefetch` keyword. The block's main trigger and prefetch trigger are separated with a semi-colon character (`;`). In the example below, the prefetching starts when a browser becomes idle and the contents of the block is rendered only once the user interacts with the placeholder. ```angular-html @defer (on interaction; prefetch on idle) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` ## Testing `@defer` blocks Angular provides TestBed APIs to simplify the process of testing `@defer` blocks and triggering different states during testing. By default, `@defer` blocks in tests play through like a defer block would behave in a real application. If you want to manually step through states, you can switch the defer block behavior to `Manual` in the TestBed configuration. ```angular-ts it('should render a defer block in different states', async () => { // configures the defer block behavior to start in "paused" state for manual control. TestBed.configureTestingModule({deferBlockBehavior: DeferBlockBehavior.Manual}); @Component({ // ... template: ` @defer { <large-component /> } @placeholder { Placeholder } @loading { Loading... } ` }) class ComponentA {} // Create component fixture. const componentFixture = TestBed.createComponent(ComponentA); // Retrieve the list of all defer block fixtures and get the first block. const deferBlockFixture = (await componentFixture.getDeferBlocks())[0]; // Renders placeholder state by default. expect(componentFixture.nativeElement.innerHTML).toContain('Placeholder'); // Render loading state and verify rendered output. await deferBlockFixture.render(DeferBlockState.Loading); expect(componentFixture.nativeElement.innerHTML).toContain('Loading'); // Render final state and verify the output. await deferBlockFixture.render(DeferBlockState.Complete); expect(componentFixture.nativeElement.innerHTML).toContain('large works!'); }); ``` ## Does `@defer` work with `NgModule`? `@defer` blocks are compatible with both standalone and NgModule-based components, directives and pipes. However, **only standalone components, directives and pipes can be deferred**. NgModule-based dependencies are not deferred and are included in the eagerly loaded bundle. ## How does `@defer` work with server-side rendering (SSR) and static-site generation (SSG)? When rendering an application on the server (either using SSR or SSG), defer blocks always render their `@placeholder` (or nothing if a placeholder is not specified). Triggers are ignored on the server. ## Best practices for deferring views ### Avoid cascading loads with nested `@defer` blocks When you have nested `@defer` blocks, they should have different triggers in order to avoid loading simultaneously, which causes cascading requests and may negatively impact page load performance. ### Avoid layout shifts Avoid deferring components that are visible in the user’s viewport on initial load. Doing this may negatively affect Core Web Vitals by causing an increase in cumulative layout shift (CLS). In the event this is necessary, avoid `immediate`, `timer`, `viewport`, and custom `when` triggers that cause the content to load during the initial page render.
{ "end_byte": 14329, "start_byte": 5220, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/defer.md" }
angular/adev/src/content/guide/templates/event-listeners.md_0_3536
# Adding event listeners Angular supports defining event listeners on an element in your template by specifying the event name inside parentheses along with a statement that runs every time the event occurs. ## Listening to native events When you want to add event listeners to an HTML element, you wrap the event with parentheses, `()`, which allows you to specify a listener statement. ```angular-ts @Component({ template: ` <input type="text" (keyup)="updateField()" /> `, ... }) export class AppComponent({ updateField(): void { console.log('Field is updated!'); } }) ``` In this example, Angular calls `updateField` every time the `<input>` element emits a `keyup` event. You can add listeners for any native events, such as: `click`, `keydown`, `mouseover`, etc. To learn more, check out the [all available events on elements on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element#events). ## Accessing the event argument In every template event listener, Angular provides a variable named `$event` that contains a reference to the event object. ```angular-ts @Component({ template: ` <input type="text" (keyup)="updateField($event)" /> `, ... }) export class AppComponent { updateField(event: KeyboardEvent): void { console.log(`The user pressed: ${event.key}`); } } ``` ## Using key modifiers When you want to capture specific keyboard events for a specific key, you might write some code like the following: ```angular-ts @Component({ template: ` <input type="text" (keyup)="updateField($event)" /> `, ... }) export class AppComponent { updateField(event: KeyboardEvent): void { if (event.key === 'Enter') { console.log('The user pressed enter in the text field.'); } } } ``` However, since this is a common scenario, Angular lets you filter the events by specifying a specific key using the period (`.`) character. By doing so, code can be simplified to: ```angular-ts @Component({ template: ` <input type="text" (keyup.enter)="updateField($event)" /> `, ... }) export class AppComponent({ updateField(event: KeyboardEvent): void { console.log('The user pressed enter in the text field.'); } }) ``` You can also add additional key modifiers: ```angular-html <!-- Matches shift and enter --> <input type="text" (keyup.shift.enter)="updateField($event)" /> ``` Angular supports the modifiers `alt`, `control`, `meta`, and `shift`. You can specify the key or code that you would like to bind to keyboard events. The key and code fields are a native part of the browser keyboard event object. By default, event binding assumes you want to use the [Key values for keyboard events](https://developer.mozilla.org/docs/Web/API/UI_Events/Keyboard_event_key_values). Angular also allows you to specify [Code values for keyboard events](https://developer.mozilla.org/docs/Web/API/UI_Events/Keyboard_event_code_values) by providing a built-in `code` suffix. ```angular-html <!-- Matches alt and left shift --> <input type="text" (keydown.code.alt.leftshift)="updateField($event)" /> ``` This can be useful for handling keyboard events consistently across different operating systems. For example, when using the Alt key on MacOS devices, the `key` property reports the key based on the character already modified by the Alt key. This means that a combination like Alt + S reports a `key` value of `'ß'`. The `code` property, however, corresponds to the physical or virtual button pressed rather than the character produced.
{ "end_byte": 3536, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/event-listeners.md" }
angular/adev/src/content/guide/templates/overview.md_0_4985
<docs-decorative-header title="Template syntax" imgSrc="adev/src/assets/images/templates.svg"> <!-- markdownlint-disable-line --> In Angular, a template is a chunk of HTML. Use special syntax within a template to leverage many of Angular's features. </docs-decorative-header> Tip: Check out Angular's [Essentials](essentials/rendering-dynamic-templates) before diving into this comprehensive guide. Every Angular component has a **template** that defines the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) that the component renders onto the page. By using templates, Angular is able to automatically keep your page up-to-date as data changes. Templates are usually found within either the `template` property of a `*.component.ts` file or the `*.component.html` file. To learn more, check out the [in-depth components guide](/guide/components). ## How do templates work? Templates are based on [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) syntax, with additional features such as built-in template functions, data binding, event listening, variables, and more. Angular compiles templates into JavaScript in order to build up an internal understanding of your application. One of the benefits of this are built-in rendering optimizations that Angular applies to your application automatically. ### Differences from standard HTML Some differences between templates and standard HTML syntax include: - Comments in the template source code are not included in the rendered output - Component and directive elements can be self-closed (e.g., `<UserProfile />`) - Attributes with certain characters (i.e., `[]`, `()`, etc.) have special meaning to Angular. See [binding docs](guide/templates/binding) and [adding event listeners docs](guide/templates/event-listeners) for more information. - The `@` character has a special meaning to Angular for adding dynamic behavior, such as [control flow](guide/templates/control-flow), to templates. You can include a literal `@` character by escaping it as an HTML entity code (`&commat;` or `&#64;`). - Angular ignores and collapses unnecessary whitespace characters. See [whitespace in templates](guide/templates/whitespace) for more details. - Angular may add comment nodes to a page as placeholders for dynamic content, but developers can ignore these. In addition, while most HTML syntax is valid template syntax, Angular does not support `<script>` element in templates. For more information, see the [Security](best-practices/security) page. ## What's next? You might also be interested in the following: | Topics | Details | | :-------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- | | [Binding dynamic text, properties, and attributes](guide/templates/binding) | Bind dynamic data to text, properties and attributes. | | [Adding event listeners](guide/templates/event-listeners) | Respond to events in your templates. | | [Two-way binding](guide/templates/two-way-binding) | Simultaneously binds a value and propagate changes. | | [Control flow](guide/templates/control-flow) | Conditionally show, hide and repeat elements. | | [Pipes](guide/templates/pipes) | Transform data declaratively. | | [Slotting child content with ng-content](guide/templates/ng-content) | Control how components render content. | | [Create template fragments with ng-template](guide/templates/ng-template) | Declare a template fragment. | | [Grouping elements with ng-container](guide/templates/ng-container) | Group multiple elements together or mark a location for rendering. | | [Variables in templates](guide/templates/variables) | Learn about variable declarations. | | [Deferred loading with @defer](guide/templates/defer) | Create deferrable views with `@defer`. | | [Expression syntax](guide/templates/expression-syntax) | Learn similarities and differences betwene Angular expressions and standard JavaScript. | | [Whitespace in templates](guide/templates/whitespace) | Learn how Angular handles whitespace. |
{ "end_byte": 4985, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/overview.md" }
angular/adev/src/content/guide/templates/pipes.md_0_7960
# Pipes ## Overview Pipes are a special operator in Angular template expressions that allows you to transform data declaratively in your template. Pipes let you declare a transformation function once and then use that transformation across multiple templates. Angular pipes use the vertical bar character (`|`), inspired by the [Unix pipe](<https://en.wikipedia.org/wiki/Pipeline_(Unix)>). Note: Angular's pipe syntax deviates from standard JavaScript, which uses the vertical bar character for the [bitwise OR operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_OR). Angular template expressions do not support bitwise operators. Here is an example using some built-in pipes that Angular provides: ```angular-ts import { Component } from '@angular/core'; import { CurrencyPipe, DatePipe, TitleCasePipe } from '@angular/common'; @Component({ selector: 'app-root', standalone: true, imports: [CurrencyPipe, DatePipe, TitleCasePipe], template: ` <main> <!-- Transform the company name to title-case and transform the purchasedOn date to a locale-formatted string --> <h1>Purchases from {{ company | titlecase }} on {{ purchasedOn | date }}</h1> <!-- Transform the amount to a currency-formatted string --> <p>Total: {{ amount | currency }}</p> </main> `, }) export class ShoppingCartComponent { amount = 123.45; company = 'acme corporation'; purchasedOn = '2024-07-08'; } ``` When Angular renders the component, it will ensure that the appropriate date format and currency is based on the locale of the user. If the user is in the United States, it would render: ```angular-html <main> <h1>Purchases from Acme Corporation on Jul 8, 2024</h1> <p>Total: $123.45</p> </main> ``` See the [in-depth guide on i18n](/guide/i18n) to learn more about how Angular localizes values. ### Built-in Pipes Angular includes a set of built-in pipes in the `@angular/common` package: | Name | Description | | --------------------------------------------- | --------------------------------------------------------------------------------------------- | | [`AsyncPipe`](api/common/AsyncPipe) | Read the value from a `Promise` or an RxJS `Observable`. | | [`CurrencyPipe`](api/common/CurrencyPipe) | Transforms a number to a currency string, formatted according to locale rules. | | [`DatePipe`](api/common/DatePipe) | Formats a `Date` value according to locale rules. | | [`DecimalPipe`](api/common/DecimalPipe) | Transforms a number into a string with a decimal point, formatted according to locale rules. | | [`I18nPluralPipe`](api/common/I18nPluralPipe) | Maps a value to a string that pluralizes the value according to locale rules. | | [`I18nSelectPipe`](api/common/I18nSelectPipe) | Maps a key to a custom selector that returns a desired value. | | [`JsonPipe`](api/common/JsonPipe) | Transforms an object to a string representation via `JSON.stringify`, intended for debugging. | | [`KeyValuePipe`](api/common/KeyValuePipe) | Transforms Object or Map into an array of key value pairs. | | [`LowerCasePipe`](api/common/LowerCasePipe) | Transforms text to all lower case. | | [`PercentPipe`](api/common/PercentPipe) | Transforms a number to a percentage string, formatted according to locale rules. | | [`SlicePipe`](api/common/SlicePipe) | Creates a new Array or String containing a subset (slice) of the elements. | | [`TitleCasePipe`](api/common/TitleCasePipe) | Transforms text to title case. | | [`UpperCasePipe`](api/common/UpperCasePipe) | Transforms text to all upper case. | ## Using pipes Angular's pipe operator uses the vertical bar character (`|`), within a template expression. The pipe operator is a binary operator– the left-hand operand is the value passed to the transformation function, and the right side operand is the name of the pipe and any additional arguments (described below). ```angular-html <p>Total: {{ amount | currency }}</p> ``` In this example, the value of `amount` is passed into the `CurrencyPipe` where the pipe name is `currency`. It then renders the default currency for the user’s locale. ### Combining multiple pipes in the same expression You can apply multiple transformations to a value by using multiple pipe operators. Angular runs the pipes from left to right. The following example demonstrates a combination of pipes to display a localized date in all uppercase: ```angular-html <p>The event will occur on {{ scheduledOn | date | uppercase }}.</p> ``` ### Passing parameters to pipes Some pipes accept parameters to configure the transformation. To specify a parameter, append the pipe name with a colon (`:`) followed by the parameter value. For example, the `DatePipe` is able to take parameters to format the date in a specific way. ```angular-html <p>The event will occur at {{ scheduledOn | date:'hh:mm' }}.</p> ``` Some pipes may accept multiple parameters. You can specify additional parameter values separated by the colon character (`:`). For example, we can also pass a second optional parameter to control the timezone. ```angular-html <p>The event will occur at {{ scheduledOn | date:'hh:mm':'UTC' }}.</p> ``` ## How pipes work Conceptually, pipes are functions that accept an input value and return a transformed value. ```angular-ts import { Component } from '@angular/core'; import { CurrencyPipe} from '@angular/common'; @Component({ selector: 'app-root', standalone: true, imports: [CurrencyPipe], template: ` <main> <p>Total: {{ amount | currency }}</p> </main> `, }) export class AppComponent { amount = 123.45; } ``` In this example: 1. `CurrencyPipe` is imported from `@angular/common` 1. `CurrencyPipe` is added to the `imports` array 1. The `amount` data is passed to the `currency` pipe ### Pipe operator precedence The pipe operator has lower precedence than other binary operators, including `+`, `-`, `*`, `/`, `%`, `&&`, `||`, and `??`. ```angular-html <!-- firstName and lastName are concatenated before the result is passed to the uppercase pipe --> {{ (firstName + lastName | uppercase }} ``` The pipe operator has higher precedence than the conditional (ternary) operator. ```angular-html {{ (isAdmin ? 'Access granted' : 'Access denied') | uppercase }} ``` If the same expression were written without parentheses: ```angular-html {{ isAdmin ? 'Access granted' : 'Access denied' | uppercase }} ``` It will be parsed instead as: ```angular-html {{ isAdmin ? 'Access granted' : ('Access denied' | uppercase) }} ``` Always use parentheses in your expressions when operator precedence may be ambiguous. ### Change detection with pipes By default, all pipes are considered `pure`, which means that it only executes when a primitive input value (such as a `String`, `Number`, `Boolean`, or `Symbol`) or a changed object reference (such as `Array`, `Object`, `Function`, or `Date`). Pure pipes offer a performance advantage because Angular can avoid calling the transformation function if the passed value has not changed. As a result, this means that mutations to object properties or array items are not detected unless the entire object or array reference is replaced with a different instance. If you want this level of change detection, refer to [detecting changes within arrays or objects](#detecting-change-within-arrays-or-objects). ## C
{ "end_byte": 7960, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/pipes.md" }
angular/adev/src/content/guide/templates/pipes.md_7960_11963
reating custom pipes You can define a custom pipe by implementing a TypeScript class with the `@Pipe` decorator. A pipe must have two things: - A name, specified in the pipe decorator - A method named `transform` that performs the value transformation. The TypeScript class should additionally implement the `PipeTransform` interface to ensure that it satisfies the type signature for a pipe. Here is an example of a custom pipe that transforms strings to kebab case: ```angular-ts // kebab-case.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'kebabCase', standalone: true, }) export class KebabCasePipe implements PipeTransform { transform(value: string): string { return value.toLowerCase().replace(/ /g, '-'); } } ``` ### Using the `@Pipe` decorator When creating a custom pipe, import `Pipe` from the `@angular/core` package and use it as a decorator for the TypeScript class. ```angular-ts import { Pipe } from '@angular/core'; @Pipe({ name: 'myCustomTransformation', standalone: true }) export class MyCustomTransformationPipe {} ``` The `@Pipe` decorator requires two configuration options: - `name`: The pipe name that will be used in a template - `standalone: true` - Ensures the pipe can be used in standalone applications ### Naming convention for custom pipes The naming convention for custom pipes consists of two conventions: - `name` - camelCase is recommended. Do not use hyphens. - `class name` - PascalCase version of the `name` with `Pipe` appended to the end ### Implement the `PipeTransform` interface In addition to the `@Pipe` decorator, custom pipes should always implement the `PipeTransform` interface from `@angular/core`. ```angular-ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'myCustomTransformation', standalone: true }) export class MyCustomTransformationPipe implements PipeTransform {} ``` Implementing this interface ensures that your pipe class has the correct structure. ### Transforming the value of a pipe Every transformation is invoked by the `transform` method with the first parameter being the value being passed in and the return value being the transformed value. ```angular-ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'myCustomTransformation', standalone: true }) export class MyCustomTransformationPipe implements PipeTransform { transform(value: string): string { return `My custom transformation of ${value}.` } } ``` ### Adding parameters to a custom pipe You can add parameters to your transformation by adding additional parameters to the `transform` method: ```angular-ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'myCustomTransformation', standalone: true }) export class MyCustomTransformationPipe implements PipeTransform { transform(value: string, format: string): string { let msg = `My custom transformation of ${value}.` if (format === 'uppercase') { return msg.toUpperCase() else { return msg } } } ``` ### Detecting change within arrays or objects When you want a pipe to detect changes within arrays or objects, it must be marked as an impure function by passing the `pure` flag with a value of `false`. Avoid creating impure pipes unless absolutely necessary, as they can incur a significant performance penalty if used without care. ```angular-ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'featuredItemsImpure', pure: false, standalone: true }) export class FeaturedItemsImpurePipe implements PipeTransform { transform(value: string, format: string): string { let msg = `My custom transformation of ${value}.` if (format === 'uppercase') { return msg.toUpperCase() else { return msg } } } ``` Angular developers often adopt the convention of including `Impure` in the pipe `name` and class name to indicate the potential performance pitfall to other developers.
{ "end_byte": 11963, "start_byte": 7960, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/pipes.md" }
angular/adev/src/content/guide/templates/two-way-binding.md_0_4564
# Two-way binding **Two way binding** is a shorthand to simultaneously bind a value into an element, while also giving that element the ability to propagate changes back through this binding. ## Syntax The syntax for two-way binding is a combination of square brackets and parentheses, `[()]`. It combines the syntax from property binding, `[]`, and the syntax from event binding, `()`. The Angular community informally refers to this syntax as "banana-in-a-box". ## Two-way binding with form controls Developers commonly use two-way binding to keep component data in sync with a form control as a user interacts with the control. For example, when a user fills out a text input, it should update the state in the component. The following example dynamically updates the `firstName` attribute on the page: ```angular-ts import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ standalone: true, imports: [FormsModule], template: ` <main> <h2>Hello {{ firstName }}!</h2> <input type="text" [(ngModel)]="firstName" /> </main> ` }) export class AppComponent { firstName = 'Ada'; } ``` To use two-way binding with native form controls, you need to: 1. Import the `FormsModule` from `@angular/forms` 1. Use the `ngModel` directive with the two-way binding syntax (e.g., `[(ngModel)]`) 1. Assign it the state that you want it to update (e.g., `firstName`) Once that is setup, Angular will ensure that any updates in the text input will reflect correctly inside of the component state! Learn more about [`NgModel`](guide/directives#displaying-and-updating-properties-with-ngmodel) in the official docs. ## Two-way binding between components Leveraging two-way binding between a parent and child component requires more configuration compared to form elements. Here is an example where the `AppComponent` is responsible for setting the initial count state, but the logic for updating and rendering the UI for the counter primarily resides inside its child `CounterComponent`. ```angular-ts // ./app.component.ts import { Component } from '@angular/core'; import { CounterComponent } from './counter/counter.component'; @Component({ selector: 'app-root', standalone: true, imports: [CounterComponent], template: ` <main> <h1>Counter: {{ initialCount }}</h1> <app-counter [(count)]="initialCount"></app-counter> </main> `, }) export class AppComponent { initialCount = 18; } ``` ```angular-ts // './counter/counter.component.ts'; import { Component, EventEmitter, Input, Output } from '@angular/core'; @Component({ selector: 'app-counter', standalone: true, template: ` <button (click)="updateCount(-1)">-</button> <span>{{ count }}</span> <button (click)="updateCount(+1)">+</button> `, }) export class CounterComponent { @Input() count: number; @Output() countChange = new EventEmitter<number>(); updateCount(amount: number): void { this.count += amount; this.countChange.emit(this.count); } } ``` ### Enabling two-way binding between components If we break down the example above to its core , each two-way binding for components requires the following: The child component must contain: 1. An `@Input()` property 1. A corresponding `@Output()` event emitter that has the exact same name as the input property plus "Change" at the end. The emitter must also emit the same type as the input property. 1. A method that emits to the event emitter with the updated value of the `@Input()`. Here is a simplified example: ```angular-ts // './counter/counter.component.ts'; import { Component, EventEmitter, Input, Output } from '@angular/core'; @Component({ // Omitted for brevity }) export class CounterComponent { @Input() count: number; @Output() countChange = new EventEmitter<number>(); updateCount(amount: number): void { this.count += amount; this.countChange.emit(this.count); } } ``` The parent component must: 1. Wrap the `@Input()` property name in the two-way binding syntax. 1. Specify the corresponding property to which the updated value is assigned Here is a simplified example: ```angular-ts // ./app.component.ts import { Component } from '@angular/core'; import { CounterComponent } from './counter/counter.component'; @Component({ selector: 'app-root', standalone: true, imports: [CounterComponent], template: ` <main> <app-counter [(count)]="initialCount"></app-counter> </main> `, }) export class AppComponent { initialCount = 18; } ```
{ "end_byte": 4564, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/two-way-binding.md" }
angular/adev/src/content/guide/templates/whitespace.md_0_2611
# Whitespace in templates By default, Angular templates do not preserve whitespace that the framework considers unnecessary. This commonly occurs in two situations: whitespace between elements, and collapsible whitespace inside of text. ## Whitespace between elements Most developers prefer to format their templates with newlines and indentation to make the template readable: ```angular-html <section> <h3>User profile</p> <label> User name <input> </label> </section> ``` This template contains whitespace between all of the elements. The following snippet shows the same HTML with each whitespace character replaced with the hash (`#`) character to highlight how much whitespace is present: ```angular-html <!-- Total Whitespace: 20 --> <section>###<h3>User profile</p>###<label>#####User name#####<input>###</label>#</section> ``` Preserving the whitespace as written in the template would result in many unnecessary [text nodes](https://developer.mozilla.org/en-US/docs/Web/API/Text) and increase page rendering overhead. By ignoring this whitespace between elements, Angular performs less work when rendering the template on the page, improving overall performance. ## Collapsible whitespace inside text When your web browser renders HTML on a page, it collapses multiple consecutive whitespace characters to a single character: ```angular-html <!-- What it looks like in the template --> <p>Hello world</p> ``` In this example, the browser displays only a single space between "Hello" and "world". ```angular-html <!-- What shows up in the browser --> <p>Hello world</p> ``` See [How whitespace is handled by HTML, CSS, and in the DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Whitespace) for more context on how this works. Angular avoids sending these unnecessary whitespace characters to the browser in the first place by collapsing them to a single character when it compiles the template. ## Preserving whitespace You can tell Angular to preserve whitespace in a template by specifying `preserveWhitespaces: true` in the `@Component` decorator for a template. ```angular-ts @Component({ /* ... */, preserveWhitespaces: true, template: ` <p>Hello world</p> ` }) ``` Avoid setting this option unless absolutely necessary. Preserving whitespace can cause Angular to produce significantly more nodes while rendering, slowing down your application. You can additionally use a special HTML entity unique to Angular, `&ngsp;`. This entity produces a single space character that's preserved in the compiled output.
{ "end_byte": 2611, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/whitespace.md" }
angular/adev/src/content/guide/templates/binding.md_0_9521
# Binding dynamic text, properties and attributes In Angular, a **binding** creates a dynamic connection between a component's template and its data. This connection ensures that changes to the component's data automatically update the rendered template. ## Render dynamic text with text interpolation You can bind dynamic text in templates with double curly braces, which tells Angular that it is responsible for the expression inside and ensuring it is updated correctly. This is called **text interpolation**. ```angular-ts @Component({ template: ` <p>Your color preference is {{ theme }}.</p> `, ... }) export class AppComponent { theme = 'dark'; } ``` In this example, when the snippet is rendered to the page, Angular will replace `{{ theme }}` with `dark`. ```angular-html <!-- Rendered Output --> <p>Your color preference is dark.</p> ``` In addition to evaluating the expression at first render, Angular also updates the rendered content when the expression's value changes. Continuing the theme example, if a user clicks on a button that changes the value of `theme` to `'light'` after the page loads, the page updates accordingly to: ```angular-html <!-- Rendered Output --> <p>Your color preference is light.</p> ``` You can use text interpolation anywhere you would normally write text in HTML. All expression values are converted to a string. Objects and arrays are converted using the value’s `toString` method. ## Binding dynamic properties and attributes Angular supports binding dynamic values into object properties and HTML attributes with square brackets. You can bind to properties on an HTML element's DOM instance, a [component](guide/components) instance, or a [directive](guide/directives) instance. ### Native element properties Every HTML element has a corresponding DOM representation. For example, each `<button>` HTML element corresponds to an instance of `HTMLButtonElement` in the DOM. In Angular, you use property bindings to set values directly to the DOM representation of the element. ```angular-html <!-- Bind the `disabled` property on the button element's DOM object --> <button [disabled]="isFormValid">Save</button> ``` In this example, every time `isFormValid` changes, Angular automatically sets the `disabled` property of the `HTMLButtonElement` instance. ### Component and directive properties When an element is an Angular component, you can use property bindings to set component input properties using the same square bracket syntax. ```angular-html <!-- Bind the `value` property on the `MyListbox` component instance. --> <my-listbox [value]="mySelection" /> ``` In this example, every time `mySelection` changes, Angular automatically sets the `value` property of the `MyListbox` instance. You can bind to directive properties as well. ```angular-html <!-- Bind to the `ngSrc` property of the `NgOptimizedImage` directive --> <img [ngSrc]="profilePhotoUrl" alt="The current user's profile photo"> ``` ### Attributes When you need to set HTML attributes that do not have corresponding DOM properties, such as ARIA attributes or SVG attributes, you can bind attributes to elements in your template with the `attr.` prefix. ```angular-html <!-- Bind the `role` attribute on the `<ul>` element to the component's `listRole` property. --> <ul [attr.role]="listRole"> ``` In this example, every time `listRole` changes, Angular automatically sets the `role` attribute of the `<ul>` element by calling `setAttribute`. If the value of an attribute binding is `null`, Angular removes the attribute by calling `removeAttribute`. ### Text interpolation in properties and attributes You can also use text interpolation syntax in properties and attributes by using the double curly brace syntax instead of square braces around the property or attribute name. When using this syntax, Angular treats the assignment as a property binding. ```angular-html <!-- Binds a value to the `alt` property of the image element's DOM object. --> <img src="profile-photo.jpg" alt="Profile photo of {{ firstName }}" > ``` To bind to an attribute with the text interpolation syntax, prefix the attribute name with `attr.` ```angular-html <button attr.aria-label="Save changes to {{ objectType }}"> ``` ## CSS class and style property bindings Angular supports additional features for binding CSS classes and CSS style properties to elements. ### CSS classes You can create a CSS class binding to conditionally add or remove a CSS class on an element based on whether the bound value is [truthy or falsy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). ```angular-html <!-- When `isExpanded` is truthy, add the `expanded` CSS class. --> <ul [class.expanded]="isExpanded"> ``` You can also bind directly to the `class` property. Angular accepts three types of value: | Description of `class` value | TypeScript type | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | A string containing one or more CSS classes separated by spaces | `string` | | An array of CSS class strings | `string[]` | | An object where each property name is a CSS class name and each corresponding value determines whether that class is applied to the element, based on truthiness. | `Record<string, any>` | ```angular-ts @Component({ template: ` <ul [class]="listClasses"> ... </ul> <section [class]="sectionClasses"> ... </section> <button [class]="buttonClasses"> ... </button> `, ... }) export class UserProfile { listClasses = 'full-width outlined'; sectionClasses = ['expandable', 'elevated']; buttonClasses = { highlighted: true, embiggened: false, }; } ``` The above example renders the following DOM: ```angular-html <ul class="full-width outlined"> ... </ul> <section class="expandable elevated"> ... </section> <button class="highlighted"> ... </button> ``` Angular ignores any string values that are not valid CSS class names. When using static CSS classes, directly binding `class`, and binding specific classes, Angular intelligently combines all of the classes in the rendered result. ```angular-ts @Component({ template: `<ul class="list" [class]="listType" [class.expanded]="isExpanded"> ...`, ... }) export class Listbox { listType = 'box'; isExpanded = true; } ``` In the example above, Angular renders the `ul` element with all three CSS classes. ```angular-html <ul class="list box expanded"> ``` Angular does not guarantee any specific order of CSS classes on rendered elements. When binding `class` to an array or an object, Angular compares the previous value to the current value with the triple-equals operator (`===`). You must create a new object or array instance when you modify these values in order to Angular to apply any updates. If an element has multiple bindings for the same CSS class, Angular resolves collisions by following its style precedence order. ### CSS style properties You can also bind to CSS style properties directly on an element. ```angular-html <!-- Set the CSS `display` property based on the `isExpanded` property. --> <section [style.display]="isExpanded ? 'block' : 'none'"> ``` You can further specify units for CSS properties that accept units. ```angular-html <!-- Set the CSS `height` property to a pixel value based on the `sectionHeightInPixels` property. --> <section [style.height.px]="sectionHeightInPixels"> ``` You can also set multiple style values in one binding. Angular accepts the following types of value: | Description of `style` value | TypeScript type | | ------------------------------------------------------------------------------------------------------------------------- | --------------------- | | A string containing zero or more CSS declarations, such as `"display: flex; margin: 8px"`. | `string` | | An object where each property name is a CSS property name and each corresponding value is the value of that CSS property. | `Record<string, any>` | ```angular-ts @Component({ template: ` <ul [style]="listStyles"> ... </ul> <section [style]="sectionStyles"> ... </section> `, ... }) export class UserProfile { listStyles = 'display: flex; padding: 8px'; sectionStyles = { border: '1px solid black', 'font-weight': 'bold', }; } ``` The above example renders the following DOM. ```angular-html <ul style="display: flex; padding: 8px"> ... </ul> <section style="border: 1px solid black; font-weight: bold"> ... </section> ``` When binding `style` to an object, Angular compares the previous value to the current value with the triple-equals operator (`===`). You must create a new object instance when you modify these values in order to Angular to apply any updates. If an element has multiple bindings for the same style property, Angular resolves collisions by following its style precedence order.
{ "end_byte": 9521, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/binding.md" }
angular/adev/src/content/guide/templates/ng-content.md_0_1073
# Render templates from a parent component with `ng-content` `<ng-content>` is a special element that accepts markup or a template fragment and controls how components render content. It does not render a real DOM element. Here is an example of a `BaseButton` component that accepts any markup from its parent. ```angular-ts // ./base-button/base-button.component.ts import { Component } from '@angular/core'; @Component({ selector: 'button[baseButton]', standalone: true, template: ` <ng-content /> `, }) export class BaseButton {} ``` ```angular-ts // ./app.component.ts import { Component } from '@angular/core'; import { BaseButton } from './base-button/base-button.component.ts'; @Component({ selector: 'app-root', standalone: true, imports: [BaseButton], template: ` <button baseButton> Next <span class="icon arrow-right" /> </button> `, }) export class AppComponent {} ``` For more detail, check out the [`<ng-content>` in-depth guide](/guide/components/content-projection) for other ways you can leverage this pattern.
{ "end_byte": 1073, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/ng-content.md" }
angular/adev/src/content/guide/templates/ng-container.md_0_3768
# Grouping elements with ng-container `<ng-container>` is a special element in Angular that groups multiple elements together or marks a location in a template without rendering a real element in the DOM. ```angular-html <!-- Component template --> <section> <ng-container> <h3>User bio</h3> <p>Here's some info about the user</p> </ng-container> </section> ``` ```angular-html <!-- Rendered DOM --> <section> <h3>User bio</h3> <p>Here's some info about the user</p> </section> ``` You can apply directives to `<ng-container>` to add behaviors or configuration to a part of your template. Angular ignores all attribute bindings and event listeners applied to `<ng-container>`, including those applied via directive. ## Using `<ng-container>` to display dynamic contents `<ng-container>` can act as a placeholder for rendering dynamic content. ### Rendering components You can use Angular's built-in `NgComponentOutlet` directive to dynamically render a component to the location of the `<ng-container>`. ```angular-ts @Component({ template: ` <h2>Your profile</h2> <ng-container [ngComponentOutlet]="profileComponent()" /> ` }) export class UserProfile { isAdmin = input(false); profileComponent = computed(() => this.isAdmin() ? AdminProfile : BasicUserProfile); } ``` In the example above, the `NgComponentOutlet` directive dynamically renders either `AdminProfile` or `BasicUserProfile` in the location of the `<ng-container>` element. ### Rendering template fragments You can use Angular's built-in `NgTemplateOutlet` directive to dynamically render a template fragment to the location of the `<ng-container>`. ```angular-ts @Component({ template: ` <h2>Your profile</h2> <ng-container [ngTemplateOutlet]="profileTemplate()" /> <ng-template #admin>This is the admin profile</ng-template> <ng-template #basic>This is the basic profile</ng-template> ` }) export class UserProfile { isAdmin = input(false); adminTemplate = viewChild('admin', {read: TemplateRef}); basicTemplate = viewChild('basic', {read: TemplateRef}); profileTemplate = computed(() => this.isAdmin() ? this.adminTemplate() : this.basicTemplate()); } ``` In the example above, the `ngTemplateOutlet` directive dynamically renders one of two template fragments in the location of the `<ng-container>` element. For more information regarding NgTemplateOutlet, see the [NgTemplateOutlets API documentation page](/api/common/NgTemplateOutlet). ## Using `<ng-container>` with structural directives You can also apply structural directives to `<ng-container>` elements. Common examples of this include `ngIf`and `ngFor`. ```angular-html <ng-container *ngIf="permissions == 'admin'"> <h1>Admin Dashboard</h1> <admin-infographic></admin-infographic> </ng-container> <ng-container *ngFor="let item of items; index as i; trackBy: trackByFn"> <h2>{{ item.title }}</h2> <p>{{ item.description }}</p> </ng-container> ``` ## Using `<ng-container>` for injection See the Dependency Injection guide for more information on Angular's dependency injection system. When you apply a directive to `<ng-container>`, descendant elements can inject the directive or anything that the directive provides. Use this when you want to declaratively provide a value to a specific part of your template. ```angular-ts @Directive({ selector: '[theme]', }) export class Theme { // Create an input that accepts 'light' or 'dark`, defaulting to 'light'. mode = input<'light' | 'dark'>('light'); } ``` ```angular-html <ng-container theme="dark"> <profile-pic /> <user-bio /> </ng-container> ``` In the example above, the `ProfilePic` and `UserBio` components can inject the `Theme` directive and apply styles based on its `mode`.
{ "end_byte": 3768, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/ng-container.md" }
angular/adev/src/content/guide/templates/ng-template.md_0_8304
# Create template fragments with ng-template Inspired by the [native `<template>` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template), the `<ng-template>` element lets you declare a **template fragment** – a section of content that you can dynamically or programmatically render. ## Creating a template fragment You can create a template fragment inside of any component template with the `<ng-template>` element: ```angular-html <p>This is a normal element</p> <ng-template> <p>This is a template fragment</p> </ng-template> ``` When the above is rendered, the content of the `<ng-template>` element is not rendered on the page. Instead, you can get a reference to the template fragment and write code to dynamically render it. ### Binding context for fragments Template fragments may contain bindings with dynamic expressions: ```angular-ts @Component({ /* ... */, template: `<ng-template>You've selected {{count}} items.</ng-template>`, }) export class ItemCounter { count: number = 0; } ``` Expressions or statements in a template fragment are evaluated against the component in which the fragment is declared, regardless of where the fragment is rendered. ## Getting a reference to a template fragment You can get a reference to a template fragment in one of three ways: - By declaring a [template reference variable](/guide/templates/variables#template-reference-variables) on the `<ng-template>` element - By querying for the fragment with [a component or directive query](/guide/components/queries) - By injecting the fragment in a directive that's applied directly to an `<ng-template>` element. In all three cases, the fragment is represented by a [TemplateRef](/api/core/TemplateRef) object. ### Referencing a template fragment with a template reference variable You can add a template reference variable to an `<ng-template>` element to reference that template fragment in other parts of the same template file: ```angular-html <p>This is a normal element</p> <ng-template #myFragment> <p>This is a template fragment</p> </ng-template> ``` You can then reference this fragment anywhere else in the template via the `myFragment` variable. ### Referencing a template fragment with queries You can get a reference to a template fragment using any [component or directive query API](/guide/components/queries). For example, if your template has exactly one template fragment, you can query directly for the `TemplateRef` object with a `@ViewChild` query: ```angular-ts @Component({ /* ... */, template: ` <p>This is a normal element</p> <ng-template> <p>This is a template fragment</p> </ng-template> `, }) export class ComponentWithFragment { @ViewChild(TemplateRef) myFragment: TemplateRef<unknown> | undefined; } ``` You can then reference this fragment in your component code or the component's template like any other class member. If a template contains multiple fragments, you can assign a name to each fragment by adding a template reference variable to each `<ng-template>` element and querying for the fragments based on that name: ```angular-ts @Component({ /* ... */, template: ` <p>This is a normal element</p> <ng-template #fragmentOne> <p>This is one template fragment</p> </ng-template> <ng-template #fragmentTwo> <p>This is another template fragment</p> </ng-template> `, }) export class ComponentWithFragment { // When querying by name, you can use the `read` option to specify that you want to get the // TemplateRef object associated with the element. @ViewChild('fragmentOne', {read: TemplateRef}) fragmentOne: TemplateRef<unknown> | undefined; @ViewChild('fragmentTwo', {read: TemplateRef}) fragmentTwo: TemplateRef<unknown> | undefined; } ``` Again, you can then reference these fragments in your component code or the component's template like any other class members. ### Injecting a template fragment A directive can inject a `TemplateRef` if that directive is applied directly to an `<ng-template>` element: ```angular-ts @Directive({ selector: '[myDirective]' }) export class MyDirective { private fragment = inject(TemplateRef); } ``` ```angular-html <ng-template myDirective> <p>This is one template fragment</p> </ng-template> ``` You can then reference this fragment in your directive code like any other class member. ## Rendering a template fragment Once you have a reference to a template fragment's `TemplateRef` object, you can render a fragment in one of two ways: in your template with the `NgTemplateOutlet` directive or in your TypeScript code with `ViewContainerRef`. ### Using `NgTemplateOutlet` The `NgTemplateOutlet` directive from `@angular/common` accepts a `TemplateRef` and renders the fragment as a **sibling** to the element with the outlet. You should generally use `NgTemplateOutlet` on an [`<ng-container>` element](/guide/templates/ng-container). The following example declares a template fragment and renders that fragment to a `<ng-container>` element with `NgTemplateOutlet`: ```angular-html <p>This is a normal element</p> <ng-template #myFragment> <p>This is a fragment</p> </ng-template> <ng-container [ngTemplateOutlet]="myFragment" /> ``` This example produces the following rendered DOM: ```angular-html <p>This is a normal element</p> <p>This is a fragment</p> ``` ### Using `ViewContainerRef` A **view container** is a node in Angular's component tree that can contain content. Any component or directive can inject `ViewContainerRef` to get a reference to a view container corresponding to that component or directive's location in the DOM. You can use the `createEmbeddedView` method on `ViewContainerRef` to dynamically render a template fragment. When you render a fragment with a `ViewContainerRef`, Angular appends it into the DOM as the next sibling of the component or directive that injected the `ViewContainerRef`. The following example shows a component that accepts a reference to a template fragment as an input and renders that fragment into the DOM on a button click. ```angular-ts @Component({ /* ... */, selector: 'component-with-fragment', template: ` <h2>Component with a fragment</h2> <ng-template #myFragment> <p>This is the fragment</p> </ng-template> <my-outlet [fragment]="myFragment" /> `, }) export class ComponentWithFragment { } @Component({ /* ... */, selector: 'my-outlet', template: `<button (click)="showFragment()">Show</button>`, }) export class MyOutlet { private viewContainer = inject(ViewContainerRef); @Input() fragment: TemplateRef<unknown> | undefined; showFragment() { if (this.fragment) { this.viewContainer.createEmbeddedView(this.fragment); } } } ``` In the example above, clicking the "Show" button results in the following output: ```angular-html <component-with-fragment> <h2>Component with a fragment> <my-outlet> <button>Show</button> </my-outlet> <p>This is the fragment</p> </component-with-fragment> ``` ## Passing parameters when rendering a template fragment When declaring a template fragment with `<ng-template>`, you can additionally declare parameters accepted by the fragment. When you render a fragment, you can optimally pass a `context` object corresponding to these parameters. You can use data from this context object in binding expressions and statements, in addition to referencing data from the component in which the fragment is declared. Each parameter is written as an attribute prefixed with `let-` with a value matching a property name in the context object: ```angular-html <ng-template let-pizzaTopping="topping"> <p>You selected: {{pizzaTopping}}</p> </ng-template> ``` ### Using `NgTemplateOutlet` You can bind a context object to the `ngTemplateOutletContext` input: ```angular-html <ng-template #myFragment let-pizzaTopping="topping"> <p>You selected: {{pizzaTopping}}</p> </ng-template> <ng-container [ngTemplateOutlet]="myFragment" [ngTemplateOutletContext]="{topping: 'onion'}" /> ``` ### Using `ViewContainerRef` You can pass a context object as the second argument to `createEmbeddedView`: ```angular-ts this.viewContainer.createEmbeddedView(this.myFragment, {topping: 'onion'}); ``` ##
{ "end_byte": 8304, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/ng-template.md" }
angular/adev/src/content/guide/templates/ng-template.md_8304_9587
Structural directives A **structural directive** is any directive that: - Injects `TemplateRef` - Injects `ViewContainerRef` and programmatically renders the injected `TemplateRef` Angular supports a special convenience syntax for structural directives. If you apply the directive to an element and prefix the directive's selector with an asterisk (`*`) character, Angular interprets the entire element and all of its content as a template fragment: ```angular-html <section *myDirective> <p>This is a fragment</p> </section> ``` This is equivalent to: ```angular-html <ng-template myDirective> <section> <p>This is a fragment</p> </section> </ng-template> ``` Developers typically use structural directives to conditionally render fragments or render fragments multiple times. For more details, see [Structural Directives](/guide/directives/structural-directives). ## Additional resources For examples of how `ng-template` is used in other libraries, check out: - [Tabs from Angular Material](https://material.angular.io/components/tabs/overview) - nothing gets rendered into the DOM until the tab is activated - [Table from Angular Material](https://material.angular.io/components/table/overview) - allows developers to define different ways to render data
{ "end_byte": 9587, "start_byte": 8304, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/ng-template.md" }
angular/adev/src/content/guide/templates/control-flow.md_0_5071
# Control flow Angular templates support control flow blocks that let you conditionally show, hide, and repeat elements. Note: This was previously accomplished with the *ngIf, *ngFor, and \*ngSwitch directives. ## Conditionally display content with `@if`, `@else-if` and `@else` The `@if` block conditionally displays its content when its condition expression is truthy: ```angular-html @if (a > b) { <p>{{a}} is greater than {{b}}</p> } ``` If you want to display alternative content, you can do so by providing any number of `@else if` blocks and a singular `@else` block. ```angular-html @if (a > b) { {{a}} is greater than {{b}} } @else if (b > a) { {{a}} is less than {{b}} } @else { {{a}} is equal to {{b}} } ``` ### Referencing the conditional expression's result The `@if` conditional supports saving the result of the conditional expression into a variable for reuse inside of the block. ```angular-html @if (user.profile.settings.startDate; as startDate) { {{ startDate }} } ``` This can be useful for referencing longer expressions that would be easier to read and maintain within the template. ## Repeat content with the `@for` block The `@for` block loops through a collection and repeatedly renders the content of a block. The collection can be any JavaScript [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols), but Angular has additional performance optimizations for `Array` values. A typical `@for` loop looks like: ```angular-html @for (item of items; track item.id) { {{ item.name }} } ``` ### Why is `track` in `@for` blocks important? The `track` expression allows Angular to maintain a relationship between your data and the DOM nodes on the page. This allows Angular to optimize performance by executing the minimum necessary DOM operations when the data changes. Using track effectively can significantly improve your application's rendering performance when looping over data collections. Select a property that uniquely identifies each item in the `track` expression. If your data model includes a uniquely identifying property, commonly `id` or `uuid`, use this value. If your data does not include a field like this, strongly consider adding one. For static collections that never change, you can use `$index` to tell Angular to track each item by its index in the collection. If no other option is available, you can specify `identity`. This tells Angular to track the item by its reference identity using the triple-equals operator (`===`). Avoid this option whenever possible as it can lead to significantly slower rendering updates, as Angular has no way to map which data item corresponds to which DOM nodes. ### Contextual variables in `@for` blocks Inside `@for` blocks, several implicit variables are always available: | Variable | Meaning | | -------- | --------------------------------------------- | | `$count` | Number of items in a collection iterated over | | `$index` | Index of the current row | | `$first` | Whether the current row is the first row | | `$last` | Whether the current row is the last row | | `$even` | Whether the current row index is even | | `$odd` | Whether the current row index is odd | These variables are always available with these names, but can be aliased via a `let` segment: ```angular-html @for (item of items; track item.id; let idx = $index, e = $even) { <p>Item #{{ idx }}: {{ item.name }}</p> } ``` The aliasing is useful when nesting `@for` blocks, letting you read variables from the outer `@for` block from an inner `@for` block. ### Providing a fallback for `@for` blocks with the `@empty` block You can optionally include an `@empty` section immediately after the `@for` block content. The content of the `@empty` block displays when there are no items: ```angular-html @for (item of items; track item.name) { <li> {{ item.name }}</li> } @empty { <li aria-hidden="true"> There are no items. </li> } ``` ## Conditionally display content with the `@switch` block While the `@if` block is great for most scenarios, the `@switch` block provides an alternate syntax to conditionally render data. Its syntax closely resembles JavaScript's `switch` statement. ```angular-html @switch (userPermissions) { @case ('admin') { <app-admin-dashboard /> } @case ('reviewer') { <app-reviewer-dashboard /> } @case ('editor') { <app-editor-dashboard /> } @default { <app-viewer-dashboard /> } } ``` The value of the conditional expression is compared to the case expression using the triple-equals (`===`) operator. **`@switch` does not have a fallthrough**, so you do not need an equivalent to a `break` or `return` statement in the block. You can optionally include a `@default` block. The content of the `@default` block displays if none of the preceding case expressions match the switch value. If no `@case` matches the expression and there is no `@default` block, nothing is shown.
{ "end_byte": 5071, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/control-flow.md" }
angular/adev/src/content/guide/templates/BUILD.bazel_0_257
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "templates", srcs = glob([ "*.md", ]), data = [ "//adev/src/assets/images:templates.svg", ], visibility = ["//adev:__subpackages__"], )
{ "end_byte": 257, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/BUILD.bazel" }
angular/adev/src/content/guide/templates/expression-syntax.md_0_5599
# Expression Syntax Angular expressions are based on JavaScript, but differ in some key ways. This guide walks through the similarities and differences between Angular expressions and standard JavaScript. ## Value literals Angular supports a subset of [literal values](https://developer.mozilla.org/en-US/docs/Glossary/Literal) from JavaScript. ### Supported value literals | Literal type | Example values | | ------------ | ------------------------------- | | String | `'Hello'`, `"World"` | | Boolean | `true`, `false` | | Number | `123`, `3.14` | | Object | `{name: 'Alice'}` | | Array | `['Onion', 'Cheese', 'Garlic']` | | null | `null` | ### Unsupported literals | Literal type | Example value | | --------------- | --------------------- | | Template string | `` `Hello ${name}` `` | | RegExp | `/\d+/` | ## Globals Angular expressions support the following [globals](https://developer.mozilla.org/en-US/docs/Glossary/Global_object): - [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) - [$any](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any) No other JavaScript globals are supported. Common JavaScript globals include `Number`, `Boolean`, `NaN`, `Infinity`, `parseInt`, and more. ## Local variables Angular automatically makes special local variables available for use in expressions in specific contexts. These special variables always start with the dollar sign character (`$`). For example, `@for` blocks make several local variables corresponding to information about the loop, such as `$index`. ## What operators are supported? ### Supported operators Angular supports the following operators from standard JavaScript. | Operator | Example(s) | | --------------------- | ---------------------------------------- | | Add / Concatenate | `1 + 2` | | Subtract | `52 - 3` | | Multiply | `41 * 6` | | Divide | `20 / 4` | | Remainder (Modulo) | `17 % 5` | | Parenthesis | `9 * (8 + 4)` | | Conditional (Ternary) | `a > b ? true : false` | | And (Logical) | `&&` | | Or (Logical) | `\|\|` | | Not (Logical) | `!` | | Nullish Coalescing | `const foo = null ?? 'default'` | | Comparison Operators | `<`, `<=`, `>`, `>=`, `==`, `===`, `!==` | | Unary Negation | `const y = -x` | | Unary Plus | `const x = +y` | | Property Accessor | `person['name'] = 'Mirabel'` | Angular expressions additionally also support the following non-standard operators: | Operator | Example(s) | | ------------------------------- | ------------------------------ | | [Pipe](/guides/templates/pipes) | `{{ total \| currency }}` | | Optional chaining\* | `someObj.someProp?.nestedProp` | | Non-null assertion (TypeScript) | `someObj!.someProp` | \*Note: Optional chaining behaves differently from the standard JavaScript version in that if the left side of Angular’s optional chaining operator is `null` or `undefined`, it returns `null` instead of `undefined`. ### Unsupported operators | Operator | Example(s) | | --------------------- | --------------------------------- | | All bitwise operators | `&`, `&=`, `~`, `\|=`, `^=`, etc. | | Assignment operators | `=` | | Object destructuring | `const { name } = person` | | Array destructuring | `const [firstItem] = items` | | Comma operator | `x = (x++, x)` | | typeof | `typeof 42` | | void | `void 1` | | in | `'model' in car` | | instanceof | `car instanceof Automobile` | | new | `new Car()` | ## Lexical context for expressions Angular expressions are evaluated within the context of the component class as well as any relevant [template variables](/guide/templates/variables), locals, and globals. When referring to class members, `this` is always implied. ## Declarations Generally speaking, declarations are not supported in Angular expressions. This includes, but is not limited to: | Declarations | Example(s) | | --------------- | ------------------------------------------- | | Variables | `let label = 'abc'`, `const item = 'apple'` | | Functions | `function myCustomFunction() { }` | | Arrow Functions | `() => { }` | | Classes | `class Rectangle { }` | # Event listener statements Event handlers are **statements** rather than expressions. While they support all of the same syntax as Angular expressions, the are two key differences: 1. Statements **do support** assignment operators (but not destructing assignments) 1. Statements **do not support** pipes
{ "end_byte": 5599, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/expression-syntax.md" }
angular/adev/src/content/guide/templates/variables.md_0_7027
# Variables in templates Angular has two types of variable declarations in templates: local template variables and template reference variables. ## Local template variables with `@let` Angular's `@let` syntax allows you to define a local variable and re-use it across a template, similar to the [JavaScript `let` syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let). ### Using `@let` Use `@let` to declare a variable whose value is based on the result of a template expression. Angular automatically keeps the variable's value up-to-date with the given expression, similar to [bindings](./bindings). ```angular-html @let name = user.name; @let greeting = 'Hello, ' + name; @let data = data$ | async; @let pi = 3.1459; @let coordinates = {x: 50, y: 100}; @let longExpression = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit ' + 'sed do eiusmod tempor incididunt ut labore et dolore magna ' + 'Ut enim ad minim veniam...'; ``` Each `@let` block can declare exactly one variable. You cannot declare multiple variables in the same block with a comma. ### Referencing the value of `@let` Once you've declared a variable with `@let`, you can reuse it in the same template: ```angular-html @let user = user$ | async; @if (user) { <h1>Hello, {{user.name}}</h1> <user-avatar [photo]="user.photo"/> <ul> @for (snack of user.favoriteSnacks; track snack.id) { <li>{{snack.name}}</li> } </ul> <button (click)="update(user)">Update profile</button> } ``` ### Assignability A key difference between `@let` and JavaScript's `let` is that `@let` cannot be reassigned after declaration. However, Angular automatically keeps the variable's value up-to-date with the given expression. ```angular-html @let value = 1; <!-- Invalid - This does not work! --> <button (click)="value = value + 1">Increment the value</button> ``` ### Variable scope `@let` declarations are scoped to the current view and its descendants. Angular creates a new view at component boundaries and wherever a template might contain dynamic content, such as control flow blocks, `@defer` blocks, or structural directives. Since `@let` declarations are not hoisted, they **cannot** be accessed by parent views or siblings: ```angular-html @let topLevel = value; <div> @let insideDiv = value; </div> {{topLevel}} <!-- Valid --> {{insideDiv}} <!-- Valid --> @if (condition) { {{topLevel + insideDiv}} <!-- Valid --> @let nested = value; @if (condition) { {{topLevel + insideDiv + nested}} <!-- Valid --> } } <div *ngIf="condition"> {{topLevel + insideDiv}} <!-- Valid --> @let nestedNgIf = value; <div *ngIf="condition"> {{topLevel + insideDiv + nestedNgIf}} <!-- Valid --> </div> </div> {{nested}} <!-- Error, not hoisted from @if --> {{nestedNgIf}} <!-- Error, not hoisted from *ngIf --> ``` ### Full syntax The `@let` syntax is formally defined as: - The `@let` keyword. - Followed by one or more whitespaces, not including new lines. - Followed by a valid JavaScript name and zero or more whitespaces. - Followed by the = symbol and zero or more whitespaces. - Followed by an Angular expression which can be multi-line. - Terminated by the `;` symbol. ## Template reference variables Template reference variables give you a way to declare a variable that references a value from an element in your template. A template reference variable can refer to the following: - a DOM element within a template (including [custom elements](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements)) - an Angular component or directive - a [TemplateRef](/api/core/TemplateRef) from an [ng-template](/api/core/ng-template) You can use template reference variables to read information from one part of the template in another part of the same template. ### Declaring a template reference variable You can declare a variable on an element in a template by adding an attribute that starts with the hash character (`#`) followed by the variable name. ```angular-html <!-- Create a template reference variable named "taskInput", referring to the HTMLInputElement. --> <input #taskInput placeholder="Enter task name"> ``` ### Assigning values to template reference variables Angular assigns a value to template variables based on the element on which the variable is declared. If you declare the variable on a Angular component, the variable refers to the component instance. ```angular-html <!-- The `startDate` variable is assigned the instance of `MyDatepicker`. --> <my-datepicker #startDate /> ``` If you declare the variable on an `<ng-template>` element, the variable refers to a TemplateRef instance which represents the template. For more information, see [How Angular uses the asterisk, \*, syntax](/guide/directives/structural-directives#asterisk) in [Structural directives](/guide/directives/structural-directives). ```angular-html <!-- The `myFragment` variable is assigned the `TemplateRef` instance corresponding to this template fragment. --> <ng-template #myFragment> <p>This is a template fragment</p> </ng-template> ``` If you declare the variable on any other displayed element, the variable refers to the `HTMLElement` instance. ```angular-html <!-- The "taskInput" variable refers to the HTMLInputElement instance. --> <input #taskInput placeholder="Enter task name"> ``` #### Assigning a reference to an Angular directive Angular directives may have an `exportAs` property that defines a name by which the directive can be referenced in a template: ```angular-ts @Directive({ selector: '[dropZone]', exportAs: 'dropZone', }) export class DropZone { /* ... */ } ``` When you declare a template variable on an element, you can assign that variable a directive instance by specifying this `exportAs` name: ```angular-html <!-- The `firstZone` variable refers to the `DropZone` directive instance. --> <section dropZone #firstZone="dropZone"> ... </section> ``` You cannot refer to a directive that does not specify an `exportAs` name. ### Using template reference variables with queries In addition to using template variables to read values from another part of the same template, you can also use this style of variable declaration to "mark" an element for [component and directive queries](/guide/components/queries). When you want to query for a specific element in a template, you can declare a template variable on that element and then query for the element based on the variable name. ```angular-html <input #description value="Original description"> ``` ```angular-ts @Component({ /* ... */, template: `<input #description value="Original description">`, }) export class AppComponent { // Query for the input element based on the template variable name. @ViewChild('description') input: ElementRef | undefined; } ``` See [Referencing children with queries](/guide/components/queries) for more information on queries.
{ "end_byte": 7027, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/templates/variables.md" }
angular/adev/src/content/guide/routing/overview.md_0_1490
<docs-decorative-header title="Angular Routing" imgSrc="adev/src/assets/images/routing.svg"> <!-- markdownlint-disable-line --> Routing helps you change what the user sees in a single-page app. </docs-decorative-header> In a single-page app, you change what the user sees by showing or hiding portions of the display that correspond to particular components, rather than going out to the server to get a new page. As users perform application tasks, they need to move between the different views that you have defined. To handle the navigation from one view to the next, you use the Angular **`Router`**. The **`Router`** enables navigation by interpreting a browser URL as an instruction to change the view. ## Learn about Angular routing <docs-card-container> <docs-card title="Common routing tasks" href="guide/routing/common-router-tasks"> Learn how to implement many of the common tasks associated with Angular routing. </docs-card> <docs-card title="Routing SPA tutorial" href="guide/routing/router-tutorial"> A tutorial that covers patterns associated with Angular routing. </docs-card> <docs-card title="Creating custom route matches tutorial" href="guide/routing/routing-with-urlmatcher"> A tutorial that covers how to use custom matching strategy patterns with Angular routing. </docs-card> <docs-card title="Router reference" href="guide/routing/router-reference"> Describes some core router API concepts. </docs-card> </docs-card-container>
{ "end_byte": 1490, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/overview.md" }
angular/adev/src/content/guide/routing/routing-with-urlmatcher.md_0_5053
# Creating custom route matches The Angular Router supports a powerful matching strategy that you can use to help users navigate your application. This matching strategy supports static routes, variable routes with parameters, wildcard routes, and so on. Also, build your own custom pattern matching for situations in which the URLs are more complicated. In this tutorial, you'll build a custom route matcher using Angular's `UrlMatcher`. This matcher looks for a Twitter handle in the URL. ## Objectives Implement Angular's `UrlMatcher` to create a custom route matcher. ## Create a sample application Using the Angular CLI, create a new application, *angular-custom-route-match*. In addition to the default Angular application framework, you will also create a *profile* component. 1. Create a new Angular project, *angular-custom-route-match*. ```shell ng new angular-custom-route-match ``` When prompted with `Would you like to add Angular routing?`, select `Y`. When prompted with `Which stylesheet format would you like to use?`, select `CSS`. After a few moments, a new project, `angular-custom-route-match`, is ready. 1. From your terminal, navigate to the `angular-custom-route-match` directory. 1. Create a component, *profile*. ```shell ng generate component profile ``` 1. In your code editor, locate the file, `profile.component.html` and replace the placeholder content with the following HTML. <docs-code header="src/app/profile/profile.component.html" path="adev/src/content/examples/routing-with-urlmatcher/src/app/profile/profile.component.html"/> 1. In your code editor, locate the file, `app.component.html` and replace the placeholder content with the following HTML. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/routing-with-urlmatcher/src/app/app.component.html"/> ## Configure your routes for your application With your application framework in place, you next need to add routing capabilities to the `app.config.ts` file. As a part of this process, you will create a custom URL matcher that looks for a Twitter handle in the URL. This handle is identified by a preceding `@` symbol. 1. In your code editor, open your `app.config.ts` file. 1. Add an `import` statement for Angular's `provideRouter` and `withComponentInputBinding` as well as the application routes. ```ts import {provideRouter, withComponentInputBinding} from '@angular/router'; import {routes} from './app.routes'; ``` 1. In the providers array, add a `provideRouter(routes, withComponentInputBinding())` statement. 1. Define the custom route matcher by adding the following code to the application routes. <docs-code header="src/app/app.routes.ts" path="adev/src/content/examples/routing-with-urlmatcher/src/app/app.routes.ts" visibleRegion="matcher"/> This custom matcher is a function that performs the following tasks: * The matcher verifies that the array contains only one segment * The matcher employs a regular expression to ensure that the format of the username is a match * If there is a match, the function returns the entire URL, defining a `username` route parameter as a substring of the path * If there isn't a match, the function returns null and the router continues to look for other routes that match the URL HELPFUL: A custom URL matcher behaves like any other route definition. Define child routes or lazy loaded routes as you would with any other route. ## Reading the route parameters With the custom matcher in place, you can now bind the route parameter in the `profile` component. In your code editor, open your `profile.component.ts` file and create an `Input` matching the `username` parameter. We added the `withComponentInputBinding` feature earlier in `provideRouter`. This allows the `Router` to bind information directly to the route components. ```ts @Input() username!: string; ``` ## Test your custom URL matcher With your code in place, you can now test your custom URL matcher. 1. From a terminal window, run the `ng serve` command. <docs-code language="shell"> ng serve </docs-code> 1. Open a browser to `http://localhost:4200`. You should see a single web page, consisting of a sentence that reads `Navigate to my profile`. 1. Click the **my profile** hyperlink. A new sentence, reading `Hello, Angular!` appears on the page. ## Next steps Pattern matching with the Angular Router provides you with a lot of flexibility when you have dynamic URLs in your application. To learn more about the Angular Router, see the following topics: <docs-pill-row> <docs-pill href="guide/routing/common-router-tasks" title="In-app Routing and Navigation"/> <docs-pill href="api/router/Router" title="Router API"/> </docs-pill-row> HELPFUL: This content is based on [Custom Route Matching with the Angular Router](https://medium.com/@brandontroberts/custom-route-matching-with-the-angular-router-fbdd48665483), by [Brandon Roberts](https://twitter.com/brandontroberts).
{ "end_byte": 5053, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/routing-with-urlmatcher.md" }
angular/adev/src/content/guide/routing/common-router-tasks.md_0_8144
# Common Routing Tasks This topic describes how to implement many of the common tasks associated with adding the Angular router to your application. ## Generate an application with routing enabled The following command uses the Angular CLI to generate a basic Angular application with application routes. The application name in the following example is `routing-app`. ```shell ng new routing-app ``` ### Adding components for routing To use the Angular router, an application needs to have at least two components so that it can navigate from one to the other. To create a component using the CLI, enter the following at the command line where `first` is the name of your component: ```shell ng generate component first ``` Repeat this step for a second component but give it a different name. Here, the new name is `second`. <docs-code language="shell"> ng generate component second </docs-code> The CLI automatically appends `Component`, so if you were to write `first-component`, your component would be `FirstComponentComponent`. <docs-callout title="`base href`"> This guide works with a CLI-generated Angular application. If you are working manually, make sure that you have `<base href="/">` in the `<head>` of your index.html file. This assumes that the `app` folder is the application root, and uses `"/"`. </docs-callout> ### Importing your new components To use your new components, import them into `app.routes.ts` at the top of the file, as follows: <docs-code language="ts"> import {FirstComponent} from './first/first.component'; import {SecondComponent} from './second/second.component'; </docs-code> ## Defining a basic route There are three fundamental building blocks to creating a route. Import the routes into `app.config.ts` and add it to the `provideRouter` function. The following is the default `ApplicationConfig` using the CLI. <docs-code language="ts"> export const appConfig: ApplicationConfig = { providers: [provideRouter(routes)] }; </docs-code> The Angular CLI performs this step for you. However, if you are creating an application manually or working with an existing, non-CLI application, verify that the imports and configuration are correct. <docs-workflow> <docs-step title="Set up a `Routes` array for your routes"> The Angular CLI performs this step automatically. ```ts import { Routes } from '@angular/router'; export const routes: Routes = []; ``` </docs-step> <docs-step title="Define your routes in your `Routes` array"> Each route in this array is a JavaScript object that contains two properties. The first property, `path`, defines the URL path for the route. The second property, `component`, defines the component Angular should use for the corresponding path. ```ts const routes: Routes = [ { path: 'first-component', component: FirstComponent }, { path: 'second-component', component: SecondComponent }, ]; ``` </docs-step> <docs-step title="Add your routes to your application"> Now that you have defined your routes, add them to your application. First, add links to the two components. Assign the anchor tag that you want to add the route to the `routerLink` attribute. Set the value of the attribute to the component to show when a user clicks on each link. Next, update your component template to include `<router-outlet>`. This element informs Angular to update the application view with the component for the selected route. ```angular-html <h1>Angular Router App</h1> <nav> <ul> <li><a routerLink="/first-component" routerLinkActive="active" ariaCurrentWhenActive="page">First Component</a></li> <li><a routerLink="/second-component" routerLinkActive="active" ariaCurrentWhenActive="page">Second Component</a></li> </ul> </nav> <!-- The routed views render in the <router-outlet>--> <router-outlet></router-outlet> ``` You also need to add the `RouterLink`, `RouterLinkActive`, and `RouterOutlet` to the `imports` array of `AppComponent`. ```ts @Component({ selector: 'app-root', standalone: true, imports: [CommonModule, RouterOutlet, RouterLink, RouterLinkActive], templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'routing-app'; } ``` </docs-step> </docs-workflow> ### Route order The order of routes is important because the `Router` uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. List routes with a static path first, followed by an empty path route, which matches the default route. The [wildcard route](guide/routing/common-router-tasks#setting-up-wildcard-routes) comes last because it matches every URL and the `Router` selects it only if no other routes match first. ## Getting route information Often, as a user navigates your application, you want to pass information from one component to another. For example, consider an application that displays a shopping list of grocery items. Each item in the list has a unique `id`. To edit an item, users click an Edit button, which opens an `EditGroceryItem` component. You want that component to retrieve the `id` for the grocery item so it can display the right information to the user. Use a route to pass this type of information to your application components. To do so, you use the [withComponentInputBinding](api/router/withComponentInputBinding) feature with `provideRouter` or the `bindToComponentInputs` option of `RouterModule.forRoot`. To get information from a route: <docs-workflow> <docs-step title="Add `withComponentInputBinding`"> Add the `withComponentInputBinding` feature to the `provideRouter` method. ```ts providers: [ provideRouter(appRoutes, withComponentInputBinding()), ] ``` </docs-step> <docs-step title="Add an `Input` to the component"> Update the component to have an `Input` matching the name of the parameter. ```ts @Input() set id(heroId: string) { this.hero$ = this.service.getHero(heroId); } ``` NOTE: You can bind all route data with key, value pairs to component inputs: static or resolved route data, path parameters, matrix parameters, and query parameters. If you want to use the parent components route info you will need to set the router `paramsInheritanceStrategy` option: `withRouterConfig({paramsInheritanceStrategy: 'always'})` </docs-step> </docs-workflow> ## Setting up wildcard routes A well-functioning application should gracefully handle when users attempt to navigate to a part of your application that does not exist. To add this functionality to your application, you set up a wildcard route. The Angular router selects this route any time the requested URL doesn't match any router paths. To set up a wildcard route, add the following code to your `routes` definition. <docs-code> { path: '**', component: <component-name> } </docs-code> The two asterisks, `**`, indicate to Angular that this `routes` definition is a wildcard route. For the component property, you can define any component in your application. Common choices include an application-specific `PageNotFoundComponent`, which you can define to [display a 404 page](guide/routing/common-router-tasks#displaying-a-404-page) to your users; or a redirect to your application's main component. A wildcard route is the last route because it matches any URL. For more detail on why order matters for routes, see [Route order](guide/routing/common-router-tasks#route-order). ## Displaying a 404 page To display a 404 page, set up a [wildcard route](guide/routing/common-router-tasks#setting-up-wildcard-routes) with the `component` property set to the component you'd like to use for your 404 page as follows: ```ts const routes: Routes = [ { path: 'first-component', component: FirstComponent }, { path: 'second-component', component: SecondComponent }, { path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page ]; ``` The last route with the `path` of `**` is a wildcard route. The router selects this route if the requested URL doesn't match any of the paths earlier in the list and sends the user to the `PageNotFoundComponent`.
{ "end_byte": 8144, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/common-router-tasks.md" }
angular/adev/src/content/guide/routing/common-router-tasks.md_8144_16645
## Setting up redirects To set up a redirect, configure a route with the `path` you want to redirect from, the `component` you want to redirect to, and a `pathMatch` value that tells the router how to match the URL. ```ts const routes: Routes = [ { path: 'first-component', component: FirstComponent }, { path: 'second-component', component: SecondComponent }, { path: '', redirectTo: '/first-component', pathMatch: 'full' }, // redirect to `first-component` { path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page ]; ``` In this example, the third route is a redirect so that the router defaults to the `first-component` route. Notice that this redirect precedes the wildcard route. Here, `path: ''` means to use the initial relative URL \(`''`\). Sometimes a redirect is not a simple, static redirect. The `redirectTo` property can also be a function with more complex logic that returns a string or `UrlTree`. ```ts const routes: Routes = [ { path: "first-component", component: FirstComponent }, { path: "old-user-page", redirectTo: ({ queryParams }) => { const errorHandler = inject(ErrorHandler); const userIdParam = queryParams['userId']; if (userIdParam !== undefined) { return `/user/${userIdParam}`; } else { errorHandler.handleError(new Error('Attempted navigation to user page without user ID.')); return `/not-found`; } }, }, { path: "user/:userId", component: OtherComponent }, ]; ``` ## Nesting routes As your application grows more complex, you might want to create routes that are relative to a component other than your root component. These types of nested routes are called child routes. This means you're adding a second `<router-outlet>` to your app, because it is in addition to the `<router-outlet>` in `AppComponent`. In this example, there are two additional child components, `child-a`, and `child-b`. Here, `FirstComponent` has its own `<nav>` and a second `<router-outlet>` in addition to the one in `AppComponent`. ```angular-html <h2>First Component</h2> <nav> <ul> <li><a routerLink="child-a">Child A</a></li> <li><a routerLink="child-b">Child B</a></li> </ul> </nav> <router-outlet></router-outlet> ``` A child route is like any other route, in that it needs both a `path` and a `component`. The one difference is that you place child routes in a `children` array within the parent route. ```ts 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 }, ], }, ]; ``` ## Setting the page title Each page in your application should have a unique title so that they can be identified in the browser history. The `Router` sets the document's title using the `title` property from the `Route` config. ```ts const routes: Routes = [ { path: 'first-component', title: 'First component', component: FirstComponent, // this is the component with the <router-outlet> in the template children: [ { path: 'child-a', // child route path title: resolvedChildATitle, component: ChildAComponent, // child route component that the router renders }, { path: 'child-b', title: 'child b', component: ChildBComponent, // another child route component that the router renders }, ], }, ]; const resolvedChildATitle: ResolveFn<string> = () => Promise.resolve('child a'); ``` HELPFUL: The `title` property follows the same rules as static route `data` and dynamic values that implement `ResolveFn`. You can also provide a custom title strategy by extending the `TitleStrategy`. ```ts @Injectable({providedIn: 'root'}) export class TemplatePageTitleStrategy extends TitleStrategy { constructor(private readonly title: Title) { super(); } override updateTitle(routerState: RouterStateSnapshot) { const title = this.buildTitle(routerState); if (title !== undefined) { this.title.setTitle(`My Application | ${title}`); } } } export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes), {provide: TitleStrategy, useClass: TemplatePageTitleStrategy}, ] }; ``` ## Using relative paths Relative paths let you define paths that are relative to the current URL segment. The following example shows a relative route to another component, `second-component`. `FirstComponent` and `SecondComponent` are at the same level in the tree, however, the link to `SecondComponent` is situated within the `FirstComponent`, meaning that the router has to go up a level and then into the second directory to find the `SecondComponent`. Rather than writing out the whole path to get to `SecondComponent`, use the `../` notation to go up a level. ```angular-html <h2>First Component</h2> <nav> <ul> <li><a routerLink="../second-component">Relative Route to second component</a></li> </ul> </nav> <router-outlet></router-outlet> ``` In addition to `../`, use `./` or no leading slash to specify the current level. ### Specifying a relative route To specify a relative route, use the `NavigationExtras` `relativeTo` property. In the component class, import `NavigationExtras` from the `@angular/router`. Then use `relativeTo` in your navigation method. After the link parameters array, which here contains `items`, add an object with the `relativeTo` property set to the `ActivatedRoute`, which is `this.route`. ```ts goToItems() { this.router.navigate(['items'], { relativeTo: this.route }); } ``` The `navigate()` arguments configure the router to use the current route as a basis upon which to append `items`. The `goToItems()` method interprets the destination URI as relative to the activated route and navigates to the `items` route. ## Accessing query parameters and fragments Sometimes, a feature of your application requires accessing a part of a route, such as a query parameter or a fragment. In this example, the route contains an `id` parameter we can use to target a specific hero page. ```ts import {ApplicationConfig} from "@angular/core"; import {Routes} from '@angular/router'; import {HeroListComponent} from './hero-list.component'; export const routes: Routes = [ {path: 'hero/:id', component: HeroDetailComponent} ]; export const appConfig: ApplicationConfig = { providers: [provideRouter(routes)], }; ``` First, import the following members in the component you want to navigate from. ```ts import { ActivatedRoute } from '@angular/router'; import { Observable } from 'rxjs'; import { switchMap } from 'rxjs/operators'; ``` Next inject the activated route service: ```ts constructor(private route: ActivatedRoute) {} ``` Configure the class so that you have an observable, `heroes$`, a `selectedId` to hold the `id` number of the hero, and the heroes in the `ngOnInit()`, add the following code to get the `id` of the selected hero. This code snippet assumes that you have a heroes list, a hero service, a function to get your heroes, and the HTML to render your list and details, just as in the Tour of Heroes example. ```ts heroes$: Observable<Hero[]>; selectedId: number; heroes = HEROES; ngOnInit() { this.heroes$ = this.route.paramMap.pipe( switchMap(params => { this.selectedId = Number(params.get('id')); return this.service.getHeroes(); }) ); } ``` Next, in the component that you want to navigate to, import the following members. ```ts import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { Observable } from 'rxjs'; ``` Inject `ActivatedRoute` and `Router` in the constructor of the component class so they are available to this component: ```ts hero$: Observable<Hero>; constructor( private route: ActivatedRoute, private router: Router ) {} ngOnInit() { const heroId = this.route.snapshot.paramMap.get('id'); this.hero$ = this.service.getHero(heroId); } gotoItems(hero: Hero) { const heroId = hero ? hero.id : null; // Pass along the hero id if available // so that the HeroList component can select that item. this.router.navigate(['/heroes', { id: heroId }]); } ```
{ "end_byte": 16645, "start_byte": 8144, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/common-router-tasks.md" }
angular/adev/src/content/guide/routing/common-router-tasks.md_16645_24193
## Lazy loading You can configure your routes to lazy load modules, which means that Angular only loads modules as needed, rather than loading all modules when the application launches. Additionally, preload parts of your application in the background to improve the user experience. Any route can lazily load its routed, standalone component by using `loadComponent:` <docs-code header="Lazy loading a standalone component" language="typescript"> const routes: Routes = [ { path: 'lazy', loadComponent: () => import('./lazy.component').then(c => c.LazyComponent) } ]; </docs-code> This works as long as the loaded component is standalone. For more information on lazy loading and preloading see the dedicated guide [Lazy loading](guide/ngmodules/lazy-loading). ## Preventing unauthorized access Use route guards to prevent users from navigating to parts of an application without authorization. The following route guards are available in Angular: <docs-pill-row> <docs-pill href="api/router/CanActivateFn" title="`canActivate`"/> <docs-pill href="api/router/CanActivateChildFn" title="`canActivateChild`"/> <docs-pill href="api/router/CanDeactivateFn" title="`canDeactivate`"/> <docs-pill href="api/router/CanMatchFn" title="`canMatch`"/> <docs-pill href="api/router/ResolveFn" title="`resolve`"/> <docs-pill href="api/router/CanLoadFn" title="`canLoad`"/> </docs-pill-row> To use route guards, consider using [component-less routes](api/router/Route#componentless-routes) as this facilitates guarding child routes. Create a file for your guard: ```bash ng generate guard your-guard ``` In your guard file, add the guard functions you want to use. The following example uses `canActivateFn` to guard the route. ```ts export const yourGuardFunction: CanActivateFn = ( next: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { // your logic goes here } ``` In your routing module, use the appropriate property in your `routes` configuration. Here, `canActivate` tells the router to mediate navigation to this particular route. ```ts { path: '/your-path', component: YourComponent, canActivate: [yourGuardFunction], } ``` ## Link parameters array A link parameters array holds the following ingredients for router navigation: - The path of the route to the destination component - Required and optional route parameters that go into the route URL Bind the `RouterLink` directive to such an array like this: ```angular-html <a [routerLink]="['/heroes']">Heroes</a> ``` The following is a two-element array when specifying a route parameter: ```angular-html <a [routerLink]="['/hero', hero.id]"> <span class="badge">{{ hero.id }}</span>{{ hero.name }} </a> ``` Provide optional route parameters in an object, as in `{ foo: 'foo' }`: ```angular-html <a [routerLink]="['/crisis-center', { foo: 'foo' }]">Crisis Center</a> ``` These three examples cover the needs of an application with one level of routing. However, with a child router, such as in the crisis center, you create new link array possibilities. The following minimal `RouterLink` example builds upon a specified default child route for the crisis center. ```angular-html <a [routerLink]="['/crisis-center']">Crisis Center</a> ``` Review the following: - The first item in the array identifies the parent route \(`/crisis-center`\) - There are no parameters for this parent route - There is no default for the child route so you need to pick one - You're navigating to the `CrisisListComponent`, whose route path is `/`, but you don't need to explicitly add the slash Consider the following router link that navigates from the root of the application down to the Dragon Crisis: ```angular-html <a [routerLink]="['/crisis-center', 1]">Dragon Crisis</a> ``` - The first item in the array identifies the parent route \(`/crisis-center`\) - There are no parameters for this parent route - The second item identifies the child route details about a particular crisis \(`/:id`\) - The details child route requires an `id` route parameter - You added the `id` of the Dragon Crisis as the second item in the array \(`1`\) - The resulting path is `/crisis-center/1` You could also redefine the `AppComponent` template with Crisis Center routes exclusively: ```angular-ts @Component({ template: ` <h1 class="title">Angular Router</h1> <nav> <a [routerLink]="['/crisis-center']">Crisis Center</a> <a [routerLink]="['/crisis-center/1', { foo: 'foo' }]">Dragon Crisis</a> <a [routerLink]="['/crisis-center/2']">Shark Crisis</a> </nav> <router-outlet></router-outlet> ` }) export class AppComponent {} ``` In summary, you can write applications with one, two or more levels of routing. The link parameters array affords the flexibility to represent any routing depth and any legal sequence of route paths, \(required\) router parameters, and \(optional\) route parameter objects. ## `LocationStrategy` and browser URL styles When the router navigates to a new component view, it updates the browser's location and history with a URL for that view. Modern HTML5 browsers support [history.pushState](https://developer.mozilla.org/docs/Web/API/History_API/Working_with_the_History_API#adding_and_modifying_history_entries 'HTML5 browser history push-state'), a technique that changes a browser's location and history without triggering a server page request. The router can compose a "natural" URL that is indistinguishable from one that would otherwise require a page load. Here's the Crisis Center URL in this "HTML5 pushState" style: ```text localhost:3002/crisis-center ``` Older browsers send page requests to the server when the location URL changes unless the change occurs after a "#" \(called the "hash"\). Routers can take advantage of this exception by composing in-application route URLs with hashes. Here's a "hash URL" that routes to the Crisis Center. ```text localhost:3002/src/#/crisis-center ``` The router supports both styles with two `LocationStrategy` providers: | Providers | Details | | :--------------------- | :----------------------------------- | | `PathLocationStrategy` | The default "HTML5 pushState" style. | | `HashLocationStrategy` | The "hash URL" style. | The `RouterModule.forRoot()` function sets the `LocationStrategy` to the `PathLocationStrategy`, which makes it the default strategy. You also have the option of switching to the `HashLocationStrategy` with an override during the bootstrapping process. HELPFUL: For more information on providers and the bootstrap process, see [Dependency Injection](guide/di/dependency-injection-providers). ## Choosing a routing strategy You must choose a routing strategy early in the development of your project because once the application is in production, visitors to your site use and depend on application URL references. Almost all Angular projects should use the default HTML5 style. It produces URLs that are easier for users to understand and it preserves the option to do server-side rendering. Rendering critical pages on the server is a technique that can greatly improve perceived responsiveness when the application first loads. An application that would otherwise take ten or more seconds to start could be rendered on the server and delivered to the user's device in less than a second. This option is only available if application URLs look like normal web URLs without hash \(`#`\) characters in the middle.
{ "end_byte": 24193, "start_byte": 16645, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/common-router-tasks.md" }
angular/adev/src/content/guide/routing/common-router-tasks.md_24193_28286
## `<base href>` The router uses the browser's [history.pushState](https://developer.mozilla.org/docs/Web/API/History_API/Working_with_the_History_API#adding_and_modifying_history_entries 'HTML5 browser history push-state') for navigation. `pushState` lets you customize in-application URL paths; for example, `localhost:4200/crisis-center`. The in-application URLs can be indistinguishable from server URLs. Modern HTML5 browsers were the first to support `pushState` which is why many people refer to these URLs as "HTML5 style" URLs. HELPFUL: HTML5 style navigation is the router default. In the [LocationStrategy and browser URL styles](#locationstrategy-and-browser-url-styles) section, learn why HTML5 style is preferable, how to adjust its behavior, and how to switch to the older hash \(`#`\) style, if necessary. You must add a [`<base href>` element](https://developer.mozilla.org/docs/Web/HTML/Element/base 'base href') to the application's `index.html` for `pushState` routing to work. The browser uses the `<base href>` value to prefix relative URLs when referencing CSS files, scripts, and images. Add the `<base>` element just after the `<head>` tag. If the `app` folder is the application root, as it is for this application, set the `href` value in `index.html` as shown here. <docs-code header="src/index.html (base-href)" path="adev/src/content/examples/router/src/index.html" visibleRegion="base-href"/> ### HTML5 URLs and the `<base href>` The guidelines that follow will refer to different parts of a URL. This diagram outlines what those parts refer to: <docs-code hideCopy language="text"> foo://example.com:8042/over/there?name=ferret#nose \_/ \______________/\_________/ \_________/ \__/ | | | | | scheme authority path query fragment </docs-code> While the router uses the [HTML5 pushState](https://developer.mozilla.org/docs/Web/API/History_API#Adding_and_modifying_history_entries 'Browser history push-state') style by default, you must configure that strategy with a `<base href>`. The preferred way to configure the strategy is to add a [`<base href>` element](https://developer.mozilla.org/docs/Web/HTML/Element/base 'base href') tag in the `<head>` of the `index.html`. ```angular-html <base href="/"> ``` Without that tag, the browser might not be able to load resources \(images, CSS, scripts\) when "deep linking" into the application. Some developers might not be able to add the `<base>` element, perhaps because they don't have access to `<head>` or the `index.html`. Those developers can still use HTML5 URLs by taking the following two steps: 1. Provide the router with an appropriate `APP_BASE_HREF` value. 1. Use root URLs \(URLs with an `authority`\) for all web resources: CSS, images, scripts, and template HTML files. - The `<base href>` `path` should end with a "/", as browsers ignore characters in the `path` that follow the right-most "`/`" - If the `<base href>` includes a `query` part, the `query` is only used if the `path` of a link in the page is empty and has no `query`. This means that a `query` in the `<base href>` is only included when using `HashLocationStrategy`. - If a link in the page is a root URL \(has an `authority`\), the `<base href>` is not used. In this way, an `APP_BASE_HREF` with an authority will cause all links created by Angular to ignore the `<base href>` value. - A fragment in the `<base href>` is _never_ persisted For more complete information on how `<base href>` is used to construct target URIs, see the [RFC](https://tools.ietf.org/html/rfc3986#section-5.2.2) section on transforming references. ### `HashLocationStrategy` Use `HashLocationStrategy` by providing the `useHash: true` in an object as the second argument of the `RouterModule.forRoot()` in the `AppModule`. ```ts providers: [ provideRouter(appRoutes, withHashLocation()) ] ``` When using `RouterModule.forRoot`, this is configured with the `useHash: true` in the second argument: `RouterModule.forRoot(routes, {useHash: true})`.
{ "end_byte": 28286, "start_byte": 24193, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/common-router-tasks.md" }
angular/adev/src/content/guide/routing/router-reference.md_0_9740
# Router reference The following sections highlight some core router concepts. ## Router imports The Angular Router is an optional service that presents a particular component view for a given URL. It isn't part of the Angular core and thus is in its own library package, `@angular/router`. Import what you need from it as you would from any other Angular package. ```ts import { provideRouter } from '@angular/router'; ``` HELPFUL: For more on browser URL styles, see [`LocationStrategy` and browser URL styles](guide/routing/common-router-tasks#browser-url-styles). ## Configuration A routed Angular application has one singleton instance of the `Router` service. When the browser's URL changes, that router looks for a corresponding `Route` from which it can determine the component to display. A router has no routes until you configure it. The following example creates five route definitions, configures the router via the `provideRouter` method, and adds the result to the `providers` array of the `ApplicationConfig`'. ```ts const appRoutes: Routes = [ { path: 'crisis-center', component: CrisisListComponent }, { path: 'hero/:id', component: HeroDetailComponent }, { path: 'heroes', component: HeroListComponent, data: { title: 'Heroes List' } }, { path: '', redirectTo: '/heroes', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]; export const appConfig: ApplicationConfig = { providers: [provideRouter(appRoutes, withDebugTracing())] } ``` The `routes` array of routes describes how to navigate. Pass it to the `provideRouter` method in the `ApplicationConfig` `providers` to configure the router. Each `Route` maps a URL `path` to a component. There are no leading slashes in the path. The router parses and builds the final URL for you, which lets you use both relative and absolute paths when navigating between application views. The `:id` in the second route is a token for a route parameter. In a URL such as `/hero/42`, "42" is the value of the `id` parameter. The corresponding `HeroDetailComponent` uses that value to find and present the hero whose `id` is 42. The `data` property in the third route is a place to store arbitrary data associated with this specific route. The data property is accessible within each activated route. Use it to store items such as page titles, breadcrumb text, and other read-only, static data. Use the resolve guard to retrieve dynamic data. The empty path in the fourth route represents the default path for the application —the place to go when the path in the URL is empty, as it typically is at the start. This default route redirects to the route for the `/heroes` URL and, therefore, displays the `HeroesListComponent`. If you need to see what events are happening during the navigation lifecycle, there is the `withDebugTracing` feature. This outputs each router event that took place during each navigation lifecycle to the browser console. Use `withDebugTracing` only for debugging purposes. You set the `withDebugTracing` option in the object passed as the second argument to the `provideRouter` method. ## Router outlet The `RouterOutlet` is a directive from the router library that is used like a component. It acts as a placeholder that marks the spot in the template where the router should display the components for that outlet. <docs-code language="html"> <router-outlet></router-outlet> <!-- Routed components go here --> </docs-code> Given the preceding configuration, when the browser URL for this application becomes `/heroes`, the router matches that URL to the route path `/heroes` and displays the `HeroListComponent` as a sibling element to the `RouterOutlet` that you've placed in the host component's template. ## Router links To navigate as a result of some user action such as the click of an anchor tag, use `RouterLink`. Consider the following template: <docs-code header="src/app/app.component.html" path="adev/src/content/examples/router/src/app/app.component.1.html"/> The `RouterLink` directives on the anchor tags give the router control over those elements. The navigation paths are fixed, so you can assign a string as a one-time binding to the `routerLink`. Had the navigation path been more dynamic, you could have bound to a template expression that returned an array of route link parameters; that is, the [link parameters array](guide/routing/common-router-tasks#link-parameters-array). The router resolves that array into a complete URL. ## Active router links The `RouterLinkActive` directive toggles CSS classes for active `RouterLink` bindings based on the current `RouterState`. On each anchor tag, you see a [property binding](guide/templates/property-binding) to the `RouterLinkActive` directive that looks like <docs-code hideCopy language="html"> routerLinkActive="..." </docs-code> The template expression to the right of the equal sign, `=`, contains a space-delimited string of CSS classes that the Router adds when this link is active and removes when the link is inactive. You set the `RouterLinkActive` directive to a string of classes such as `routerLinkActive="active fluffy"` or bind it to a component property that returns such a string. For example, <docs-code hideCopy language="typescript"> [routerLinkActive]="someStringProperty" </docs-code> Active route links cascade down through each level of the route tree, so parent and child router links can be active at the same time. To override this behavior, bind to the `[routerLinkActiveOptions]` input binding with the `{ exact: true }` expression. By using `{ exact: true }`, a given `RouterLink` is only active if its URL is an exact match to the current URL. `RouterLinkActive` also allows you to easily apply the `aria-current` attribute to the active element, thus providing a more accessible experience for all users. For more information see the Accessibility Best Practices [Active links identification section](/best-practices/a11y#active-links-identification). ## Router state After the end of each successful navigation lifecycle, the router builds a tree of `ActivatedRoute` objects that make up the current state of the router. You can access the current `RouterState` from anywhere in the application using the `Router` service and the `routerState` property. Each `ActivatedRoute` in the `RouterState` provides methods to traverse up and down the route tree to get information from parent, child, and sibling routes. ## Activated route The route path and parameters are available through an injected router service called the [ActivatedRoute](api/router/ActivatedRoute). It has a great deal of useful information including: | Property | Details | |:--- |:--- | | `url` | An `Observable` of the route paths, represented as an array of strings for each part of the route path. | | `data` | An `Observable` that contains the `data` object provided for the route. Also contains any resolved values from the resolve guard. | | `params` | An `Observable` that contains the required and optional parameters specific to the route. | | `paramMap` | An `Observable` that contains a [map](api/router/ParamMap) of the required and optional parameters specific to the route. The map supports retrieving single and multiple values from the same parameter. | | `queryParamMap` | An `Observable` that contains a [map](api/router/ParamMap) of the query parameters available to all routes. The map supports retrieving single and multiple values from the query parameter. | | `queryParams` | An `Observable` that contains the query parameters available to all routes. | | `fragment` | An `Observable` of the URL fragment available to all routes. | | `outlet` | The name of the `RouterOutlet` used to render the route. For an unnamed outlet, the outlet name is primary. | | `routeConfig` | The route configuration used for the route that contains the origin path. | | `parent` | The route's parent `ActivatedRoute` when this route is a child route. | | `firstChild` | Contains the first `ActivatedRoute` in the list of this route's child routes. | | `children` | Contains all the child routes activated under the current route. | ##
{ "end_byte": 9740, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/router-reference.md" }
angular/adev/src/content/guide/routing/router-reference.md_9740_16871
Router events During each navigation, the `Router` emits navigation events through the `Router.events` property. These events are shown in the following table. | Router event | Details | |:--- |:--- | | [`NavigationStart`](api/router/NavigationStart) | Triggered when navigation starts. | | [`RouteConfigLoadStart`](api/router/RouteConfigLoadStart) | Triggered before the `Router` lazy loads a route configuration. | | [`RouteConfigLoadEnd`](api/router/RouteConfigLoadEnd) | Triggered after a route has been lazy loaded. | | [`RoutesRecognized`](api/router/RoutesRecognized) | Triggered when the Router parses the URL and the routes are recognized. | | [`GuardsCheckStart`](api/router/GuardsCheckStart) | Triggered when the Router begins the Guards phase of routing. | | [`ChildActivationStart`](api/router/ChildActivationStart) | Triggered when the Router begins activating a route's children. | | [`ActivationStart`](api/router/ActivationStart) | Triggered when the Router begins activating a route. | | [`GuardsCheckEnd`](api/router/GuardsCheckEnd) | Triggered when the Router finishes the Guards phase of routing successfully. | | [`ResolveStart`](api/router/ResolveStart) | Triggered when the Router begins the Resolve phase of routing. | | [`ResolveEnd`](api/router/ResolveEnd) | Triggered when the Router finishes the Resolve phase of routing successfully. | | [`ChildActivationEnd`](api/router/ChildActivationEnd) | Triggered when the Router finishes activating a route's children. | | [`ActivationEnd`](api/router/ActivationEnd) | Triggered when the Router finishes activating a route. | | [`NavigationEnd`](api/router/NavigationEnd) | Triggered when navigation ends successfully. | | [`NavigationCancel`](api/router/NavigationCancel) | Triggered when navigation is canceled. This can happen when a Route Guard returns false during navigation, or redirects by returning a `UrlTree` or `RedirectCommand`. | | [`NavigationError`](api/router/NavigationError) | Triggered when navigation fails due to an unexpected error. | | [`Scroll`](api/router/Scroll) | Represents a scrolling event. | When you enable the `withDebugTracing` feature, Angular logs these events to the console. ## Router terminology Here are the key `Router` terms and their meanings: | Router part | Details | |:--- |:--- | | `Router` | Displays the application component for the active URL. Manages navigation from one component to the next. | | `provideRouter` | provides the necessary service providers for navigating through application views. | | `RouterModule` | A separate NgModule that provides the necessary service providers and directives for navigating through application views. | | `Routes` | Defines an array of Routes, each mapping a URL path to a component. | | `Route` | Defines how the router should navigate to a component based on a URL pattern. Most routes consist of a path and a component type. | | `RouterOutlet` | The directive \(`<router-outlet>`\) that marks where the router displays a view. | | `RouterLink` | The directive for binding a clickable HTML element to a route. Clicking an element with a `routerLink` directive that's bound to a *string* or a *link parameters array* triggers a navigation. | | `RouterLinkActive` | The directive for adding/removing classes from an HTML element when an associated `routerLink` contained on or inside the element becomes active/inactive. It can also set the `aria-current` of an active link for better accessibility. | | `ActivatedRoute` | A service that's provided to each route component that contains route specific information such as route parameters, static data, resolve data, global query parameters, and the global fragment. | | `RouterState` | The current state of the router including a tree of the currently activated routes together with convenience methods for traversing the route tree. | | Link parameters array | An array that the router interprets as a routing instruction. You can bind that array to a `RouterLink` or pass the array as an argument to the `Router.navigate` method. | | Routing component | An Angular component with a `RouterOutlet` that displays views based on router navigations. |
{ "end_byte": 16871, "start_byte": 9740, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/router-reference.md" }
angular/adev/src/content/guide/routing/BUILD.bazel_0_1141
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "routing", srcs = glob([ "*.md", ]), data = [ "//adev/src/assets/images:routing.svg", "//adev/src/content/examples/router:src/app/app.component.1.html", "//adev/src/content/examples/router:src/index.html", "//adev/src/content/examples/router-tutorial:src/app/app.component.css", "//adev/src/content/examples/router-tutorial:src/app/app.component.html", "//adev/src/content/examples/router-tutorial:src/app/crisis-list/crisis-list.component.html", "//adev/src/content/examples/router-tutorial:src/app/heroes-list/heroes-list.component.html", "//adev/src/content/examples/router-tutorial:src/app/page-not-found/page-not-found.component.html", "//adev/src/content/examples/routing-with-urlmatcher:src/app/app.component.html", "//adev/src/content/examples/routing-with-urlmatcher:src/app/app.routes.ts", "//adev/src/content/examples/routing-with-urlmatcher:src/app/profile/profile.component.html", ], visibility = ["//adev:__subpackages__"], )
{ "end_byte": 1141, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/BUILD.bazel" }
angular/adev/src/content/guide/routing/router-tutorial.md_0_7994
# Using Angular routes in a single-page application This tutorial describes how to build a single-page application, SPA that uses multiple Angular routes. In a Single Page Application \(SPA\), all of your application's functions exist in a single HTML page. As users access your application's features, the browser needs to render only the parts that matter to the user, instead of loading a new page. This pattern can significantly improve your application's user experience. To define how users navigate through your application, you use routes. Add routes to define how users navigate from one part of your application to another. You can also configure routes to guard against unexpected or unauthorized behavior. ## Objectives * Organize a sample application's features into modules. * Define how to navigate to a component. * Pass information to a component using a parameter. * Structure routes by nesting several routes. * Check whether users can access a route. * Control whether the application can discard unsaved changes. * Improve performance by pre-fetching route data and lazy loading feature modules. * Require specific criteria to load components. ## Create a sample application Using the Angular CLI, create a new application, *angular-router-sample*. This application will have two components: *crisis-list* and *heroes-list*. 1. Create a new Angular project, *angular-router-sample*. <docs-code language="shell"> ng new angular-router-sample </docs-code> When prompted with `Would you like to add Angular routing?`, select `N`. When prompted with `Which stylesheet format would you like to use?`, select `CSS`. After a few moments, a new project, `angular-router-sample`, is ready. 1. From your terminal, navigate to the `angular-router-sample` directory. 1. Create a component, *crisis-list*. <docs-code language="shell"> ng generate component crisis-list </docs-code> 1. In your code editor, locate the file, `crisis-list.component.html` and replace the placeholder content with the following HTML. <docs-code header="src/app/crisis-list/crisis-list.component.html" path="adev/src/content/examples/router-tutorial/src/app/crisis-list/crisis-list.component.html"/> 1. Create a second component, *heroes-list*. <docs-code language="shell"> ng generate component heroes-list </docs-code> 1. In your code editor, locate the file, `heroes-list.component.html` and replace the placeholder content with the following HTML. <docs-code header="src/app/heroes-list/heroes-list.component.html" path="adev/src/content/examples/router-tutorial/src/app/heroes-list/heroes-list.component.html"/> 1. In your code editor, open the file, `app.component.html` and replace its contents with the following HTML. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/router-tutorial/src/app/app.component.html" visibleRegion="setup"/> 1. Verify that your new application runs as expected by running the `ng serve` command. <docs-code language="shell"> ng serve </docs-code> 1. Open a browser to `http://localhost:4200`. You should see a single web page, consisting of a title and the HTML of your two components. ## Define your routes In this section, you'll define two routes: * The route `/crisis-center` opens the `crisis-center` component. * The route `/heroes-list` opens the `heroes-list` component. A route definition is a JavaScript object. Each route typically has two properties. The first property, `path`, is a string that specifies the URL path for the route. The second property, `component`, is a string that specifies what component your application should display for that path. 1. From your code editor, create and open the `app.routes.ts` file. 1. Create and export a routes list for your application: ```ts import {Routes} from '@angular/router'; export const routes = []; ``` 1. Add two routes for your first two components: ```ts {path: 'crisis-list', component: CrisisListComponent}, {path: 'heroes-list', component: HeroesListComponent}, ``` This routes list is an array of JavaScript objects, with each object defining the properties of a route. ## Import `provideRouter` from `@angular/router` Routing lets you display specific views of your application depending on the URL path. To add this functionality to your sample application, you need to update the `app.config.ts` file to use the router providers function, `provideRouter`. You import this provider function from `@angular/router`. 1. From your code editor, open the `app.config.ts` file. 1. Add the following import statements: ```ts import { provideRouter } from '@angular/router'; import { routes } from './app.routes'; ``` 1. Update the providers in the `appConfig`: ```ts providers: [provideRouter(routes)] ``` For `NgModule` based applications, put the `provideRouter` in the `providers` list of the `AppModule`, or whichever module is passed to `bootstrapModule` in the application. ## Update your component with `router-outlet` At this point, you have defined two routes for your application. However, your application still has both the `crisis-list` and `heroes-list` components hard-coded in your `app.component.html` template. For your routes to work, you need to update your template to dynamically load a component based on the URL path. To implement this functionality, you add the `router-outlet` directive to your template file. 1. From your code editor, open the `app.component.html` file. 1. Delete the following lines. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/router-tutorial/src/app/app.component.html" visibleRegion="components"/> 1. Add the `router-outlet` directive. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/router-tutorial/src/app/app.component.html" visibleRegion="router-outlet"/> 1. Add `RouterOutlet` to the imports of the `AppComponent` in `app.component.ts` ```ts imports: [RouterOutlet], ``` View your updated application in your browser. You should see only the application title. To view the `crisis-list` component, add `crisis-list` to the end of the path in your browser's address bar. For example: <docs-code language="http"> http://localhost:4200/crisis-list </docs-code> Notice that the `crisis-list` component displays. Angular is using the route you defined to dynamically load the component. You can load the `heroes-list` component the same way: <docs-code language="http"> http://localhost:4200/heroes-list </docs-code> ## Control navigation with UI elements Currently, your application supports two routes. However, the only way to use those routes is for the user to manually type the path in the browser's address bar. In this section, you'll add two links that users can click to navigate between the `heroes-list` and `crisis-list` components. You'll also add some CSS styles. While these styles are not required, they make it easier to identify the link for the currently-displayed component. You'll add that functionality in the next section. 1. Open the `app.component.html` file and add the following HTML below the title. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/router-tutorial/src/app/app.component.html" visibleRegion="nav"/> This HTML uses an Angular directive, `routerLink`. This directive connects the routes you defined to your template files. 1. Add the `RouterLink` directive to the imports list of `AppComponent` in `app.component.ts`. 1. Open the `app.component.css` file and add the following styles. <docs-code header="src/app/app.component.css" path="adev/src/content/examples/router-tutorial/src/app/app.component.css"/> If you view your application in the browser, you should see these two links. When you click on a link, the corresponding component appears.
{ "end_byte": 7994, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/router-tutorial.md" }
angular/adev/src/content/guide/routing/router-tutorial.md_7994_12713
## Identify the active route While users can navigate your application using the links you added in the previous section, they don't have a straightforward way to identify what the active route is. Add this functionality using Angular's `routerLinkActive` directive. 1. From your code editor, open the `app.component.html` file. 1. Update the anchor tags to include the `routerLinkActive` directive. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/router-tutorial/src/app/app.component.html" visibleRegion="routeractivelink"/> 1. Add the `RouterLinkActive` directive to the `imports` list of `AppComponent` in `app.component.ts`. View your application again. As you click one of the buttons, the style for that button updates automatically, identifying the active component to the user. By adding the `routerLinkActive` directive, you inform your application to apply a specific CSS class to the active route. In this tutorial, that CSS class is `activebutton`, but you could use any class that you want. Note that we are also specifying a value for the `routerLinkActive`'s `ariaCurrentWhenActive`. This makes sure that visually impaired users (which may not perceive the different styling being applied) can also identify the active button. For more information see the Accessibility Best Practices [Active links identification section](/best-practices/a11y#active-links-identification). ## Adding a redirect In this step of the tutorial, you add a route that redirects the user to display the `/heroes-list` component. 1. From your code editor, open the `app.routes.ts` file. 1. Update the `routes` section as follows. ```ts {path: '', redirectTo: '/heroes-list', pathMatch: 'full'}, ``` Notice that this new route uses an empty string as its path. In addition, it replaces the `component` property with two new ones: | Properties | Details | |:--- |:--- | | `redirectTo` | This property instructs Angular to redirect from an empty path to the `heroes-list` path. | | `pathMatch` | This property instructs Angular on how much of the URL to match. For this tutorial, you should set this property to `full`. This strategy is recommended when you have an empty string for a path. For more information about this property, see the [Route API documentation](api/router/Route). | Now when you open your application, it displays the `heroes-list` component by default. ## Adding a 404 page It is possible for a user to try to access a route that you have not defined. To account for this behavior, the best practice is to display a 404 page. In this section, you'll create a 404 page and update your route configuration to show that page for any unspecified routes. 1. From the terminal, create a new component, `PageNotFound`. <docs-code language="shell"> ng generate component page-not-found </docs-code> 1. From your code editor, open the `page-not-found.component.html` file and replace its contents with the following HTML. <docs-code header="src/app/page-not-found/page-not-found.component.html" path="adev/src/content/examples/router-tutorial/src/app/page-not-found/page-not-found.component.html"/> 1. Open the `app.routes.ts` file and add the following route to the routes list: ```ts {path: '**', component: PageNotFoundComponent} ``` The new route uses a path, `**`. This path is how Angular identifies a wildcard route. Any route that does not match an existing route in your configuration will use this route. IMPORTANT: Notice that the wildcard route is placed at the end of the array. The order of your routes is important, as Angular applies routes in order and uses the first match it finds. Try navigating to a non-existing route on your application, such as `http://localhost:4200/powers`. This route doesn't match anything defined in your `app.routes.ts` file. However, because you defined a wildcard route, the application automatically displays your `PageNotFound` component. ## Next steps At this point, you have a basic application that uses Angular's routing feature to change what components the user can see based on the URL address. You have extended these features to include a redirect, as well as a wildcard route to display a custom 404 page. For more information about routing, see the following topics: <docs-pill-row> <docs-pill href="guide/routing/common-router-tasks" title="In-app Routing and Navigation"/> <docs-pill href="api/router/Router" title="Router API"/> </docs-pill-row>
{ "end_byte": 12713, "start_byte": 7994, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/routing/router-tutorial.md" }
angular/adev/src/content/guide/performance/overview.md_0_1909
<docs-decorative-header title="Performance" imgSrc="adev/src/assets/images/overview.svg"> <!-- markdownlint-disable-line --> Learn about different ways you can optimize the performance of your application. </docs-decorative-header> One of the top priorities of any developer is ensuring that their application is as performant as possible. These guides are here to help you follow best practices for building performant applications. That said, please note that these best practices will only take the performance of your application so far. At the end of the day, we encourage you to measure performance in order to best understand what custom optimizations are best for your application. | Guides Types | Description | | :---------------------------------------- | :--------------------------------------------------------------------------------------------------------- | | [Deferrable views](/guide/defer) | Defer loading of select dependencies within a template by wrapping corresponding parts in a `@defer` block. | | [Image optimization](/guide/image-optimization) | Use the `NgOptimizedImage` directive to adopt best practices for loading images. | | [Server-side rendering](/guide/ssr) | Learn how to leverage rendering pages on the server to improve load times. | | [Build-time prerendering](/guide/prerendering) | Also known as static-side generation (SSG), is an alternate rendering method to improve load times. | | [Hydration](/guide/hydration) | A process to improve application performance by restoring its state after server-side rendering and reusing existing DOM structure as much as possible. |
{ "end_byte": 1909, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/performance/overview.md" }
angular/adev/src/content/guide/performance/BUILD.bazel_0_258
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "performance", srcs = glob([ "*.md", ]), data = [ "//adev/src/assets/images:overview.svg", ], visibility = ["//adev:__subpackages__"], )
{ "end_byte": 258, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/performance/BUILD.bazel" }
angular/adev/src/content/guide/i18n/format-data-locale.md_0_2034
# Format data based on locale Angular provides the following built-in data transformation [pipes](guide/templates/pipes). The data transformation pipes use the [`LOCALE_ID`][ApiCoreLocaleId] token to format data based on rules of each locale. | Data transformation pipe | Details | |:--- |:--- | | [`DatePipe`][ApiCommonDatepipe] | Formats a date value. | | [`CurrencyPipe`][ApiCommonCurrencypipe] | Transforms a number into a currency string. | | [`DecimalPipe`][ApiCommonDecimalpipe] | Transforms a number into a decimal number string. | | [`PercentPipe`][ApiCommonPercentpipe] | Transforms a number into a percentage string. | ## Use DatePipe to display the current date To display the current date in the format for the current locale, use the following format for the `DatePipe`. <!--todo: replace with docs-code --> <docs-code language="typescript"> {{ today | date }} </docs-code> ## Override current locale for CurrencyPipe Add the `locale` parameter to the pipe to override the current value of `LOCALE_ID` token. To force the currency to use American English \(`en-US`\), use the following format for the `CurrencyPipe` <!--todo: replace with docs-code --> <docs-code language="typescript"> {{ amount | currency : 'en-US' }} </docs-code> HELPFUL: The locale specified for the `CurrencyPipe` overrides the global `LOCALE_ID` token of your application. ## What's next <docs-pill-row> <docs-pill href="guide/i18n/prepare" title="Prepare component for translation"/> </docs-pill-row> [ApiCommonCurrencypipe]: api/common/CurrencyPipe "CurrencyPipe | Common - API | Angular" [ApiCommonDatepipe]: api/common/DatePipe "DatePipe | Common - API | Angular" [ApiCommonDecimalpipe]: api/common/DecimalPipe "DecimalPipe | Common - API | Angular" [ApiCommonPercentpipe]: api/common/PercentPipe "PercentPipe | Common - API | Angular" [ApiCoreLocaleId]: api/core/LOCALE_ID "LOCALE_ID | Core - API | Angular"
{ "end_byte": 2034, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/format-data-locale.md" }
angular/adev/src/content/guide/i18n/translation-files.md_0_8293
# Work with translation files After you prepare a component for translation, use the [`extract-i18n`][CliExtractI18n] [Angular CLI][CliMain] command to extract the marked text in the component into a *source language* file. The marked text includes text marked with `i18n`, attributes marked with `i18n-`*attribute*, and text tagged with `$localize` as described in [Prepare component for translation][GuideI18nCommonPrepare]. Complete the following steps to create and update translation files for your project. 1. [Extract the source language file][GuideI18nCommonTranslationFilesExtractTheSourceLanguageFile]. 1. Optionally, change the location, format, and name. 1. Copy the source language file to [create a translation file for each language][GuideI18nCommonTranslationFilesCreateATranslationFileForEachLanguage]. 1. [Translate each translation file][GuideI18nCommonTranslationFilesTranslateEachTranslationFile]. 1. Translate plurals and alternate expressions separately. 1. [Translate plurals][GuideI18nCommonTranslationFilesTranslatePlurals]. 1. [Translate alternate expressions][GuideI18nCommonTranslationFilesTranslateAlternateExpressions]. 1. [Translate nested expressions][GuideI18nCommonTranslationFilesTranslateNestedExpressions]. ## Extract the source language file To extract the source language file, complete the following actions. 1. Open a terminal window. 1. Change to the root directory of your project. 1. Run the following CLI command. <docs-code path="adev/src/content/examples/i18n/doc-files/commands.sh" visibleRegion="extract-i18n-default"/> The `extract-i18n` command creates a source language file named `messages.xlf` in the root directory of your project. For more information about the XML Localization Interchange File Format \(XLIFF, version 1.2\), see [XLIFF][WikipediaWikiXliff]. Use the following [`extract-i18n`][CliExtractI18n] command options to change the source language file location, format, and file name. | Command option | Details | |:--- |:--- | | `--format` | Set the format of the output file | | `--out-file` | Set the name of the output file | | `--output-path` | Set the path of the output directory | ### Change the source language file location To create a file in the `src/locale` directory, specify the output path as an option. #### `extract-i18n --output-path` example The following example specifies the output path as an option. <docs-code path="adev/src/content/examples/i18n/doc-files/commands.sh" visibleRegion="extract-i18n-output-path"/> ### Change the source language file format The `extract-i18n` command creates files in the following translation formats. | Translation format | Details | File extension | |:--- |:--- |:--- | | ARB | [Application Resource Bundle][GithubGoogleAppResourceBundleWikiApplicationresourcebundlespecification] | `.arb` | | JSON | [JavaScript Object Notation][JsonMain] | `.json` | | XLIFF 1.2 | [XML Localization Interchange File Format, version 1.2][OasisOpenDocsXliffXliffCoreXliffCoreHtml] | `.xlf` | | XLIFF 2 | [XML Localization Interchange File Format, version 2][OasisOpenDocsXliffXliffCoreV20Cos01XliffCoreV20Cose01Html] | `.xlf` | | XMB | [XML Message Bundle][UnicodeCldrDevelopmentDevelopmentProcessDesignProposalsXmb] | `.xmb` \(`.xtb`\) | Specify the translation format explicitly with the `--format` command option. HELPFUL: The XMB format generates `.xmb` source language files, but uses`.xtb` translation files. #### `extract-i18n --format` example The following example demonstrates several translation formats. <docs-code path="adev/src/content/examples/i18n/doc-files/commands.sh" visibleRegion="extract-i18n-formats"/> ### Change the source language file name To change the name of the source language file generated by the extraction tool, use the `--out-file` command option. #### `extract-i18n --out-file` example The following example demonstrates naming the output file. <docs-code path="adev/src/content/examples/i18n/doc-files/commands.sh" visibleRegion="extract-i18n-out-file"/> ## Create a translation file for each language To create a translation file for a locale or language, complete the following actions. 1. [Extract the source language file][GuideI18nCommonTranslationFilesExtractTheSourceLanguageFile]. 1. Make a copy of the source language file to create a *translation* file for each language. 1. Rename the *translation* file to add the locale. <docs-code language="file"> messages.xlf --> messages.{locale}.xlf </docs-code> 1. Create a new directory at your project root named `locale`. <docs-code language="file"> src/locale </docs-code> 1. Move the *translation* file to the new directory. 1. Send the *translation* file to your translator. 1. Repeat the above steps for each language you want to add to your application. ### `extract-i18n` example for French For example, to create a French translation file, complete the following actions. 1. Run the `extract-i18n` command. 1. Make a copy of the `messages.xlf` source language file. 1. Rename the copy to `messages.fr.xlf` for the French language \(`fr`\) translation. 1. Move the `fr` translation file to the `src/locale` directory. 1. Send the `fr` translation file to the translator. ## Translate each translation file Unless you are fluent in the language and have the time to edit translations, you will likely complete the following steps. 1. Send each translation file to a translator. 1. The translator uses an XLIFF file editor to complete the following actions. 1. Create the translation. 1. Edit the translation. ### Translation process example for French To demonstrate the process, review the `messages.fr.xlf` file in the [Example Angular Internationalization application][GuideI18nExample]. The [Example Angular Internationalization application][GuideI18nExample] includes a French translation for you to edit without a special XLIFF editor or knowledge of French. The following actions describe the translation process for French. 1. Open `messages.fr.xlf` and find the first `<trans-unit>` element. This is a *translation unit*, also known as a *text node*, that represents the translation of the `<h1>` greeting tag that was previously marked with the `i18n` attribute. <docs-code header="src/locale/messages.fr.xlf (<trans-unit>)" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="translated-hello-before"/> The `id="introductionHeader"` is a [custom ID][GuideI18nOptionalManageMarkedText], but without the `@@` prefix required in the source HTML. 1. Duplicate the `<source>... </source>` element in the text node, rename it to `target`, and then replace the content with the French text. <docs-code header="src/locale/messages.fr.xlf (<trans-unit>, after translation)" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="translated-hello"/> In a more complex translation, the information and context in the [description and meaning elements][GuideI18nCommonPrepareAddHelpfulDescriptionsAndMeanings] help you choose the right words for translation. 1. Translate the other text nodes. The following example displays the way to translate. <docs-code header="src/locale/messages.fr.xlf (<trans-unit>)" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="translated-other-nodes"/> IMPORTANT: Don't change the IDs for translation units. Each `id` attribute is generated by Angular and depends on the content of the component text and the assigned meaning. If you change either the text or the meaning, then the `id` attribute changes. For more about managing text updates and IDs, see [custom IDs][GuideI18nOptionalManageMarkedText].
{ "end_byte": 8293, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/translation-files.md" }
angular/adev/src/content/guide/i18n/translation-files.md_8293_14451
## Translate plurals Add or remove plural cases as needed for each language. HELPFUL: For language plural rules, see [CLDR plural rules][GithubUnicodeOrgCldrStagingChartsLatestSupplementalLanguagePluralRulesHtml]. ### `minute` `plural` example To translate a `plural`, translate the ICU format match values. * `just now` * `one minute ago` * `<x id="INTERPOLATION" equiv-text="{{minutes}}"/> minutes ago` The following example displays the way to translate. <docs-code header="src/locale/messages.fr.xlf (<trans-unit>)" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="translated-plural"/> ## Translate alternate expressions Angular also extracts alternate `select` ICU expressions as separate translation units. ### `gender` `select` example The following example displays a `select` ICU expression in the component template. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/src/app/app.component.html" visibleRegion="i18n-select"/> In this example, Angular extracts the expression into two translation units. The first contains the text outside of the `select` clause, and uses a placeholder for `select` \(`<x id="ICU">`\): <docs-code header="src/locale/messages.fr.xlf (<trans-unit>)" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="translate-select-1"/> IMPORTANT: When you translate the text, move the placeholder if necessary, but don't remove it. If you remove the placeholder, the ICU expression is removed from your translated application. The following example displays the second translation unit that contains the `select` clause. <docs-code header="src/locale/messages.fr.xlf (<trans-unit>)" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="translate-select-2"/> The following example displays both translation units after translation is complete. <docs-code header="src/locale/messages.fr.xlf (<trans-unit>)" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="translated-select"/> ## Translate nested expressions Angular treats a nested expression in the same manner as an alternate expression. Angular extracts the expression into two translation units. ### Nested `plural` example The following example displays the first translation unit that contains the text outside of the nested expression. <docs-code header="src/locale/messages.fr.xlf (<trans-unit>)" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="translate-nested-1"/> The following example displays the second translation unit that contains the complete nested expression. <docs-code header="src/locale/messages.fr.xlf (<trans-unit>)" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="translate-nested-2"/> The following example displays both translation units after translating. <docs-code header="src/locale/messages.fr.xlf (<trans-unit>)" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="translate-nested"/> ## What's next <docs-pill-row> <docs-pill href="guide/i18n/merge" title="Merge translations into the app"/> </docs-pill-row> [CliMain]: cli "CLI Overview and Command Reference | Angular" [CliExtractI18n]: cli/extract-i18n "ng extract-i18n | CLI | Angular" [GuideI18nCommonPrepare]: guide/i18n/prepare "Prepare component for translation | Angular" [GuideI18nCommonPrepareAddHelpfulDescriptionsAndMeanings]: guide/i18n/prepare#add-helpful-descriptions-and-meanings "Add helpful descriptions and meanings - Prepare component for translation | Angular" [GuideI18nCommonTranslationFilesCreateATranslationFileForEachLanguage]: guide/i18n/translation-files#create-a-translation-file-for-each-language "Create a translation file for each language - Work with translation files | Angular" [GuideI18nCommonTranslationFilesExtractTheSourceLanguageFile]: guide/i18n/translation-files#extract-the-source-language-file "Extract the source language file - Work with translation files | Angular" [GuideI18nCommonTranslationFilesTranslateAlternateExpressions]: guide/i18n/translation-files#translate-alternate-expressions "Translate alternate expressions - Work with translation files | Angular" [GuideI18nCommonTranslationFilesTranslateEachTranslationFile]: guide/i18n/translation-files#translate-each-translation-file "Translate each translation file - Work with translation files | Angular" [GuideI18nCommonTranslationFilesTranslateNestedExpressions]: guide/i18n/translation-files#translate-nested-expressions "Translate nested expressions - Work with translation files | Angular" [GuideI18nCommonTranslationFilesTranslatePlurals]: guide/i18n/translation-files#translate-plurals "Translate plurals - Work with translation files | Angular" [GuideI18nExample]: guide/i18n/example "Example Angular Internationalization application | Angular" [GuideI18nOptionalManageMarkedText]: guide/i18n/manage-marked-text "Manage marked text with custom IDs | Angular" [GithubGoogleAppResourceBundleWikiApplicationresourcebundlespecification]: https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification "ApplicationResourceBundleSpecification | google/app-resource-bundle | GitHub" [GithubUnicodeOrgCldrStagingChartsLatestSupplementalLanguagePluralRulesHtml]: https://cldr.unicode.org/index/cldr-spec/plural-rules "Language Plural Rules - CLDR Charts | Unicode | GitHub" [JsonMain]: https://www.json.org "Introducing JSON | JSON" [OasisOpenDocsXliffXliffCoreXliffCoreHtml]: http://docs.oasis-open.org/xliff/xliff-core/xliff-core.html "XLIFF Version 1.2 Specification | Oasis Open Docs" [OasisOpenDocsXliffXliffCoreV20Cos01XliffCoreV20Cose01Html]: http://docs.oasis-open.org/xliff/xliff-core/v2.0/cos01/xliff-core-v2.0-cos01.html "XLIFF Version 2.0 | Oasis Open Docs" [UnicodeCldrDevelopmentDevelopmentProcessDesignProposalsXmb]: http://cldr.unicode.org/development/development-process/design-proposals/xmb "XMB | CLDR - Unicode Common Locale Data Repository | Unicode" [WikipediaWikiXliff]: https://en.wikipedia.org/wiki/XLIFF "XLIFF | Wikipedia"
{ "end_byte": 14451, "start_byte": 8293, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/translation-files.md" }
angular/adev/src/content/guide/i18n/manage-marked-text.md_0_4780
# Manage marked text with custom IDs The Angular extractor generates a file with a translation unit entry each of the following instances. * Each `i18n` attribute in a component template * Each [`$localize`][ApiLocalizeInitLocalize] tagged message string in component code As described in [How meanings control text extraction and merges][GuideI18nCommonPrepareHowMeaningsControlTextExtractionAndMerges], Angular assigns each translation unit a unique ID. The following example displays translation units with unique IDs. <docs-code header="messages.fr.xlf.html" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="generated-id"/> When you change the translatable text, the extractor generates a new ID for that translation unit. In most cases, changes in the source text also require a change to the translation. Therefore, using a new ID keeps the text change in sync with translations. However, some translation systems require a specific form or syntax for the ID. To address the requirement, use a custom ID to mark text. Most developers don't need to use a custom ID. If you want to use a unique syntax to convey additional metadata, use a custom ID. Additional metadata may include the library, component, or area of the application in which the text appears. To specify a custom ID in the `i18n` attribute or [`$localize`][ApiLocalizeInitLocalize] tagged message string, use the `@@` prefix. The following example defines the `introductionHeader` custom ID in a heading element. <docs-code header="app/app.component.html" path="adev/src/content/examples/i18n/doc-files/app.component.html" visibleRegion="i18n-attribute-solo-id"/> The following example defines the `introductionHeader` custom ID for a variable. <!--todo: replace with code example --> <docs-code language="typescript"> variableText1 = $localize`:@@introductionHeader:Hello i18n!`; </docs-code> When you specify a custom ID, the extractor generates a translation unit with the custom ID. <docs-code header="messages.fr.xlf.html" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="custom-id"/> If you change the text, the extractor does not change the ID. As a result, you don't have to take the extra step to update the translation. The drawback of using custom IDs is that if you change the text, your translation may be out-of-sync with the newly changed source text. ## Use a custom ID with a description Use a custom ID in combination with a description and a meaning to further help the translator. The following example includes a description, followed by the custom ID. <docs-code header="app/app.component.html" path="adev/src/content/examples/i18n/doc-files/app.component.html" visibleRegion="i18n-attribute-id"/> The following example defines the `introductionHeader` custom ID and description for a variable. <!--todo: replace with code example --> <docs-code language="typescript"> variableText2 = $localize`:An introduction header for this sample@@introductionHeader:Hello i18n!`; </docs-code> The following example adds a meaning. <docs-code header="app/app.component.html" path="adev/src/content/examples/i18n/doc-files/app.component.html" visibleRegion="i18n-attribute-meaning-and-id"/> The following example defines the `introductionHeader` custom ID for a variable. <!--todo: replace with code example --> <docs-code language="typescript"> variableText3 = $localize`:site header|An introduction header for this sample@@introductionHeader:Hello i18n!`; </docs-code> ### Define unique custom IDs Be sure to define custom IDs that are unique. If you use the same ID for two different text elements, the extraction tool extracts only the first one, and Angular uses the translation in place of both original text elements. For example, in the following code snippet the same `myId` custom ID is defined for two different text elements. <docs-code header="app/app.component.html" path="adev/src/content/examples/i18n/doc-files/app.component.html" visibleRegion="i18n-duplicate-custom-id"/> The following displays the translation in French. <docs-code header="src/locale/messages.fr.xlf" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html" visibleRegion="i18n-duplicate-custom-id"/> Both elements now use the same translation \(`Bonjour`\), because both were defined with the same custom ID. <docs-code path="adev/src/content/examples/i18n/doc-files/rendered-output.html"/> [ApiLocalizeInitLocalize]: api/localize/init/$localize "$localize | init - localize - API | Angular" [GuideI18nCommonPrepareHowMeaningsControlTextExtractionAndMerges]: guide/i18n/prepare#h1-example "How meanings control text extraction and merges - Prepare components for translations | Angular"
{ "end_byte": 4780, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/manage-marked-text.md" }
angular/adev/src/content/guide/i18n/overview.md_0_2681
# Angular Internationalization *Internationalization*, sometimes referenced as i18n, is the process of designing and preparing your project for use in different locales around the world. *Localization* is the process of building versions of your project for different locales. The localization process includes the following actions. * Extract text for translation into different languages * Format data for a specific locale A *locale* identifies a region in which people speak a particular language or language variant. Possible regions include countries and geographical regions. A locale determines the formatting and parsing of the following details. * Measurement units including date and time, numbers, and currencies * Translated names including time zones, languages, and countries For a quick introduction to localization and internationalization watch this video: <docs-video src="https://www.youtube.com/embed/KNTN-nsbV7M"/> ## Learn about Angular internationalization <docs-card-container> <docs-card title="Add the localize package" href="guide/i18n/add-package"> Learn how to add the Angular Localize package to your project </docs-card> <docs-card title="Refer to locales by ID" href="guide/i18n/locale-id"> Learn how to identify and specify a locale identifier for your project </docs-card> <docs-card title="Format data based on locale" href="guide/i18n/format-data-locale"> Learn how to implement localized data pipes and override the locale for your project </docs-card> <docs-card title="Prepare component for translation" href="guide/i18n/prepare"> Learn how to specify source text for translation </docs-card> <docs-card title="Work with translation files" href="guide/i18n/translation-files"> Learn how to review and process translation text </docs-card> <docs-card title="Merge translations into the application" href="guide/i18n/merge"> Learn how to merge translations and build your translated application </docs-card> <docs-card title="Deploy multiple locales" href="guide/i18n/deploy"> Learn how to deploy multiple locales for your application </docs-card> <docs-card title="Import global variants of the locale data" href="guide/i18n/import-global-variants"> Learn how to import locale data for language variants </docs-card> <docs-card title="Manage marked text with custom IDs" href="guide/i18n/manage-marked-text"> Learn how to implement custom IDs to help you manage your marked text </docs-card> <docs-card title="Internationalization example" href="guide/i18n/example"> Review an example of Angular internationalization. </docs-card> </docs-card-container>
{ "end_byte": 2681, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/overview.md" }
angular/adev/src/content/guide/i18n/example.md_0_976
# Example Angular Internationalization application <!-- ## Explore the translated example application --> <!-- Explore the sample application with French translations used in the [Angular Internationalization][GuideI18nOverview] guide: --> <!-- TODO: link to GitHub --> <!-- <docs-code live path="adev/src/content/examples/i18n" title="live example"/> --> ## `fr-CA` and `en-US` example The following tabs display the example application and the associated translation files. <docs-code-multifile> <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/src/app/app.component.html"/> <docs-code header="src/app/app.component.ts" path="adev/src/content/examples/i18n/src/app/app.component.ts"/> <docs-code header="src/main.ts" path="adev/src/content/examples/i18n/doc-files/main.1.ts"/> <docs-code header="src/locale/messages.fr.xlf" path="adev/src/content/examples/i18n/doc-files/messages.fr.xlf.html"/> </docs-code-multifile>
{ "end_byte": 976, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/example.md" }
angular/adev/src/content/guide/i18n/prepare.md_0_9006
# Prepare component for translation To prepare your project for translation, complete the following actions. - Use the `i18n` attribute to mark text in component templates - Use the `i18n-` attribute to mark attribute text strings in component templates - Use the `$localize` tagged message string to mark text strings in component code ## Mark text in component template In a component template, the i18n metadata is the value of the `i18n` attribute. <docs-code language="html"> <element i18n="{i18n_metadata}">{string_to_translate}</element> </docs-code> Use the `i18n` attribute to mark a static text message in your component templates for translation. Place it on every element tag that contains fixed text you want to translate. HELPFUL: The `i18n` attribute is a custom attribute that the Angular tools and compilers recognize. ### `i18n` example The following `<h1>` tag displays a simple English language greeting, "Hello i18n!". <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/doc-files/app.component.html" visibleRegion="greeting"/> To mark the greeting for translation, add the `i18n` attribute to the `<h1>` tag. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/doc-files/app.component.html" visibleRegion="i18n-attribute"/> ### using conditional statement with `i18n` The following `<div>` tag will display translated text as part of `div` and `aria-label` based on toggle status <docs-code-multifile> <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/src/app/app.component.html" visibleRegion="i18n-conditional"/> <docs-code header="src/app/app.component.ts" path="adev/src/content/examples/i18n/src/app/app.component.ts" visibleLines="[[14,21],[33,37]]"/> </docs-code-multifile> ### Translate inline text without HTML element Use the `<ng-container>` element to associate a translation behavior for specific text without changing the way text is displayed. HELPFUL: Each HTML element creates a new DOM element. To avoid creating a new DOM element, wrap the text in an `<ng-container>` element. The following example shows the `<ng-container>` element transformed into a non-displayed HTML comment. <docs-code path="adev/src/content/examples/i18n/src/app/app.component.html" visibleRegion="i18n-ng-container"/> ## Mark element attributes for translations In a component template, the i18n metadata is the value of the `i18n-{attribute_name}` attribute. <docs-code language="html"> <element i18n-{attribute_name}="{i18n_metadata}" {attribute_name}="{attribute_value}" /> </docs-code> The attributes of HTML elements include text that should be translated along with the rest of the displayed text in the component template. Use `i18n-{attribute_name}` with any attribute of any element and replace `{attribute_name}` with the name of the attribute. Use the following syntax to assign a meaning, description, and custom ID. <!--todo: replace with docs-code --> <docs-code language="html"> i18n-{attribute_name}="{meaning}|{description}@@{id}" </docs-code> ### `i18n-title` example To translate the title of an image, review this example. The following example displays an image with a `title` attribute. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/doc-files/app.component.html" visibleRegion="i18n-title"/> To mark the title attribute for translation, complete the following action. 1. Add the `i18n-title` attribute The following example displays how to mark the `title` attribute on the `img` tag by adding `i18n-title`. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/src/app/app.component.html" visibleRegion="i18n-title-translate"/> ## Mark text in component code In component code, the translation source text and the metadata are surrounded by backtick \(<code>&#96;</code>\) characters. Use the [`$localize`][ApiLocalizeInitLocalize] tagged message string to mark a string in your code for translation. <!--todo: replace with docs-code --> <docs-code language="typescript"> $localize`string_to_translate`; </docs-code> The i18n metadata is surrounded by colon \(`:`\) characters and prepends the translation source text. <!--todo: replace with docs-code --> <docs-code language="typescript"> $localize`:{i18n_metadata}:string_to_translate` </docs-code> ### Include interpolated text Include [interpolations](guide/templates/binding#render-dynamic-text-with-text-interpolation) in a [`$localize`][ApiLocalizeInitLocalize] tagged message string. <!--todo: replace with docs-code --> <docs-code language="typescript"> $localize`string_to_translate ${variable_name}`; </docs-code> ### Name the interpolation placeholder <docs-code language="typescript"> $localize`string_to_translate ${variable_name}:placeholder_name:`; </docs-code> ### Conditional syntax for translations <docs-code language="typescript"> return this.show ? $localize`Show Tabs` : $localize`Hide tabs`; </docs-code> ## i18n metadata for translation <!--todo: replace with docs-code --> <docs-code language="html"> {meaning}|{description}@@{custom_id} </docs-code> The following parameters provide context and additional information to reduce confusion for your translator. | Metadata parameter | Details | | :----------------- | :-------------------------------------------------------------------- | | Custom ID | Provide a custom identifier | | Description | Provide additional information or context | | Meaning | Provide the meaning or intent of the text within the specific context | For additional information about custom IDs, see [Manage marked text with custom IDs][GuideI18nOptionalManageMarkedText]. ### Add helpful descriptions and meanings To translate a text message accurately, provide additional information or context for the translator. Add a _description_ of the text message as the value of the `i18n` attribute or [`$localize`][ApiLocalizeInitLocalize] tagged message string. The following example shows the value of the `i18n` attribute. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/doc-files/app.component.html" visibleRegion="i18n-attribute-desc"/> The following example shows the value of the [`$localize`][ApiLocalizeInitLocalize] tagged message string with a description. <!--todo: replace with docs-code --> <docs-code language="typescript"> $localize`:An introduction header for this sample:Hello i18n!`; </docs-code> The translator may also need to know the meaning or intent of the text message within this particular application context, in order to translate it the same way as other text with the same meaning. Start the `i18n` attribute value with the _meaning_ and separate it from the _description_ with the `|` character: `{meaning}|{description}`. #### `h1` example For example, you may want to specify that the `<h1>` tag is a site header that you need translated the same way, whether it is used as a header or referenced in another section of text. The following example shows how to specify that the `<h1>` tag must be translated as a header or referenced elsewhere. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/doc-files/app.component.html" visibleRegion="i18n-attribute-meaning"/> The result is any text marked with `site header`, as the _meaning_ is translated exactly the same way. The following code example shows the value of the [`$localize`][ApiLocalizeInitLocalize] tagged message string with a meaning and a description. <!--todo: replace with docs-code --> <docs-code language="typescript"> $localize`:site header|An introduction header for this sample:Hello i18n!`; </docs-code> <docs-callout title="How meanings control text extraction and merges"> The Angular extraction tool generates a translation unit entry for each `i18n` attribute in a template. The Angular extraction tool assigns each translation unit a unique ID based on the _meaning_ and _description_. HELPFUL: For more information about the Angular extraction tool, see [Work with translation files](guide/i18n/translation-files). The same text elements with different _meanings_ are extracted with different IDs. For example, if the word "right" uses the following two definitions in two different locations, the word is translated differently and merged back into the application as different translation entries. - `correct` as in "you are right" - `direction` as in "turn right" If the same text elements meet the following conditions, the text elements are extracted only once and use the same ID. - Same meaning or definition - Different descriptions That one translation entry is merged back into the application wherever the same text elements appear. </docs-callout>
{ "end_byte": 9006, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/prepare.md" }
angular/adev/src/content/guide/i18n/prepare.md_9006_17947
## ICU expressions ICU expressions help you mark alternate text in component templates to meet conditions. An ICU expression includes a component property, an ICU clause, and the case statements surrounded by open curly brace \(`{`\) and close curly brace \(`}`\) characters. <!--todo: replace with docs-code --> <docs-code language="html"> { component_property, icu_clause, case_statements } </docs-code> The component property defines the variable An ICU clause defines the type of conditional text. | ICU clause | Details | | :------------------------------------------------------------------- | :------------------------------------------------------------------ | | [`plural`][GuideI18nCommonPrepareMarkPlurals] | Mark the use of plural numbers | | [`select`][GuideI18nCommonPrepareMarkAlternatesAndNestedExpressions] | Mark choices for alternate text based on your defined string values | To simplify translation, use International Components for Unicode clauses \(ICU clauses\) with regular expressions. HELPFUL: The ICU clauses adhere to the [ICU Message Format][GithubUnicodeOrgIcuUserguideFormatParseMessages] specified in the [CLDR pluralization rules][UnicodeCldrIndexCldrSpecPluralRules]. ### Mark plurals Different languages have different pluralization rules that increase the difficulty of translation. Because other locales express cardinality differently, you may need to set pluralization categories that do not align with English. Use the `plural` clause to mark expressions that may not be meaningful if translated word-for-word. <!--todo: replace with docs-code --> <docs-code language="html"> { component_property, plural, pluralization_categories } </docs-code> After the pluralization category, enter the default text \(English\) surrounded by open curly brace \(`{`\) and close curly brace \(`}`\) characters. <!--todo: replace with docs-code --> <docs-code language="html"> pluralization_category { } </docs-code> The following pluralization categories are available for English and may change based on the locale. | Pluralization category | Details | Example | | :--------------------- | :------------------------- | :------------------------- | | `zero` | Quantity is zero | `=0 { }` <br /> `zero { }` | | `one` | Quantity is 1 | `=1 { }` <br /> `one { }` | | `two` | Quantity is 2 | `=2 { }` <br /> `two { }` | | `few` | Quantity is 2 or more | `few { }` | | `many` | Quantity is a large number | `many { }` | | `other` | The default quantity | `other { }` | If none of the pluralization categories match, Angular uses `other` to match the standard fallback for a missing category. <!--todo: replace with docs-code --> <docs-code language="html"> other { default_quantity } </docs-code> HELPFUL: For more information about pluralization categories, see [Choosing plural category names][UnicodeCldrIndexCldrSpecPluralRulesTocChoosingPluralCategoryNames] in the [CLDR - Unicode Common Locale Data Repository][UnicodeCldrMain]. <docs-callout header='Background: Locales may not support some pluralization categories'> Many locales don't support some of the pluralization categories. The default locale \(`en-US`\) uses a very simple `plural()` function that doesn't support the `few` pluralization category. Another locale with a simple `plural()` function is `es`. The following code example shows the [en-US `plural()`][GithubAngularAngularBlobEcffc3557fe1bff9718c01277498e877ca44588dPackagesCoreSrcI18nLocaleEnTsL14L18] function. <docs-code path="adev/src/content/examples/i18n/doc-files/locale_plural_function.ts" class="no-box" hideCopy/> The `plural()` function only returns 1 \(`one`\) or 5 \(`other`\). The `few` category never matches. </docs-callout> #### `minutes` example If you want to display the following phrase in English, where `x` is a number. <!--todo: replace output docs-code with screen capture image ---> <docs-code language="html"> updated x minutes ago </docs-code> And you also want to display the following phrases based on the cardinality of `x`. <!--todo: replace output docs-code with screen capture image ---> <docs-code language="html"> updated just now </docs-code> <!--todo: replace output docs-code with screen capture image ---> <docs-code language="html"> updated one minute ago </docs-code> Use HTML markup and [interpolations](guide/templates/binding#render-dynamic-text-with-text-interpolation). The following code example shows how to use the `plural` clause to express the previous three situations in a `<span>` element. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/src/app/app.component.html" visibleRegion="i18n-plural"/> Review the following details in the previous code example. | Parameters | Details | | :-------------------------------- | :-------------------------------------------------------------------------------------------------------------------- | | `minutes` | The first parameter specifies the component property is `minutes` and determines the number of minutes. | | `plural` | The second parameter specifies the ICU clause is `plural`. | | `=0 {just now}` | For zero minutes, the pluralization category is `=0`. The value is `just now`. | | `=1 {one minute}` | For one minute, the pluralization category is `=1`. The value is `one minute`. | | `other {{{minutes}} minutes ago}` | For any unmatched cardinality, the default pluralization category is `other`. The value is `{{minutes}} minutes ago`. | `{{minutes}}` is an [interpolation](guide/templates/binding#render-dynamic-text-with-text-interpolation). ### Mark alternates and nested expressions The `select` clause marks choices for alternate text based on your defined string values. <!--todo: replace with docs-code --> <docs-code language="html"> { component_property, select, selection_categories } </docs-code> Translate all of the alternates to display alternate text based on the value of a variable. After the selection category, enter the text \(English\) surrounded by open curly brace \(`{`\) and close curly brace \(`}`\) characters. <!--todo: replace with docs-code --> <docs-code language="html"> selection_category { text } </docs-code> Different locales have different grammatical constructions that increase the difficulty of translation. Use HTML markup. If none of the selection categories match, Angular uses `other` to match the standard fallback for a missing category. <!--todo: replace with docs-code --> <docs-code language="html"> other { default_value } </docs-code> #### `gender` example If you want to display the following phrase in English. <!--todo: replace output docs-code with screen capture image ---> <docs-code language="html"> The author is other </docs-code> And you also want to display the following phrases based on the `gender` property of the component. <!--todo: replace output docs-code with screen capture image ---> <docs-code language="html"> The author is female </docs-code> <!--todo: replace output docs-code with screen capture image ---> <docs-code language="html"> The author is male </docs-code> The following code example shows how to bind the `gender` property of the component and use the `select` clause to express the previous three situations in a `<span>` element. The `gender` property binds the outputs to each of following string values. | Value | English value | | :----- | :------------ | | female | `female` | | male | `male` | | other | `other` | The `select` clause maps the values to the appropriate translations. The following code example shows `gender` property used with the select clause. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/src/app/app.component.html" visibleRegion="i18n-select"/> #### `gender` and `minutes` example Combine different clauses together, such as the `plural` and `select` clauses. The following code example shows nested clauses based on the `gender` and `minutes` examples. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/i18n/src/app/app.component.html" visibleRegion="i18n-nested"/>
{ "end_byte": 17947, "start_byte": 9006, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/prepare.md" }
angular/adev/src/content/guide/i18n/prepare.md_17947_19622
## What's next <docs-pill-row> <docs-pill href="guide/i18n/translation-files" title="Work with translation files"/> </docs-pill-row> [ApiLocalizeInitLocalize]: api/localize/init/$localize '$localize | init - localize - API | Angular' [GuideI18nCommonPrepareMarkAlternatesAndNestedExpressions]: guide/i18n/prepare#mark-alternates-and-nested-expressions 'Mark alternates and nested expressions - Prepare templates for translation | Angular' [GuideI18nCommonPrepareMarkPlurals]: guide/i18n/prepare#mark-plurals 'Mark plurals - Prepare component for translation | Angular' [GuideI18nOptionalManageMarkedText]: guide/i18n/manage-marked-text 'Manage marked text with custom IDs | Angular' [GithubAngularAngularBlobEcffc3557fe1bff9718c01277498e877ca44588dPackagesCoreSrcI18nLocaleEnTsL14L18]: https://github.com/angular/angular/blob/ecffc3557fe1bff9718c01277498e877ca44588d/packages/core/src/i18n/locale_en.ts#L14-L18 'Line 14 to 18 - angular/packages/core/src/i18n/locale_en.ts | angular/angular | GitHub' [GithubUnicodeOrgIcuUserguideFormatParseMessages]: https://unicode-org.github.io/icu/userguide/format_parse/messages 'ICU Message Format - ICU Documentation | Unicode | GitHub' [UnicodeCldrMain]: https://cldr.unicode.org 'Unicode CLDR Project' [UnicodeCldrIndexCldrSpecPluralRules]: http://cldr.unicode.org/index/cldr-spec/plural-rules 'Plural Rules | CLDR - Unicode Common Locale Data Repository | Unicode' [UnicodeCldrIndexCldrSpecPluralRulesTocChoosingPluralCategoryNames]: http://cldr.unicode.org/index/cldr-spec/plural-rules#TOC-Choosing-Plural-Category-Names 'Choosing Plural Category Names - Plural Rules | CLDR - Unicode Common Locale Data Repository | Unicode'
{ "end_byte": 19622, "start_byte": 17947, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/prepare.md" }
angular/adev/src/content/guide/i18n/add-package.md_0_1954
# Add the localize package To take advantage of the localization features of Angular, use the [Angular CLI][CliMain] to add the `@angular/localize` package to your project. To add the `@angular/localize` package, use the following command to update the `package.json` and TypeScript configuration files in your project. <docs-code path="adev/src/content/examples/i18n/doc-files/commands.sh" visibleRegion="add-localize"/> It adds `types: ["@angular/localize"]` in the TypeScript configuration files as well as the reference to the type definition of `@angular/localize` at the top of the `main.ts` file. HELPFUL: For more information about `package.json` and `tsconfig.json` files, see [Workspace npm dependencies][GuideNpmPackages] and [TypeScript Configuration][GuideTsConfig]. If `@angular/localize` is not installed and you try to build a localized version of your project (for example, while using the `i18n` attributes in templates), the [Angular CLI][CliMain] will generate an error, which would contain the steps that you can take to enable i18n for your project. ## Options | OPTION | DESCRIPTION | VALUE TYPE | DEFAULT VALUE |:--- |:--- |:------ |:------ | `--project` | The name of the project. | `string` | | `--use-at-runtime` | If set, then `$localize` can be used at runtime. Also `@angular/localize` gets included in the `dependencies` section of `package.json`, rather than `devDependencies`, which is the default. | `boolean` | `false` For more available options, see `ng add` in [Angular CLI][CliMain]. ## What's next <docs-pill-row> <docs-pill href="guide/i18n/locale-id" title="Refer to locales by ID"/> </docs-pill-row> [CliMain]: cli "CLI Overview and Command Reference | Angular" [GuideNpmPackages]: reference/configs/npm-packages "Workspace npm dependencies | Angular" [GuideTsConfig]: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html "TypeScript Configuration"
{ "end_byte": 1954, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/add-package.md" }
angular/adev/src/content/guide/i18n/deploy.md_0_2399
# 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"
{ "end_byte": 2399, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/deploy.md" }
angular/adev/src/content/guide/i18n/import-global-variants.md_0_1213
# Import global variants of the locale data The [Angular CLI][CliMain] automatically includes locale data if you run the [`ng build`][CliBuild] command with the `--localize` option. <!--todo: replace with docs-code --> <docs-code language="shell"> ng build --localize </docs-code> HELPFUL: The initial installation of Angular already contains locale data for English in the United States \(`en-US`\). The [Angular CLI][CliMain] automatically includes the locale data and sets the `LOCALE_ID` value when you use the `--localize` option with [`ng build`][CliBuild] command. The `@angular/common` package on npm contains the locale data files. Global variants of the locale data are available in `@angular/common/locales/global`. ## `import` example for French For example, you could import the global variants for French \(`fr`\) in `main.ts` where you bootstrap the application. <docs-code header="src/main.ts (import locale)" path="adev/src/content/examples/i18n/src/main.ts" visibleRegion="global-locale"/> HELPFUL: In an `NgModules` application, you would import it in your `app.module`. [CliMain]: cli "CLI Overview and Command Reference | Angular" [CliBuild]: cli/build "ng build | CLI | Angular"
{ "end_byte": 1213, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/import-global-variants.md" }
angular/adev/src/content/guide/i18n/merge.md_0_9284
# 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.
{ "end_byte": 9284, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/merge.md" }
angular/adev/src/content/guide/i18n/merge.md_9284_10869
## What's next <docs-pill-row> <docs-pill href="guide/i18n/deploy" title="Deploy multiple locales"/> </docs-pill-row> [ApiLocalizeInitLocalize]: api/localize/init/$localize "$localize | init - localize - API | Angular" [CliMain]: cli "CLI Overview and Command Reference | Angular" [CliBuild]: cli/build "ng build | CLI | Angular" [GuideBuild]: tools/cli/build "Building and serving Angular apps | Angular" [GuideI18nCommonMergeApplySpecificBuildOptionsForJustOneLocale]: guide/i18n/merge#apply-specific-build-options-for-just-one-locale "Apply specific build options for just one locale - Merge translations into the application | Angular" [GuideI18nCommonMergeBuildFromTheCommandLine]: guide/i18n/merge#build-from-the-command-line "Build from the command line - Merge translations into the application | Angular" [GuideI18nCommonMergeDefineLocalesInTheBuildConfiguration]: guide/i18n/merge#define-locales-in-the-build-configuration "Define locales in the build configuration - Merge translations into the application | Angular" [GuideI18nCommonMergeGenerateApplicationVariantsForEachLocale]: guide/i18n/merge#generate-application-variants-for-each-locale "Generate application variants for each locale - Merge translations into the application | Angular" [GuideI18nCommonTranslationFilesChangeTheSourceLanguageFileFormat]: guide/i18n/translation-files#change-the-source-language-file-format "Change the source language file format - Work with translation files | Angular" [GuideWorkspaceConfig]: reference/configs/workspace-config "Angular workspace configuration | Angular"
{ "end_byte": 10869, "start_byte": 9284, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/merge.md" }
angular/adev/src/content/guide/i18n/BUILD.bazel_0_1020
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "i18n", srcs = glob([ "*.md", ]), data = [ "//adev/src/content/examples/i18n:angular.json", "//adev/src/content/examples/i18n:doc-files/apache2.conf", "//adev/src/content/examples/i18n:doc-files/app.component.html", "//adev/src/content/examples/i18n:doc-files/commands.sh", "//adev/src/content/examples/i18n:doc-files/locale_plural_function.ts", "//adev/src/content/examples/i18n:doc-files/main.1.ts", "//adev/src/content/examples/i18n:doc-files/messages.fr.xlf.html", "//adev/src/content/examples/i18n:doc-files/nginx.conf", "//adev/src/content/examples/i18n:doc-files/rendered-output.html", "//adev/src/content/examples/i18n:src/app/app.component.html", "//adev/src/content/examples/i18n:src/app/app.component.ts", "//adev/src/content/examples/i18n:src/main.ts", ], visibility = ["//adev:__subpackages__"], )
{ "end_byte": 1020, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/BUILD.bazel" }
angular/adev/src/content/guide/i18n/locale-id.md_0_3140
# Refer to locales by ID Angular uses the Unicode *locale identifier* \(Unicode locale ID\) to find the correct locale data for internationalization of text strings. <docs-callout title="Unicode locale ID"> * A locale ID conforms to the [Unicode Common Locale Data Repository (CLDR) core specification][UnicodeCldrDevelopmentCoreSpecification]. For more information about locale IDs, see [Unicode Language and Locale Identifiers][UnicodeCldrDevelopmentCoreSpecificationLocaleIDs]. * CLDR and Angular use [BCP 47 tags][RfcEditorInfoBcp47] as the base for the locale ID </docs-callout> A locale ID specifies the language, country, and an optional code for further variants or subdivisions. A locale ID consists of the language identifier, a hyphen \(`-`\) character, and the locale extension. <docs-code language="html"> {language_id}-{locale_extension} </docs-code> HELPFUL: To accurately translate your Angular project, you must decide which languages and locales you are targeting for internationalization. Many countries share the same language, but differ in usage. The differences include grammar, punctuation, formats for currency, decimal numbers, dates, and so on. For the examples in this guide, use the following languages and locales. | Language | Locale | Unicode locale ID | |:--- |:--- |:--- | | English | Canada | `en-CA` | | English | United States of America | `en-US` | | French | Canada | `fr-CA` | | French | France | `fr-FR` | The [Angular repository][GithubAngularAngularTreeMasterPackagesCommonLocales] includes common locales. <docs-callout> For a list of language codes, see [ISO 639-2](https://www.loc.gov/standards/iso639-2). </docs-callout> ## Set the source locale ID Use the Angular CLI to set the source language in which you are writing the component template and code. By default, Angular uses `en-US` as the source locale of your project. To change the source locale of your project for the build, complete the following actions. 1. Open the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file. 1. Change the source locale in the `sourceLocale` field. ## What's next <docs-pill-row> <docs-pill href="guide/i18n/format-data-locale" title="Format data based on locale"/> </docs-pill-row> [GuideWorkspaceConfig]: reference/configs/workspace-config "Angular workspace configuration | Angular" [GithubAngularAngularTreeMasterPackagesCommonLocales]: <https://github.com/angular/angular/tree/main/packages/common/locales> "angular/packages/common/locales | angular/angular | GitHub" [RfcEditorInfoBcp47]: https://www.rfc-editor.org/info/bcp47 "BCP 47 | RFC Editor" [UnicodeCldrDevelopmentCoreSpecification]: https://cldr.unicode.org/index/cldr-spec "Core Specification | Unicode CLDR Project" [UnicodeCldrDevelopmentCoreSpecificationLocaleID]: https://cldr.unicode.org/index/cldr-spec/picking-the-right-language-code "Unicode Language and Locale Identifiers - Core Specification | Unicode CLDR Project"
{ "end_byte": 3140, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/i18n/locale-id.md" }
angular/adev/src/content/guide/animations/overview.md_0_3625
# 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>
{ "end_byte": 3625, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/animations/overview.md" }
angular/adev/src/content/guide/animations/overview.md_3625_10942
## Animating a transition Let's animate a transition that changes a single HTML element from one state to another. For example, you can specify that a button displays either **Open** or **Closed** based on the user's last action. When the button is in the `open` state, it's visible and yellow. When it's the `closed` state, it's translucent and blue. In HTML, these attributes are set using ordinary CSS styles such as color and opacity. In Angular, use the `style()` function to specify a set of CSS styles for use with animations. Collect a set of styles in an animation state, and give the state a name, such as `open` or `closed`. HELPFUL: Let's create a new `open-close` component to animate with simple transitions. Run the following command in terminal to generate the component: <docs-code language="shell"> ng g component open-close </docs-code> This will create the component at `src/app/open-close.component.ts`. ### Animation state and styles Use Angular's [`state()`](api/animations/state) function to define different states to call at the end of each transition. This function takes two arguments: A unique name like `open` or `closed` and a `style()` function. Use the `style()` function to define a set of styles to associate with a given state name. You must use *camelCase* for style attributes that contain dashes, such as `backgroundColor` or wrap them in quotes, such as `'background-color'`. Let's see how Angular's [`state()`](api/animations/state) function works with the `style⁣­(⁠)` function to set CSS style attributes. In this code snippet, multiple style attributes are set at the same time for the state. In the `open` state, the button has a height of 200 pixels, an opacity of 1, and a yellow background color. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="state1"/> In the following `closed` state, the button has a height of 100 pixels, an opacity of 0.8, and a background color of blue. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="state2"/> ### Transitions and timing In Angular, you can set multiple styles without any animation. However, without further refinement, the button instantly transforms with no fade, no shrinkage, or other visible indicator that a change is occurring. To make the change less abrupt, you need to define an animation *transition* to specify the changes that occur between one state and another over a period of time. The `transition()` function accepts two arguments: The first argument accepts an expression that defines the direction between two transition states, and the second argument accepts one or a series of `animate()` steps. Use the `animate()` function to define the length, delay, and easing of a transition, and to designate the style function for defining styles while transitions are taking place. Use the `animate()` function to define the `keyframes()` function for multi-step animations. These definitions are placed in the second argument of the `animate()` function. #### Animation metadata: duration, delay, and easing The `animate()` function \(second argument of the transition function\) accepts the `timings` and `styles` input parameters. The `timings` parameter takes either a number or a string defined in three parts. <docs-code language="typescript"> animate (duration) </docs-code> or <docs-code language="typescript"> animate ('duration delay easing') </docs-code> The first part, `duration`, is required. The duration can be expressed in milliseconds as a number without quotes, or in seconds with quotes and a time specifier. For example, a duration of a tenth of a second can be expressed as follows: * As a plain number, in milliseconds: `100` * In a string, as milliseconds: `'100ms'` * In a string, as seconds: `'0.1s'` The second argument, `delay`, has the same syntax as `duration`. For example: * Wait for 100ms and then run for 200ms: `'0.2s 100ms'` The third argument, `easing`, controls how the animation [accelerates and decelerates](https://easings.net) during its runtime. For example, `ease-in` causes the animation to begin slowly, and to pick up speed as it progresses. * Wait for 100ms, run for 200ms. Use a deceleration curve to start out fast and slowly decelerate to a resting point: `'0.2s 100ms ease-out'` * Run for 200ms, with no delay. Use a standard curve to start slow, accelerate in the middle, and then decelerate slowly at the end: `'0.2s ease-in-out'` * Start immediately, run for 200ms. Use an acceleration curve to start slow and end at full velocity: `'0.2s ease-in'` HELPFUL: See the Material Design website's topic on [Natural easing curves](https://material.io/design/motion/speed.html#easing) for general information on easing curves. This example provides a state transition from `open` to `closed` with a 1-second transition between states. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="transition1"/> In the preceding code snippet, the `=>` operator indicates unidirectional transitions, and `<=>` is bidirectional. Within the transition, `animate()` specifies how long the transition takes. In this case, the state change from `open` to `closed` takes 1 second, expressed here as `1s`. This example adds a state transition from the `closed` state to the `open` state with a 0.5-second transition animation arc. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="transition2"/> HELPFUL: Some additional notes on using styles within [`state`](api/animations/state) and `transition` functions. * Use [`state()`](api/animations/state) to define styles that are applied at the end of each transition, they persist after the animation completes * Use `transition()` to define intermediate styles, which create the illusion of motion during the animation * When animations are disabled, `transition()` styles can be skipped, but [`state()`](api/animations/state) styles can't * Include multiple state pairs within the same `transition()` argument: <docs-code language="typescript"> transition( 'on => off, off => void' ) </docs-code> ### Triggering the animation An animation requires a *trigger*, so that it knows when to start. The `trigger()` function collects the states and transitions, and gives the animation a name, so that you can attach it to the triggering element in the HTML template. The `trigger()` function describes the property name to watch for changes. When a change occurs, the trigger initiates the actions included in its definition. These actions can be transitions or other functions, as we'll see later on. In this example, we'll name the trigger `openClose`, and attach it to the `button` element. The trigger describes the open and closed states, and the timings for the two transitions. HELPFUL: Within each `trigger()` function call, an element can only be in one state at any given time. However, it's possible for multiple triggers to be active at once. ### D
{ "end_byte": 10942, "start_byte": 3625, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/animations/overview.md" }
angular/adev/src/content/guide/animations/overview.md_10942_18604
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>
{ "end_byte": 18604, "start_byte": 10942, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/animations/overview.md" }