_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular/adev/src/content/guide/animations/reusable-animations.md_0_1949
# Reusable animations This topic provides some examples of how to create reusable animations. ## Create reusable animations To create a reusable animation, use the [`animation()`](api/animations/animation) function to define an animation in a separate `.ts` file and declare this animation definition as a `const` export variable. You can then import and reuse this animation in any of your application components using the [`useAnimation()`](api/animations/useAnimation) function. <docs-code header="src/app/animations.ts" path="adev/src/content/examples/animations/src/app/animations.1.ts" visibleRegion="animation-const"/> In the preceding code snippet, `transitionAnimation` is made reusable by declaring it as an export variable. HELPFUL: The `height`, `opacity`, `backgroundColor`, and `time` inputs are replaced during runtime. You can also export a part of an animation. For example, the following snippet exports the animation `trigger`. <docs-code header="src/app/animations.1.ts" path="adev/src/content/examples/animations/src/app/animations.1.ts" visibleRegion="trigger-const"/> From this point, you can import reusable animation variables in your component class. For example, the following code snippet imports the `transitionAnimation` variable and uses it via the `useAnimation()` function. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.3.ts" visibleRegion="reusable"/> ## More on Angular animations You might also be interested in the following: <docs-pill-row> <docs-pill href="guide/animations" title="Introduction to Angular animations"/> <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/route-animations" title="Route transition animations"/> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 1949, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/animations/reusable-animations.md" }
angular/adev/src/content/guide/animations/complex-sequences.md_0_9717
# Complex animation sequences So far, we've learned simple animations of single HTML elements. Angular also lets you animate coordinated sequences, such as an entire grid or list of elements as they enter and leave a page. You can choose to run multiple animations in parallel, or run discrete animations sequentially, one following another. The functions that control complex animation sequences are: | Functions | Details | |:--- |:--- | | `query()` | Finds one or more inner HTML elements. | | `stagger()` | Applies a cascading delay to animations for multiple elements. | | [`group()`](api/animations/group) | Runs multiple animation steps in parallel. | | `sequence()` | Runs animation steps one after another. | ## The query() function Most complex animations rely on the `query()` function to find child elements and apply animations to them, basic examples of such are: | Examples | Details | |:--- |:--- | | `query()` followed by `animate()` | Used to query simple HTML elements and directly apply animations to them. | | `query()` followed by `animateChild()` | Used to query child elements, which themselves have animations metadata applied to them and trigger such animation \(which would be otherwise be blocked by the current/parent element's animation\). | The first argument of `query()` is a [css selector](https://developer.mozilla.org/docs/Web/CSS/CSS_Selectors) string which can also contain the following Angular-specific tokens: | Tokens | Details | |:--- |:--- | | `:enter` <br /> `:leave` | For entering/leaving elements. | | `:animating` | For elements currently animating. | | `@*` <br /> `@triggerName` | For elements with any—or a specific—trigger. | | `:self` | The animating element itself. | <docs-callout title="Entering and Leaving Elements"> Not all child elements are actually considered as entering/leaving; this can, at times, be counterintuitive and confusing. Please see the [query api docs](api/animations/query#entering-and-leaving-elements) for more information. You can also see an illustration of this in the animations example \(introduced in the animations [introduction section](guide/animations#about-this-guide)\) under the Querying tab. </docs-callout> ## Animate multiple elements using query() and stagger() functions After having queried child elements via `query()`, the `stagger()` function lets you define a timing gap between each queried item that is animated and thus animates elements with a delay between them. The following example demonstrates how to use the `query()` and `stagger()` functions to animate a list \(of heroes\) adding each in sequence, with a slight delay, from top to bottom. * Use `query()` to look for an element entering the page that meets certain criteria * For each of these elements, use `style()` to set the same initial style for the element. Make it transparent and use `transform` to move it out of position so that it can slide into place. * Use `stagger()` to delay each animation by 30 milliseconds * Animate each element on screen for 0.5 seconds using a custom-defined easing curve, simultaneously fading it in and un-transforming it <docs-code header="src/app/hero-list-page.component.ts" path="adev/src/content/examples/animations/src/app/hero-list-page.component.ts" visibleRegion="page-animations"/> ## Parallel animation using group() function You've seen how to add a delay between each successive animation. But you might also want to configure animations that happen in parallel. For example, you might want to animate two CSS properties of the same element but use a different `easing` function for each one. For this, you can use the animation [`group()`](api/animations/group) function. HELPFUL: The [`group()`](api/animations/group) function is used to group animation *steps*, rather than animated elements. The following example uses [`group()`](api/animations/group)s on both `:enter` and `:leave` for two different timing configurations, thus applying two independent animations to the same element in parallel. <docs-code header="src/app/hero-list-groups.component.ts (excerpt)" path="adev/src/content/examples/animations/src/app/hero-list-groups.component.ts" visibleRegion="animationdef"/> ## Sequential vs. parallel animations Complex animations can have many things happening at once. But what if you want to create an animation involving several animations happening one after the other? Earlier you used [`group()`](api/animations/group) to run multiple animations all at the same time, in parallel. A second function called `sequence()` lets you run those same animations one after the other. Within `sequence()`, the animation steps consist of either `style()` or `animate()` function calls. * Use `style()` to apply the provided styling data immediately. * Use `animate()` to apply styling data over a given time interval. ## Filter animation example Take a look at another animation on the example page. Under the Filter/Stagger tab, enter some text into the **Search Heroes** text box, such as `Magnet` or `tornado`. The filter works in real time as you type. Elements leave the page as you type each new letter and the filter gets progressively stricter. The heroes list gradually re-enters the page as you delete each letter in the filter box. The HTML template contains a trigger called `filterAnimation`. <docs-code header="src/app/hero-list-page.component.html" path="adev/src/content/examples/animations/src/app/hero-list-page.component.html" visibleRegion="filter-animations" language="angular-html"/> The `filterAnimation` in the component's decorator contains three transitions. <docs-code header="src/app/hero-list-page.component.ts" path="adev/src/content/examples/animations/src/app/hero-list-page.component.ts" visibleRegion="filter-animations"/> The code in this example performs the following tasks: * Skips animations when the user first opens or navigates to this page \(the filter animation narrows what is already there, so it only works on elements that already exist in the DOM\) * Filters heroes based on the search input's value For each change: * Hides an element leaving the DOM by setting its opacity and width to 0 * Animates an element entering the DOM over 300 milliseconds. During the animation, the element assumes its default width and opacity. * If there are multiple elements entering or leaving the DOM, staggers each animation starting at the top of the page, with a 50-millisecond delay between each element ## Animating the items of a reordering list Although Angular animates correctly `*ngFor` list items out of the box, it will not be able to do so if their ordering changes. This is because it will lose track of which element is which, resulting in broken animations. The only way to help Angular keep track of such elements is by assigning a `TrackByFunction` to the `NgForOf` directive. This makes sure that Angular always knows which element is which, thus allowing it to apply the correct animations to the correct elements all the time. IMPORTANT: If you need to animate the items of an `*ngFor` list and there is a possibility that the order of such items will change during runtime, always use a `TrackByFunction`. ## Animations and Component View Encapsulation Angular animations are based on the components DOM structure and do not directly take [View Encapsulation](guide/components/styling#style-scoping) into account, this means that components using `ViewEncapsulation.Emulated` behave exactly as if they were using `ViewEncapsulation.None` (`ViewEncapsulation.ShadowDom` behaves differently as we'll discuss shortly). For example if the `query()` function (which you'll see more of in the rest of the Animations guide) were to be applied at the top of a tree of components using the emulated view encapsulation, such query would be able to identify (and thus animate) DOM elements on any depth of the tree. On the other hand the `ViewEncapsulation.ShadowDom` changes the component's DOM structure by "hiding" DOM elements inside [`ShadowRoot`](https://developer.mozilla.org/docs/Web/API/ShadowRoot) elements. Such DOM manipulations do prevent some of the animations implementation to work properly since it relies on simple DOM structures and doesn't take `ShadowRoot` elements into account. Therefore it is advised to avoid applying animations to views incorporating components using the ShadowDom view encapsulation. ## Animation sequence summary Angular functions for animating multiple elements start with `query()` to find inner elements; for example, gathering all images within a `<div>`. The remaining functions, `stagger()`, [`group()`](api/animations/group), and `sequence()`, apply cascades or let you control how multiple animation steps are applied. ## More on Angular animations You might also be interested in the following: <docs-pill-row> <docs-pill href="guide/animations" title="Introduction to Angular animations"/> <docs-pill href="guide/animations/transition-and-triggers" title="Transition and triggers"/> <docs-pill href="guide/animations/reusable-animations" title="Reusable animations"/> <docs-pill href="guide/animations/route-animations" title="Route transition animations"/> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 9717, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/animations/complex-sequences.md" }
angular/adev/src/content/guide/animations/route-animations.md_0_9208
# Route transition animations When a user navigates from one route to another, the Angular Router maps the URL path to the relevant component and displays its view. Animating this route transition can greatly enhance the user experience. The Router has support for the View Transitions API when navigating between routes in Chrome/Chromium browsers. HELPFUL: The Router's native View Transitions integraiton is currently in [developer preview](/reference/releases#developer-preview). Native View Transitions are also a relatively new feature so there may be limited support in some browsers. ## How View Transitions work The native browser method that’s used for view transitions is `document.startViewTransition`. When `startViewTransition()` is called, the browser captures the current state of the page which includes taking a screenshot. The method takes a callback that updates the DOM and this function can be asynchronous. The new state is captured and the transition begins in the next animation frame when the promise returned by the callback resolves. Here’s an example of the startViewTransition api: ```ts document.startViewTransition(async () => { await updateTheDOMSomehow(); }); ``` If you’re curious to read more about the details of the browser API, the [Chrome Explainer](https://developer.chrome.com/docs/web-platform/view-transitions) is an invaluable resource. ## How the Router uses view transitions Several things happen after navigation starts in the router: route matching, loading lazy routes and components, executing guards and resolvers to name a few. Once these have completed successfully, the new routes are ready to be activated. This route activation is the DOM update that we want to perform as part of the view transition. When the view transition feature is enabled, navigation “pauses” and a call is made to the browser’s `startViewTransition` method. Once the `startViewTransition` callback executes (this happens asynchronously, as outlined in the spec here), navigation “resumes”. The remaining steps for the router navigation include updating the browser URL and activating or deactivating the matched routes (the DOM update). Finally, the callback passed to `startViewTransition` returns a Promise that resolves once Angular has finished rendering. As described above, this indicates to the browser that the new DOM state should be captured and the transition should begin. View transitions are a [progressive enhancement](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement). If the browser does not support the API, the Router will perform the DOM updates without calling `startViewTransition` and the navigation will not be animated. ## Enabling View Transitions in the Router To enable this feature, simply add `withViewTransitions` to the `provideRouter` or set `enableViewTransitions: true` in `RouterModule.forRoot`: ```ts // Standalone bootstrap bootstrapApplication(MyApp, {providers: [ provideRouter(ROUTES, withViewTransitions()), ]}); // NgModule bootstrap @NgModule({ imports: [RouterModule.forRoot(routes, {enableViewTransitions: true})] }) export class AppRouting {} ``` [Try the “count” example on StackBlitz](https://stackblitz.com/edit/stackblitz-starters-2dnvtm?file=src%2Fmain.ts) This example uses the counter application from the Chrome explainer and replaces the direct call to startViewTransition when the counter increments with a router navigation. ## Using CSS to customize transitions View transitions can be customized with CSS. We can also instruct the browser to create separate elements for the transition by setting a view-transition-name. We can expand the first example by adding view-transition-name: count to the .count style in the Counter component. Then, in the global styles, we can define a custom animation for this view transition: ```css /* Custom transition */ @keyframes rotate-out { to { transform: rotate(90deg); } } @keyframes rotate-in { from { transform: rotate(-90deg); } } ::view-transition-old(count), ::view-transition-new(count) { animation-duration: 200ms; animation-name: -ua-view-transition-fade-in, rotate-in; } ::view-transition-old(count) { animation-name: -ua-view-transition-fade-out, rotate-out; } ``` It is important that the view transition animations are defined in a global style file. They cannot be defined in the component styles because the default view encapsulation will scope the styles to the component. [Try the updated “count” example on StackBlitz](https://stackblitz.com/edit/stackblitz-starters-fwn4i7?file=src%2Fmain.ts) ## Controlling transitions with onViewTransitionCreated The `withViewTransitions` router feature can also be called with an options object that includes an `onViewTransitionCreated` callback. This callback is run in an [injection context](/guide/di/dependency-injection-context#run-within-an-injection-context) and receives a [ViewTransitionInfo](/api/router/ViewTransitionInfo) object that includes the `ViewTransition` returned from `startViewTransition`, as well as the `ActivatedRouteSnapshot` that the navigation is transitioning from and the new one that it is transitioning to. This callback can be used for any number of customizations. For example, you might want to skip transitions under certain conditions. We use this on the new angular.dev docs site: ```ts withViewTransitions({ onViewTransitionCreated: ({transition}) => { const router = inject(Router); const targetUrl = router.getCurrentNavigation()!.finalUrl!; // Skip the transition if the only thing // changing is the fragment and queryParams const config = { paths: 'exact', matrixParams: 'exact', fragment: 'ignored', queryParams: 'ignored', }; if (router.isActive(targetUrl, config)) { transition.skipTransition(); } }, }), ``` In this code snippet, we create a `UrlTree` from the `ActivatedRouteSnapshot` the navigation is going to. We then check with the Router to see if this `UrlTree` is already active, ignoring any differences in the fragment or query parameters. If it is already active, we call skipTransition which will skip the animation portion of the view transition. This is the case when clicking on an anchor link that will only scroll to another location in the same document. ## Examples from the Chrome explainer adapted to Angular We’ve recreated some of the great examples from the Chrome Team in Angular for you to explore. ### Transitioning elements don’t need to be the same DOM element * [Chrome Explainer](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#transitioning_elements_dont_need_to_be_the_same_dom_element) * [Angular Example on StackBlitz](https://stackblitz.com/edit/stackblitz-starters-dh8npr?file=src%2Fmain.ts) ### Custom entry and exit animations * [Chrome Explainer](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#custom_entry_and_exit_transitions) * [Angular Example on StackBlitz](https://stackblitz.com/edit/stackblitz-starters-8kly3o) ### Async DOM updates and waiting for content * [Chrome Explainer](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#async_dom_updates_and_waiting_for_content) > During this time, the page is frozen, so delays here should be kept to a minimum…in some cases it’s better to avoid the delay altogether, and use the content you already have. The view transition feature in the Angular router does not provide a way to delay the animation. For the moment, our stance is that it’s always better to use the content you have rather than making the page non-interactive for any additional amount of time. ### Handle multiple view transition styles with view transition types * [Chrome Explainer](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types) * [Angular Example on StackBlitz](https://stackblitz.com/edit/stackblitz-starters-vxzcam) ### Handle multiple view transition styles with a class name on the view transition root (deprecated) * [Chrome Explainer](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#changing-on-navigation-type) * [Angular Example on StackBlitz](https://stackblitz.com/edit/stackblitz-starters-nmnzzg?file=src%2Fmain.ts) ### Transitioning without freezing other animations * [Chrome Explainer](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#transitioning-without-freezing) * [Angular Example on StackBlitz](https://stackblitz.com/edit/stackblitz-starters-76kgww) ### Animating with Javascript * [Chrome Explainer](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#animating-with-javascript) * [Angular Example on StackBlitz](https://stackblitz.com/edit/stackblitz-starters-cklnkm) ## Native View Transitions Alternative Animating the transition between routes can also be done with the `@angular/animations` package. The animation [triggers and transitions](/guide/animations/transition-and-triggers) can be derived from the router state, such as the current URL or `ActivatedRoute`.
{ "commit_id": "cb34e406ba", "end_byte": 9208, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/animations/route-animations.md" }
angular/adev/src/content/guide/animations/transition-and-triggers.md_0_8230
# Animation transitions and triggers This guide goes into depth on special transition states such as the `*` wildcard and `void`. It shows how these special states are used for elements entering and leaving a view. This section also explores multiple animation triggers, animation callbacks, and sequence-based animation using keyframes. ## Predefined states and wildcard matching In Angular, transition states can be defined explicitly through the [`state()`](api/animations/state) function, or using the predefined `*` wildcard and `void` states. ### Wildcard state An asterisk `*` or *wildcard* matches any animation state. This is useful for defining transitions that apply regardless of the HTML element's start or end state. For example, a transition of `open => *` applies when the element's state changes from open to anything else. <img alt="wildcard state expressions" src="assets/images/guide/animations/wildcard-state-500.png"> The following is another code sample using the wildcard state together with the previous example using the `open` and `closed` states. Instead of defining each state-to-state transition pair, any transition to `closed` takes 1 second, and any transition to `open` takes 0.5 seconds. This allows the addition of new states without having to include separate transitions for each one. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="trigger-wildcard1"/> Use a double arrow syntax to specify state-to-state transitions in both directions. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="trigger-wildcard2"/> ### Use wildcard state with multiple transition states In the two-state button example, the wildcard isn't that useful because there are only two possible states, `open` and `closed`. In general, use wildcard states when an element has multiple potential states that it can change to. If the button can change from `open` to either `closed` or something like `inProgress`, using a wildcard state could reduce the amount of coding needed. <img alt="wildcard state with 3 states" src="assets/images/guide/animations/wildcard-3-states.png"> <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="trigger-transition"/> The `* => *` transition applies when any change between two states takes place. Transitions are matched in the order in which they are defined. Thus, you can apply other transitions on top of the `* => *` transition. For example, define style changes or animations that would apply just to `open => closed`, then use `* => *` as a fallback for state pairings that aren't otherwise called out. To do this, list the more specific transitions *before* `* => *`. ### Use wildcards with styles Use the wildcard `*` with a style to tell the animation to use whatever the current style value is, and animate with that. Wildcard is a fallback value that's used if the state being animated isn't declared within the trigger. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="transition4"/> ### Void state Use the `void` state to configure transitions for an element that is entering or leaving a page. See [Animating entering and leaving a view](guide/animations/transition-and-triggers#aliases-enter-and-leave). ### Combine wildcard and void states Combine wildcard and void states in a transition to trigger animations that enter and leave the page: * A transition of `* => void` applies when the element leaves a view, regardless of what state it was in before it left * A transition of `void => *` applies when the element enters a view, regardless of what state it assumes when entering * The wildcard state `*` matches to *any* state, including `void` ## Animate entering and leaving a view This section shows how to animate elements entering or leaving a page. Add a new behavior: * When you add a hero to the list of heroes, it appears to fly onto the page from the left * When you remove a hero from the list, it appears to fly out to the right <docs-code header="src/app/hero-list-enter-leave.component.ts" path="adev/src/content/examples/animations/src/app/hero-list-enter-leave.component.ts" visibleRegion="animationdef"/> In the preceding code, you applied the `void` state when the HTML element isn't attached to a view. ## Aliases :enter and :leave `:enter` and `:leave` are aliases for the `void => *` and `* => void` transitions. These aliases are used by several animation functions. <docs-code hideCopy language="typescript"> transition ( ':enter', [ … ] ); // alias for void => * transition ( ':leave', [ … ] ); // alias for * => void </docs-code> It's harder to target an element that is entering a view because it isn't in the DOM yet. Use the aliases `:enter` and `:leave` to target HTML elements that are inserted or removed from a view. ### Use `*ngIf` and `*ngFor` with :enter and :leave The `:enter` transition runs when any `*ngIf` or `*ngFor` views are placed on the page, and `:leave` runs when those views are removed from the page. IMPORTANT: Entering/leaving behaviors can sometime be confusing. As a rule of thumb consider that any element being added to the DOM by Angular passes via the `:enter` transition. Only elements being directly removed from the DOM by Angular pass via the `:leave` transition. For example, an element's view is removed from the DOM because its parent is being removed from the DOM. This example has a special trigger for the enter and leave animation called `myInsertRemoveTrigger`. The HTML template contains the following code. <docs-code header="src/app/insert-remove.component.html" path="adev/src/content/examples/animations/src/app/insert-remove.component.html" visibleRegion="insert-remove"/> In the component file, the `:enter` transition sets an initial opacity of 0. It then animates it to change that opacity to 1 as the element is inserted into the view. <docs-code header="src/app/insert-remove.component.ts" path="adev/src/content/examples/animations/src/app/insert-remove.component.ts" visibleRegion="enter-leave-trigger"/> Note that this example doesn't need to use [`state()`](api/animations/state). ## Transition :increment and :decrement The `transition()` function takes other selector values, `:increment` and `:decrement`. Use these to kick off a transition when a numeric value has increased or decreased in value. HELPFUL: The following example uses `query()` and `stagger()` methods. For more information on these methods, see the [complex sequences](guide/animations/complex-sequences) page. <docs-code header="src/app/hero-list-page.component.ts" path="adev/src/content/examples/animations/src/app/hero-list-page.component.ts" visibleRegion="increment"/> ## Boolean values in transitions If a trigger contains a Boolean value as a binding value, then this value can be matched using a `transition()` expression that compares `true` and `false`, or `1` and `0`. <docs-code header="src/app/open-close.component.html" path="adev/src/content/examples/animations/src/app/open-close.component.2.html" visibleRegion="trigger-boolean"/> In the code snippet above, the HTML template binds a `<div>` element to a trigger named `openClose` with a status expression of `isOpen`, and with possible values of `true` and `false`. This pattern is an alternative to the practice of creating two named states like `open` and `close`. Inside the `@Component` metadata under the `animations:` property, when the state evaluates to `true`, the associated HTML element's height is a wildcard style or default. In this case, the animation uses whatever height the element already had before the animation started. When the element is `closed`, the element gets animated to a height of 0, which makes it invisible. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.2.ts" visibleRegion="trigger-boolean"/> ## M
{ "commit_id": "cb34e406ba", "end_byte": 8230, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/animations/transition-and-triggers.md" }
angular/adev/src/content/guide/animations/transition-and-triggers.md_8230_17293
ultiple animation triggers You can define more than one animation trigger for a component. Attach animation triggers to different elements, and the parent-child relationships among the elements affect how and when the animations run. ### Parent-child animations Each time an animation is triggered in Angular, the parent animation always gets priority and child animations are blocked. For a child animation to run, the parent animation must query each of the elements containing child animations. It then lets the animations run using the [`animateChild()`](api/animations/animateChild) function. #### Disable an animation on an HTML element A special animation control binding called `@.disabled` can be placed on an HTML element to turn off animations on that element, as well as any nested elements. When true, the `@.disabled` binding prevents all animations from rendering. The following code sample shows how to use this feature. <docs-code-multifile> <docs-code header="src/app/open-close.component.html" path="adev/src/content/examples/animations/src/app/open-close.component.4.html" visibleRegion="toggle-animation"/> <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.4.ts" visibleRegion="toggle-animation" language="typescript"/> </docs-code-multifile> When the `@.disabled` binding is true, the `@childAnimation` trigger doesn't kick off. When an element within an HTML template has animations turned off using the `@.disabled` host binding, animations are turned off on all inner elements as well. You can't selectively turn off multiple animations on a single element.<!-- vale off --> A selective child animations can still be run on a disabled parent in one of the following ways: * A parent animation can use the [`query()`](api/animations/query) function to collect inner elements located in disabled areas of the HTML template. Those elements can still animate. <!-- vale on --> * A child animation can be queried by a parent and then later animated with the `animateChild()` function #### Disable all animations To turn off all animations for an Angular application, place the `@.disabled` host binding on the topmost Angular component. <docs-code header="src/app/app.component.ts" path="adev/src/content/examples/animations/src/app/app.component.ts" visibleRegion="toggle-app-animations"/> HELPFUL: Disabling animations application-wide is useful during end-to-end \(E2E\) testing. ## Animation callbacks The animation `trigger()` function emits *callbacks* when it starts and when it finishes. The following example features a component that contains an `openClose` trigger. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="events1"/> In the HTML template, the animation event is passed back via `$event`, as `@triggerName.start` and `@triggerName.done`, where `triggerName` is the name of the trigger being used. In this example, the trigger `openClose` appears as follows. <docs-code header="src/app/open-close.component.html" path="adev/src/content/examples/animations/src/app/open-close.component.3.html" visibleRegion="callbacks"/> A potential use for animation callbacks could be to cover for a slow API call, such as a database lookup. For example, an **InProgress** button can be set up to have its own looping animation while the backend system operation finishes. Another animation can be called when the current animation finishes. For example, the button goes from the `inProgress` state to the `closed` state when the API call is completed. An animation can influence an end user to *perceive* the operation as faster, even when it is not. Callbacks can serve as a debugging tool, for example in conjunction with `console.warn()` to view the application's progress in a browser's Developer JavaScript Console. The following code snippet creates console log output for the original example, a button with the two states of `open` and `closed`. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.ts" visibleRegion="events"/> ## Keyframes To create an animation with multiple steps run in sequence, use *keyframes*. Angular's `keyframe()` function allows several style changes within a single timing segment. For example, the button, instead of fading, could change color several times over a single 2-second time span. <img alt="keyframes" src="assets/images/guide/animations/keyframes-500.png"> The code for this color change might look like this. <docs-code header="src/app/status-slider.component.ts" path="adev/src/content/examples/animations/src/app/status-slider.component.ts" visibleRegion="keyframes"/> ### Offset Keyframes include an `offset` that defines the point in the animation where each style change occurs. Offsets are relative measures from zero to one, marking the beginning and end of the animation. They should be applied to each of the keyframe steps if used at least once. Defining offsets for keyframes is optional. If you omit them, evenly spaced offsets are automatically assigned. For example, three keyframes without predefined offsets receive offsets of 0, 0.5, and 1. Specifying an offset of 0.8 for the middle transition in the preceding example might look like this. <img alt="keyframes with offset" src="assets/images/guide/animations/keyframes-offset-500.png"> The code with offsets specified would be as follows. <docs-code header="src/app/status-slider.component.ts" path="adev/src/content/examples/animations/src/app/status-slider.component.ts" visibleRegion="keyframesWithOffsets"/> You can combine keyframes with `duration`, `delay`, and `easing` within a single animation. ### Keyframes with a pulsation Use keyframes to create a pulse effect in your animations by defining styles at specific offset throughout the animation. Here's an example of using keyframes to create a pulse effect: * The original `open` and `closed` states, with the original changes in height, color, and opacity, occurring over a timeframe of 1 second * A keyframes sequence inserted in the middle that causes the button to appear to pulsate irregularly over the course of that same 1 second timeframe <img alt="keyframes with irregular pulsation" src="assets/images/guide/animations/keyframes-pulsation.png"> The code snippet for this animation might look like this. <docs-code header="src/app/open-close.component.ts" path="adev/src/content/examples/animations/src/app/open-close.component.1.ts" visibleRegion="trigger"/> ### Animatable properties and units Angular animations support builds on top of web animations, so 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. For properties with a numeric value, define a unit by providing the value as a string, in quotes, with the appropriate suffix: * 50 pixels: `'50px'` * Relative font size: `'3em'` * Percentage: `'100%'` You can also provide the value as a number. In such cases Angular assumes a default unit of pixels, or `px`. Expressing 50 pixels as `50` is the same as saying `'50px'`. HELPFUL: The string `"50"` would instead not be considered valid\). ### Automatic property calculation with wildcards Sometimes, the value of a dimensional style property isn't known until runtime. For example, elements often have widths and heights that depend on their content or the screen size. These properties are often challenging to animate using CSS. In these cases, you can use a special wildcard `*` property value under `style()`. The value of that particular style property is computed at runtime and then plugged into the animation. The following example has a trigger called `shrinkOut`, used when an HTML element leaves the page. The animation takes whatever height the element has before it leaves, and animates from that height to zero. <docs-code header="src/app/hero-list-auto.component.ts" path="adev/src/content/examples/animations/src/app/hero-list-auto.component.ts" visibleRegion="auto-calc"/> ### Keyframes summary The `keyframes()` function in Angular allows you to specify multiple interim styles within a single transition. An optional `offset` can be used to define the point in the animation where each style change should occur. ## More on Angular animations You might also be interested in the following: <docs-pill-row> <docs-pill href="guide/animations" title="Introduction to Angular animations"/> <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>
{ "commit_id": "cb34e406ba", "end_byte": 17293, "start_byte": 8230, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/animations/transition-and-triggers.md" }
angular/adev/src/content/guide/animations/BUILD.bazel_0_2195
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "animations", srcs = glob([ "*.md", ]), data = [ "//adev/src/content/examples/animations:src/app/animations.1.ts", "//adev/src/content/examples/animations:src/app/animations.ts", "//adev/src/content/examples/animations:src/app/app.component.html", "//adev/src/content/examples/animations:src/app/app.component.ts", "//adev/src/content/examples/animations:src/app/app.module.1.ts", "//adev/src/content/examples/animations:src/app/app.routes.ts", "//adev/src/content/examples/animations:src/app/hero-list-auto.component.ts", "//adev/src/content/examples/animations:src/app/hero-list-enter-leave.component.ts", "//adev/src/content/examples/animations:src/app/hero-list-groups.component.ts", "//adev/src/content/examples/animations:src/app/hero-list-page.component.html", "//adev/src/content/examples/animations:src/app/hero-list-page.component.ts", "//adev/src/content/examples/animations:src/app/insert-remove.component.html", "//adev/src/content/examples/animations:src/app/insert-remove.component.ts", "//adev/src/content/examples/animations:src/app/open-close.component.1.html", "//adev/src/content/examples/animations:src/app/open-close.component.1.ts", "//adev/src/content/examples/animations:src/app/open-close.component.2.html", "//adev/src/content/examples/animations:src/app/open-close.component.2.ts", "//adev/src/content/examples/animations:src/app/open-close.component.3.html", "//adev/src/content/examples/animations:src/app/open-close.component.3.ts", "//adev/src/content/examples/animations:src/app/open-close.component.4.html", "//adev/src/content/examples/animations:src/app/open-close.component.4.ts", "//adev/src/content/examples/animations:src/app/open-close.component.css", "//adev/src/content/examples/animations:src/app/open-close.component.ts", "//adev/src/content/examples/animations:src/app/status-slider.component.ts", ], visibility = ["//adev:__subpackages__"], )
{ "commit_id": "cb34e406ba", "end_byte": 2195, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/animations/BUILD.bazel" }
angular/adev/src/content/ecosystem/web-workers.md_0_2418
# Background processing using web workers [Web workers](https://developer.mozilla.org/docs/Web/API/Web_Workers_API) let you run CPU-intensive computations in a background thread, freeing the main thread to update the user interface. Application's performing a lot of computations, like generating Computer-Aided Design \(CAD\) drawings or doing heavy geometric calculations, can use web workers to increase performance. HELPFUL: The Angular CLI does not support running itself in a web worker. ## Adding a web worker To add a web worker to an existing project, use the Angular CLI `ng generate` command. <docs-code language="shell"> ng generate web-worker <location> </docs-code> You can add a web worker anywhere in your application. For example, to add a web worker to the root component, `src/app/app.component.ts`, run the following command. <docs-code language="shell"> ng generate web-worker app </docs-code> The command performs the following actions. 1. Configures your project to use web workers, if it isn't already. 1. Adds the following scaffold code to `src/app/app.worker.ts` to receive messages. <docs-code language="typescript" header="src/app/app.worker.ts"> addEventListener('message', ({ data }) => { const response = `worker response to ${data}`; postMessage(response); }); </docs-code> 1. Adds the following scaffold code to `src/app/app.component.ts` to use the worker. <docs-code language="typescript" header="src/app/app.component.ts"> if (typeof Worker !== 'undefined') { // Create a new const worker = new Worker(new URL('./app.worker', import.meta.url)); worker.onmessage = ({ data }) => { console.log(`page got message: ${data}`); }; worker.postMessage('hello'); } else { // Web workers are not supported in this environment. // You should add a fallback so that your program still executes correctly. } </docs-code> After you create this initial scaffold, you must refactor your code to use the web worker by sending messages to and from the worker. IMPORTANT: Some environments or platforms, such as `@angular/platform-server` used in [Server-side Rendering](guide/ssr), don't support web workers. To ensure that your application works in these environments, you must provide a fallback mechanism to perform the computations that the worker would otherwise perform.
{ "commit_id": "cb34e406ba", "end_byte": 2418, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/web-workers.md" }
angular/adev/src/content/ecosystem/BUILD.bazel_0_187
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "ecosystem", srcs = glob([ "*.md", ]), visibility = ["//adev:__subpackages__"], )
{ "commit_id": "cb34e406ba", "end_byte": 187, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/BUILD.bazel" }
angular/adev/src/content/ecosystem/service-workers/push-notifications.md_0_4545
# Push notifications Push notifications are a compelling way to engage users. Through the power of service workers, notifications can be delivered to a device even when your application is not in focus. The Angular service worker enables the display of push notifications and the handling of notification click events. HELPFUL: When using the Angular service worker, push notification interactions are handled using the `SwPush` service. To learn more about the browser APIs involved see [Push API](https://developer.mozilla.org/docs/Web/API/Push_API) and [Using the Notifications API](https://developer.mozilla.org/docs/Web/API/Notifications_API/Using_the_Notifications_API). ## Notification payload Invoke push notifications by pushing a message with a valid payload. See `SwPush` for guidance. HELPFUL: In Chrome, you can test push notifications without a backend. Open Devtools -> Application -> Service Workers and use the `Push` input to send a JSON notification payload. ## Notification click handling The default behavior for the `notificationclick` event is to close the notification and notify `SwPush.notificationClicks`. You can specify an additional operation to be executed on `notificationclick` by adding an `onActionClick` property to the `data` object, and providing a `default` entry. This is especially useful for when there are no open clients when a notification is clicked. <docs-code language="json"> { "notification": { "title": "New Notification!", "data": { "onActionClick": { "default": {"operation": "openWindow", "url": "foo"} } } } } </docs-code> ### Operations The Angular service worker supports the following operations: | Operations | Details | |:--- |:--- | | `openWindow` | Opens a new tab at the specified URL. | | `focusLastFocusedOrOpen` | Focuses the last focused client. If there is no client open, then it opens a new tab at the specified URL. | | `navigateLastFocusedOrOpen` | Focuses the last focused client and navigates it to the specified URL. If there is no client open, then it opens a new tab at the specified URL. | | `sendRequest` | Send a simple GET request to the specified URL. | IMPORTANT: URLs are resolved relative to the service worker's registration scope.<br />If an `onActionClick` item does not define a `url`, then the service worker's registration scope is used. ### Actions Actions offer a way to customize how the user can interact with a notification. Using the `actions` property, you can define a set of available actions. Each action is represented as an action button that the user can click to interact with the notification. In addition, using the `onActionClick` property on the `data` object, you can tie each action to an operation to be performed when the corresponding action button is clicked: <docs-code language="typescript"> { "notification": { "title": "New Notification!", "actions": [ {"action": "foo", "title": "Open new tab"}, {"action": "bar", "title": "Focus last"}, {"action": "baz", "title": "Navigate last"}, {"action": "qux", "title": "Send request in the background"}, {"action": "other", "title": "Just notify existing clients"} ], "data": { "onActionClick": { "default": {"operation": "openWindow"}, "foo": {"operation": "openWindow", "url": "/absolute/path"}, "bar": {"operation": "focusLastFocusedOrOpen", "url": "relative/path"}, "baz": {"operation": "navigateLastFocusedOrOpen", "url": "https://other.domain.com/"}, "qux": {"operation": "sendRequest", "url": "https://yet.another.domain.com/"} } } } } </docs-code> IMPORTANT: If an action does not have a corresponding `onActionClick` entry, then the notification is closed and `SwPush.notificationClicks` is notified on existing clients. ## More on Angular service workers You might also be interested in the following: <docs-pill-row> <docs-pill href="ecosystem/service-workers/communications" title="Communicating with the Service Worker"/> <docs-pill href="ecosystem/service-workers/devops" title="Service Worker devops"/> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 4545, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/push-notifications.md" }
angular/adev/src/content/ecosystem/service-workers/overview.md_0_8252
# Angular service worker overview Service workers augment the traditional web deployment model and empower applications to deliver a user experience with the reliability and performance on par with code that is written to run on your operating system and hardware. Adding a service worker to an Angular application is one of the steps for turning an application into a [Progressive Web App](https://web.dev/progressive-web-apps/) (also known as a PWA). At its simplest, a service worker is a script that runs in the web browser and manages caching for an application. Service workers function as a network proxy. They intercept all outgoing HTTP requests made by the application and can choose how to respond to them. For example, they can query a local cache and deliver a cached response if one is available. Proxying isn't limited to requests made through programmatic APIs, such as `fetch`; it also includes resources referenced in HTML and even the initial request to `index.html`. Service worker-based caching is thus completely programmable and doesn't rely on server-specified caching headers. Unlike the other scripts that make up an application, such as the Angular application bundle, the service worker is preserved after the user closes the tab. The next time that browser loads the application, the service worker loads first, and can intercept every request for resources to load the application. If the service worker is designed to do so, it can *completely satisfy the loading of the application, without the need for the network*. Even across a fast reliable network, round-trip delays can introduce significant latency when loading the application. Using a service worker to reduce dependency on the network can significantly improve the user experience. ## Service workers in Angular Angular applications, as single-page applications, are in a prime position to benefit from the advantages of service workers. Angular ships with a service worker implementation. Angular developers can take advantage of this service worker and benefit from the increased reliability and performance it provides, without needing to code against low-level APIs. Angular's service worker is designed to optimize the end user experience of using an application over a slow or unreliable network connection, while also minimizing the risks of serving outdated content. To achieve this, the Angular service worker follows these guidelines: * Caching an application is like installing a native application. The application is cached as one unit, and all files update together. * A running application continues to run with the same version of all files. It does not suddenly start receiving cached files from a newer version, which are likely incompatible. * When users refresh the application, they see the latest fully cached version. New tabs load the latest cached code. * Updates happen in the background, relatively quickly after changes are published. The previous version of the application is served until an update is installed and ready. * The service worker conserves bandwidth when possible. Resources are only downloaded if they've changed. To support these behaviors, the Angular service worker loads a *manifest* file from the server. The file, called `ngsw.json` (not to be confused with the [web app manifest](https://developer.mozilla.org/docs/Web/Manifest)), describes the resources to cache and includes hashes of every file's contents. When an update to the application is deployed, the contents of the manifest change, informing the service worker that a new version of the application should be downloaded and cached. This manifest is generated from a CLI-generated configuration file called `ngsw-config.json`. Installing the Angular service worker is as straightforward as [running an Angular CLI command](ecosystem/service-workers/getting-started#adding-a-service-worker-to-your-project). In addition to registering the Angular service worker with the browser, this also makes a few services available for injection which interact with the service worker and can be used to control it. For example, an application can ask to be notified when a new update becomes available, or an application can ask the service worker to check the server for available updates. ## Before you start To make use of all the features of Angular service workers, use the latest versions of Angular and the [Angular CLI](tools/cli). For service workers to be registered, the application must be accessed over HTTPS, not HTTP. Browsers ignore service workers on pages that are served over an insecure connection. The reason is that service workers are quite powerful, so extra care is needed to ensure the service worker script has not been tampered with. There is one exception to this rule: to make local development more straightforward, browsers do *not* require a secure connection when accessing an application on `localhost`. ### Browser support To benefit from the Angular service worker, your application must run in a web browser that supports service workers in general. Currently, service workers are supported in the latest versions of Chrome, Firefox, Edge, Safari, Opera, UC Browser (Android version) and Samsung Internet. Browsers like IE and Opera Mini do not support service workers. If the user is accessing your application with a browser that does not support service workers, the service worker is not registered and related behavior such as offline cache management and push notifications does not happen. More specifically: * The browser does not download the service worker script and the `ngsw.json` manifest file * Active attempts to interact with the service worker, such as calling `SwUpdate.checkForUpdate()`, return rejected promises * The observable events of related services, such as `SwUpdate.available`, are not triggered It is highly recommended that you ensure that your application works even without service worker support in the browser. Although an unsupported browser ignores service worker caching, it still reports errors if the application attempts to interact with the service worker. For example, calling `SwUpdate.checkForUpdate()` returns rejected promises. To avoid such an error, check whether the Angular service worker is enabled using `SwUpdate.isEnabled`. To learn more about other browsers that are service worker ready, see the [Can I Use](https://caniuse.com/#feat=serviceworkers) page and [MDN docs](https://developer.mozilla.org/docs/Web/API/Service_Worker_API). ## Related resources The rest of the articles in this section specifically address the Angular implementation of service workers. <docs-pill-row> <docs-pill href="ecosystem/service-workers/config" title="Configuration file"/> <docs-pill href="ecosystem/service-workers/communications" title="Communicating with the Service Worker"/> <docs-pill href="ecosystem/service-workers/push-notifications" title="Push notifications"/> <docs-pill href="ecosystem/service-workers/devops" title="Service Worker devops"/> <docs-pill href="ecosystem/service-workers/app-shell" title="App shell pattern"/> </docs-pill-row> For more information about service workers in general, see [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers). For more information about browser support, see the [browser support](https://developers.google.com/web/fundamentals/primers/service-workers/#browser_support) section of [Service Workers: an Introduction](https://developers.google.com/web/fundamentals/primers/service-workers), Jake Archibald's [Is Serviceworker ready?](https://jakearchibald.github.io/isserviceworkerready), and [Can I Use](https://caniuse.com/serviceworkers). For additional recommendations and examples, see: <docs-pill-row> <docs-pill href="https://web.dev/precaching-with-the-angular-service-worker" title="Precaching with Angular Service Worker"/> <docs-pill href="https://web.dev/creating-pwa-with-angular-cli" title="Creating a PWA with Angular CLI"/> </docs-pill-row> ## Next step To begin using Angular service workers, see [Getting Started with service workers](ecosystem/service-workers/getting-started).
{ "commit_id": "cb34e406ba", "end_byte": 8252, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/overview.md" }
angular/adev/src/content/ecosystem/service-workers/app-shell.md_0_2153
# App shell pattern The [App shell pattern](https://developer.chrome.com/blog/app-shell) is a way to render a portion of your application using a route at build time. It can improve the user experience by quickly launching a static rendered page (a skeleton common to all pages) while the browser downloads the full client version and switches to it automatically after the code loads. This gives users a meaningful first paint of your application that appears quickly because the browser can render the HTML and CSS without the need to initialize any JavaScript. <docs-workflow> <docs-step title="Prepare the application"> Do this with the following Angular CLI command: <docs-code language="shell"> ng new my-app --routing </docs-code> For an existing application, you have to manually add the `Router` and defining a `<router-outlet>` within your application. </docs-step> <docs-step title="Create the application shell"> Use the Angular CLI to automatically create the application shell. <docs-code language="shell"> ng generate app-shell </docs-code> For more information about this command, see [App shell command](cli/generate/app-shell). The command updates the application code and adds extra files to the project structure. <docs-code language="text"> src ├── app │ ├── app.config.server.ts # server application configuration │ └── app-shell # app-shell component │ ├── app-shell.component.html │ ├── app-shell.component.scss │ ├── app-shell.component.spec.ts │ └── app-shell.component.ts └── main.server.ts # main server application bootstrapping </docs-code> <docs-step title="Verify the application is built with the shell content"> <docs-code language="shell"> ng build --configuration=development </docs-code> Or to use the production configuration. <docs-code language="shell"> ng build </docs-code> To verify the build output, open <code class="no-auto-link">dist/my-app/browser/index.html</code>. Look for default text `app-shell works!` to show that the application shell route was rendered as part of the output. </docs-step> </docs-workflow>
{ "commit_id": "cb34e406ba", "end_byte": 2153, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/app-shell.md" }
angular/adev/src/content/ecosystem/service-workers/communications.md_0_7529
# Communicating with the Service Worker Enabling service worker support does more than just register the service worker; it also provides services you can use to interact with the service worker and control the caching of your application. ## `SwUpdate` service The `SwUpdate` service gives you access to events that indicate when the service worker discovers and installs an available update for your application. The `SwUpdate` service supports three separate operations: * Receiving notifications when an updated version is *detected* on the server, *installed and ready* to be used locally or when an *installation fails*. * Asking the service worker to check the server for new updates. * Asking the service worker to activate the latest version of the application for the current tab. ### Version updates The `versionUpdates` is an `Observable` property of `SwUpdate` and emits four event types: | Event types | Details | |:--- |:--- | | `VersionDetectedEvent` | Emitted when the service worker has detected a new version of the app on the server and is about to start downloading it. | | `NoNewVersionDetectedEvent` | Emitted when the service worker has checked the version of the app on the server and did not find a new version. | | `VersionReadyEvent` | Emitted when a new version of the app is available to be activated by clients. It may be used to notify the user of an available update or prompt them to refresh the page. | | `VersionInstallationFailedEvent` | Emitted when the installation of a new version failed. It may be used for logging/monitoring purposes. | <docs-code header="log-update.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/log-update.service.ts" visibleRegion="sw-update"/> ### Checking for updates It's possible to ask the service worker to check if any updates have been deployed to the server. The service worker checks for updates during initialization and on each navigation request —that is, when the user navigates from a different address to your application. However, you might choose to manually check for updates if you have a site that changes frequently or want updates to happen on a schedule. Do this with the `checkForUpdate()` method: <docs-code header="check-for-update.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/check-for-update.service.ts"/> This method returns a `Promise<boolean>` which indicates if an update is available for activation. The check might fail, which will cause a rejection of the `Promise`. <docs-callout important title="Stabilization and service worker registration"> In order to avoid negatively affecting the initial rendering of the page, by default the Angular service worker service waits for up to 30 seconds for the application to stabilize before registering the ServiceWorker script. Constantly polling for updates, for example, with [setInterval()](https://developer.mozilla.org/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) or RxJS' [interval()](https://rxjs.dev/api/index/function/interval), prevents the application from stabilizing and the ServiceWorker script is not registered with the browser until the 30 seconds upper limit is reached. This is true for any kind of polling done by your application. Check the [isStable](api/core/ApplicationRef#isStable) documentation for more information. Avoid that delay by waiting for the application to stabilize first, before starting to poll for updates, as shown in the preceding example. Alternatively, you might want to define a different [registration strategy](api/service-worker/SwRegistrationOptions#registrationStrategy) for the ServiceWorker. </docs-callout> ### Updating to the latest version You can update an existing tab to the latest version by reloading the page as soon as a new version is ready. To avoid disrupting the user's progress, it is generally a good idea to prompt the user and let them confirm that it is OK to reload the page and update to the latest version: <docs-code header="prompt-update.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/prompt-update.service.ts" visibleRegion="sw-version-ready"/> <docs-callout important title="Safety of updating without reloading"> Calling `activateUpdate()` updates a tab to the latest version without reloading the page, but this could break the application. Updating without reloading can create a version mismatch between the application shell and other page resources, such as lazy-loaded chunks, whose filenames may change between versions. You should only use `activateUpdate()`, if you are certain it is safe for your specific use case. </docs-callout> ### Handling an unrecoverable state In some cases, the version of the application used by the service worker to serve a client might be in a broken state that cannot be recovered from without a full page reload. For example, imagine the following scenario: 1. A user opens the application for the first time and the service worker caches the latest version of the application. Assume the application's cached assets include `index.html`, `main.<main-hash-1>.js` and `lazy-chunk.<lazy-hash-1>.js`. 1. The user closes the application and does not open it for a while. 1. After some time, a new version of the application is deployed to the server. This newer version includes the files `index.html`, `main.<main-hash-2>.js` and `lazy-chunk.<lazy-hash-2>.js`. IMPORTANT: The hashes are different now, because the content of the files changed. The old version is no longer available on the server. 1. In the meantime, the user's browser decides to evict `lazy-chunk.<lazy-hash-1>.js` from its cache. Browsers might decide to evict specific (or all) resources from a cache in order to reclaim disk space. 1. The user opens the application again. The service worker serves the latest version known to it at this point, namely the old version (`index.html` and `main.<main-hash-1>.js`). 1. At some later point, the application requests the lazy bundle, `lazy-chunk.<lazy-hash-1>.js`. 1. The service worker is unable to find the asset in the cache (remember that the browser evicted it). Nor is it able to retrieve it from the server (because the server now only has `lazy-chunk.<lazy-hash-2>.js` from the newer version). In the preceding scenario, the service worker is not able to serve an asset that would normally be cached. That particular application version is broken and there is no way to fix the state of the client without reloading the page. In such cases, the service worker notifies the client by sending an `UnrecoverableStateEvent` event. Subscribe to `SwUpdate#unrecoverable` to be notified and handle these errors. <docs-code header="handle-unrecoverable-state.service.ts" path="adev/src/content/examples/service-worker-getting-started/src/app/handle-unrecoverable-state.service.ts" visibleRegion="sw-unrecoverable-state"/> ## More on Angular service workers You might also be interested in the following: <docs-pill-row> <docs-pill href="ecosystem/service-workers/push-notifications" title="Push notifications"/> <docs-pill href="ecosystem/service-workers/devops" title="Service Worker devops"/> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 7529, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/communications.md" }
angular/adev/src/content/ecosystem/service-workers/getting-started.md_0_6783
# Getting started with service workers This document explains how to enable Angular service worker support in projects that you created with the [Angular CLI](tools/cli). It then uses an example to show you a service worker in action, demonstrating loading and basic caching. ## Adding a service worker to your project To set up the Angular service worker in your project, run the following CLI command: <docs-code language="shell"> ng add @angular/pwa </docs-code> The CLI configures your application to use service workers with the following actions: 1. Adds the `@angular/service-worker` package to your project. 1. Enables service worker build support in the CLI. 1. Imports and registers the service worker with the application's root providers. 1. Updates the `index.html` file: * Includes a link to add the `manifest.webmanifest` file * Adds a meta tag for `theme-color` 1. Installs icon files to support the installed Progressive Web App (PWA). 1. Creates the service worker configuration file called [`ngsw-config.json`](ecosystem/service-workers/config), which specifies the caching behaviors and other settings. Now, build the project: <docs-code language="shell"> ng build </docs-code> The CLI project is now set up to use the Angular service worker. ## Service worker in action: a tour This section demonstrates a service worker in action, using an example application. ### Initial load With the server running on port `8080`, point your browser at `http://localhost:8080`. Your application should load normally. Tip: When testing Angular service workers, it's a good idea to use an incognito or private window in your browser to ensure the service worker doesn't end up reading from a previous leftover state, which can cause unexpected behavior. HELPFUL: If you are not using HTTPS, the service worker will only be registered when accessing the application on `localhost`. ### Simulating a network issue To simulate a network issue, disable network interaction for your application. In Chrome: 1. Select **Tools** > **Developer Tools** (from the Chrome menu located in the top right corner). 1. Go to the **Network tab**. 1. Select **Offline** in the **Throttling** dropdown menu. <img alt="The offline option in the Network tab is selected" src="assets/images/guide/service-worker/offline-option.png"> Now the application has no access to network interaction. For applications that do not use the Angular service worker, refreshing now would display Chrome's Internet disconnected page that says "There is no Internet connection". With the addition of an Angular service worker, the application behavior changes. On a refresh, the page loads normally. Look at the Network tab to verify that the service worker is active. <img alt="Requests are marked as from ServiceWorker" src="assets/images/guide/service-worker/sw-active.png"> HELPFUL: Under the "Size" column, the requests state is `(ServiceWorker)`. This means that the resources are not being loaded from the network. Instead, they are being loaded from the service worker's cache. ### What's being cached? Notice that all of the files the browser needs to render this application are cached. The `ngsw-config.json` boilerplate configuration is set up to cache the specific resources used by the CLI: * `index.html` * `favicon.ico` * Build artifacts (JS and CSS bundles) * Anything under `assets` * Images and fonts directly under the configured `outputPath` (by default `./dist/<project-name>/`) or `resourcesOutputPath`. See the documentation for `ng build` for more information about these options. IMPORTANT: The generated `ngsw-config.json` includes a limited list of cacheable fonts and images extensions. In some cases, you might want to modify the glob pattern to suit your needs. IMPORTANT: If `resourcesOutputPath` or `assets` paths are modified after the generation of configuration file, you need to change the paths manually in `ngsw-config.json`. ### Making changes to your application Now that you've seen how service workers cache your application, the next step is understanding how updates work. Make a change to the application, and watch the service worker install the update: 1. If you're testing in an incognito window, open a second blank tab. This keeps the incognito and the cache state alive during your test. 1. Close the application tab, but not the window. This should also close the Developer Tools. 1. Shut down `http-server` (Ctrl-c). 1. Open `src/app/app.component.html` for editing. 1. Change the text `Welcome to {{title}}!` to `Bienvenue à {{title}}!`. 1. Build and run the server again: <docs-code language="shell"> ng build npx http-server -p 8080 -c-1 dist/<project-name>/browser </docs-code> ### Updating your application in the browser Now look at how the browser and service worker handle the updated application. 1. Open [http://localhost:8080](http://localhost:8080) again in the same window. What happens? <img alt="It still says Welcome to Service Workers!" src="assets/images/guide/service-worker/welcome-msg-en.png"> What went wrong? _Nothing, actually!_ The Angular service worker is doing its job and serving the version of the application that it has **installed**, even though there is an update available. In the interest of speed, the service worker doesn't wait to check for updates before it serves the application that it has cached. Look at the `http-server` logs to see the service worker requesting `/ngsw.json`. <docs-code language="shell"> [2023-09-07T00:37:24.372Z] "GET /ngsw.json?ngsw-cache-bust=0.9365263935102124" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36" </docs-code> This is how the service worker checks for updates. 1. Refresh the page. <img alt="The text has changed to say Bienvenue à app!" src="assets/images/guide/service-worker/welcome-msg-fr.png"> The service worker installed the updated version of your application _in the background_, and the next time the page is loaded or reloaded, the service worker switches to the latest version. ## More on Angular service workers You might also be interested in the following: <docs-pill-row> <docs-pill href="ecosystem/service-workers/config" title="Configuration file"/> <docs-pill href="ecosystem/service-workers/communications" title="Communicating with the Service Worker"/> <docs-pill href="ecosystem/service-workers/push-notifications" title="Push notifications"/> <docs-pill href="ecosystem/service-workers/devops" title="Service Worker devops"/> <docs-pill href="ecosystem/service-workers/app-shell" title="App shell pattern"/> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 6783, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/getting-started.md" }
angular/adev/src/content/ecosystem/service-workers/config.md_0_8374
# Service Worker configuration file This topic describes the properties of the service worker configuration file. ## Modifying the configuration The `ngsw-config.json` JSON configuration file specifies which files and data URLs the Angular service worker should cache and how it should update the cached files and data. The [Angular CLI](tools/cli) processes this configuration file during `ng build`. All file paths must begin with `/`, which corresponds to the deployment directory — usually `dist/<project-name>` in CLI projects. Unless otherwise commented, patterns use a **limited*** glob format that internally will be converted into regex: | Glob formats | Details | |:--- |:--- | | `**` | Matches 0 or more path segments | | `*` | Matches 0 or more characters excluding `/` | | `?` | Matches exactly one character excluding `/` | | `!` prefix | Marks the pattern as being negative, meaning that only files that don't match the pattern are included | <docs-callout important title="Special characters need to be escaped"> Pay attention that some characters with a special meaning in a regular expression are not escaped and also the pattern is not wrapped in `^`/`$` in the internal glob to regex conversion. `$` is a special character in regex that matches the end of the string and will not be automatically escaped when converting the glob pattern to a regular expression. If you want to literally match the `$` character, you have to escape it yourself (with `\\$`). For example, the glob pattern `/foo/bar/$value` results in an unmatchable expression, because it is impossible to have a string that has any characters after it has ended. The pattern will not be automatically wrapped in `^` and `$` when converting it to a regular expression. Therefore, the patterns will partially match the request URLs. If you want your patterns to match the beginning and/or end of URLs, you can add `^`/`$` yourself. For example, the glob pattern `/foo/bar/*.js` will match both `.js` and `.json` files. If you want to only match `.js` files, use `/foo/bar/*.js$`. </docs-callout> Example patterns: | Patterns | Details | |:--- |:--- | | `/**/*.html` | Specifies all HTML files | | `/*.html` | Specifies only HTML files in the root | | `!/**/*.map` | Exclude all sourcemaps | ## Service worker configuration properties The following sections describe each property of the configuration file. ### `appData` This section enables you to pass any data you want that describes this particular version of the application. The `SwUpdate` service includes that data in the update notifications. Many applications use this section to provide additional information for the display of UI popups, notifying users of the available update. ### `index` Specifies the file that serves as the index page to satisfy navigation requests. Usually this is `/index.html`. ### `assetGroups` *Assets* are resources that are part of the application version that update along with the application. They can include resources loaded from the page's origin as well as third-party resources loaded from CDNs and other external URLs. As not all such external URLs might be known at build time, URL patterns can be matched. HELPFUL: For the service worker to handle resources that are loaded from different origins, make sure that [CORS](https://developer.mozilla.org/docs/Web/HTTP/CORS) is correctly configured on each origin's server. This field contains an array of asset groups, each of which defines a set of asset resources and the policy by which they are cached. <docs-code language="json"> { "assetGroups": [ { … }, { … } ] } </docs-code> HELPFUL: When the ServiceWorker handles a request, it checks asset groups in the order in which they appear in `ngsw-config.json`. The first asset group that matches the requested resource handles the request. It is recommended that you put the more specific asset groups higher in the list. For example, an asset group that matches `/foo.js` should appear before one that matches `*.js`. Each asset group specifies both a group of resources and a policy that governs them. This policy determines when the resources are fetched and what happens when changes are detected. Asset groups follow the Typescript interface shown here: <docs-code language="typescript"> interface AssetGroup { name: string; installMode?: 'prefetch' | 'lazy'; updateMode?: 'prefetch' | 'lazy'; resources: { files?: string[]; urls?: string[]; }; cacheQueryOptions?: { ignoreSearch?: boolean; }; } </docs-code> Each `AssetGroup` is defined by the following asset group properties. #### `name` A `name` is mandatory. It identifies this particular group of assets between versions of the configuration. #### `installMode` The `installMode` determines how these resources are initially cached. The `installMode` can be either of two values: | Values | Details | |:--- |:--- | | `prefetch` | Tells the Angular service worker to fetch every single listed resource while it's caching the current version of the application. This is bandwidth-intensive but ensures resources are available whenever they're requested, even if the browser is currently offline. | | `lazy` | Does not cache any of the resources up front. Instead, the Angular service worker only caches resources for which it receives requests. This is an on-demand caching mode. Resources that are never requested are not cached. This is useful for things like images at different resolutions, so the service worker only caches the correct assets for the particular screen and orientation. | Defaults to `prefetch`. #### `updateMode` For resources already in the cache, the `updateMode` determines the caching behavior when a new version of the application is discovered. Any resources in the group that have changed since the previous version are updated in accordance with `updateMode`. | Values | Details | |:--- |:--- | | `prefetch` | Tells the service worker to download and cache the changed resources immediately. | | `lazy` | Tells the service worker to not cache those resources. Instead, it treats them as unrequested and waits until they're requested again before updating them. An `updateMode` of `lazy` is only valid if the `installMode` is also `lazy`. | Defaults to the value `installMode` is set to. #### `resources` This section describes the resources to cache, broken up into the following groups: | Resource groups | Details | |:--- |:--- | | `files` | Lists patterns that match files in the distribution directory. These can be single files or glob-like patterns that match a number of files. | | `urls` | Includes both URLs and URL patterns that are matched at runtime. These resources are not fetched directly and do not have content hashes, but they are cached according to their HTTP headers. This is most useful for CDNs such as the Google Fonts service. <br /> *(Negative glob patterns are not supported and `?` will be matched literally; that is, it will not match any character other than `?`.)* | #### `cacheQueryOptions` These options are used to modify the matching behavior of requests. They are passed to the browsers `Cache#match` function. See [MDN](https://developer.mozilla.org/docs/Web/API/Cache/match) for details. Currently, only the following options are supported: | Options | Details | |:--- |:--- | | `ignoreSearch` | Ignore query parameters. Defaults to `false`. | ### `d
{ "commit_id": "cb34e406ba", "end_byte": 8374, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/config.md" }
angular/adev/src/content/ecosystem/service-workers/config.md_8374_16267
ataGroups` Unlike asset resources, data requests are not versioned along with the application. They're cached according to manually-configured policies that are more useful for situations such as API requests and other data dependencies. This field contains an array of data groups, each of which defines a set of data resources and the policy by which they are cached. <docs-code language="json"> { "dataGroups": [ { … }, { … } ] } </docs-code> HELPFUL: When the ServiceWorker handles a request, it checks data groups in the order in which they appear in `ngsw-config.json`. The first data group that matches the requested resource handles the request. It is recommended that you put the more specific data groups higher in the list. For example, a data group that matches `/api/foo.json` should appear before one that matches `/api/*.json`. Data groups follow this Typescript interface: <docs-code language="typescript"> export interface DataGroup { name: string; urls: string[]; version?: number; cacheConfig: { maxSize: number; maxAge: string; timeout?: string; refreshAhead?: string; strategy?: 'freshness' | 'performance'; }; cacheQueryOptions?: { ignoreSearch?: boolean; }; } </docs-code> Each `DataGroup` is defined by the following data group properties. #### `name` Similar to `assetGroups`, every data group has a `name` which uniquely identifies it. #### `urls` A list of URL patterns. URLs that match these patterns are cached according to this data group's policy. Only non-mutating requests (GET and HEAD) are cached. * Negative glob patterns are not supported * `?` is matched literally; that is, it matches *only* the character `?` #### `version` Occasionally APIs change formats in a way that is not backward-compatible. A new version of the application might not be compatible with the old API format and thus might not be compatible with existing cached resources from that API. `version` provides a mechanism to indicate that the resources being cached have been updated in a backwards-incompatible way, and that the old cache entries —those from previous versions— should be discarded. `version` is an integer field and defaults to `1`. #### `cacheConfig` The following properties define the policy by which matching requests are cached. ##### `maxSize` The maximum number of entries, or responses, in the cache. CRITICAL: Open-ended caches can grow in unbounded ways and eventually exceed storage quotas, resulting in eviction. ##### `maxAge` The `maxAge` parameter indicates how long responses are allowed to remain in the cache before being considered invalid and evicted. `maxAge` is a duration string, using the following unit suffixes: | Suffixes | Details | |:--- |:--- | | `d` | Days | | `h` | Hours | | `m` | Minutes | | `s` | Seconds | | `u` | Milliseconds | For example, the string `3d12h` caches content for up to three and a half days. ##### `timeout` This duration string specifies the network timeout. The network timeout is how long the Angular service worker waits for the network to respond before using a cached response, if configured to do so. `timeout` is a duration string, using the following unit suffixes: | Suffixes | Details | |:--- |:--- | | `d` | Days | | `h` | Hours | | `m` | Minutes | | `s` | Seconds | | `u` | Milliseconds | For example, the string `5s30u` translates to five seconds and 30 milliseconds of network timeout. ##### `refreshAhead` This duration string specifies the time ahead of the expiration of a cached resource when the Angular service worker should proactively attempt to refresh the resource from the network. The `refreshAhead` duration is an optional configuration that determines how much time before the expiration of a cached response the service worker should initiate a request to refresh the resource from the network. | Suffixes | Details | |:--- |:--- | | `d` | Days | | `h` | Hours | | `m` | Minutes | | `s` | Seconds | | `u` | Milliseconds | For example, the string `1h30m` translates to one hour and 30 minutes ahead of the expiration time. ##### `strategy` The Angular service worker can use either of two caching strategies for data resources. | Caching strategies | Details | |:--- |:--- | | `performance` | The default, optimizes for responses that are as fast as possible. If a resource exists in the cache, the cached version is used, and no network request is made. This allows for some staleness, depending on the `maxAge`, in exchange for better performance. This is suitable for resources that don't change often; for example, user avatar images. | | `freshness` | Optimizes for currency of data, preferentially fetching requested data from the network. Only if the network times out, according to `timeout`, does the request fall back to the cache. This is useful for resources that change frequently; for example, account balances. | HELPFUL: You can also emulate a third strategy, [staleWhileRevalidate](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#stale-while-revalidate), which returns cached data if it is available, but also fetches fresh data from the network in the background for next time. To use this strategy set `strategy` to `freshness` and `timeout` to `0u` in `cacheConfig`. This essentially does the following: 1. Try to fetch from the network first. 2. If the network request does not complete immediately, that is after a timeout of 0&nbsp;ms, ignore the cache age and fall back to the cached value. 3. Once the network request completes, update the cache for future requests. 4. If the resource does not exist in the cache, wait for the network request anyway. ##### `cacheOpaqueResponses` Whether the Angular service worker should cache opaque responses or not. If not specified, the default value depends on the data group's configured strategy: | Strategies | Details | |:--- |:--- | | Groups with the `freshness` strategy | The default value is `true` and the service worker caches opaque responses. These groups will request the data every time and only fall back to the cached response when offline or on a slow network. Therefore, it doesn't matter if the service worker caches an error response. | | Groups with the `performance` strategy | The default value is `false` and the service worker doesn't cache opaque responses. These groups would continue to return a cached response until `maxAge` expires, even if the error was due to a temporary network or server issue. Therefore, it would be problematic for the service worker to cache an error response. | <docs-callout title="Comment on opaque responses"> In case you are not familiar, an [opaque response](https://fetch.spec.whatwg.org#concept-filtered-response-opaque) is a special type of response returned when requesting a resource that is on a different origin which doesn't return CORS headers. One of the characteristics of an opaque response is that the service worker is not allowed to read its status, meaning it can't check if the request was successful or not. See [Introduction to `fetch()`](https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types) for more details. If you are not able to implement CORS — for example, if you don't control the origin — prefer using the `freshness` strategy for resources that result in opaque responses. </docs-callout> #### `cacheQueryOptions` See [assetGroups](#assetgroups) for details. ### `navigationUrl
{ "commit_id": "cb34e406ba", "end_byte": 16267, "start_byte": 8374, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/config.md" }
angular/adev/src/content/ecosystem/service-workers/config.md_16267_19806
s` This optional section enables you to specify a custom list of URLs that will be redirected to the index file. #### Handling navigation requests The ServiceWorker redirects navigation requests that don't match any `asset` or `data` group to the specified [index file](#index). A request is considered to be a navigation request if: * Its [method](https://developer.mozilla.org/docs/Web/API/Request/method) is `GET` * Its [mode](https://developer.mozilla.org/docs/Web/API/Request/mode) is `navigation` * It accepts a `text/html` response as determined by the value of the `Accept` header * Its URL matches the following criteria: * The URL must not contain a file extension (that is, a `.`) in the last path segment * The URL must not contain `__` HELPFUL: To configure whether navigation requests are sent through to the network or not, see the [navigationRequestStrategy](#navigationrequeststrategy) section and [applicationMaxAge](#application-max-age) sections. #### Matching navigation request URLs While these default criteria are fine in most cases, it is sometimes desirable to configure different rules. For example, you might want to ignore specific routes, such as those that are not part of the Angular app, and pass them through to the server. This field contains an array of URLs and [glob-like](#modifying-the-configuration) URL patterns that are matched at runtime. It can contain both negative patterns (that is, patterns starting with `!`) and non-negative patterns and URLs. Only requests whose URLs match *any* of the non-negative URLs/patterns and *none* of the negative ones are considered navigation requests. The URL query is ignored when matching. If the field is omitted, it defaults to: <docs-code language="typescript"> [ '/**', // Include all URLs. '!/**/*.*', // Exclude URLs to files. '!/**/****', // Exclude URLs containing `**` in the last segment. '!/**/****/**', // Exclude URLs containing `**` in any other segment. ] </docs-code> ### `navigationRequestStrategy` This optional property enables you to configure how the service worker handles navigation requests: <docs-code language="json"> { "navigationRequestStrategy": "freshness" } </docs-code> | Possible values | Details | |:--- |:--- | | `'performance'` | The default setting. Serves the specified [index file](#index-file), which is typically cached. | | `'freshness'` | Passes the requests through to the network and falls back to the `performance` behavior when offline. This value is useful when the server redirects the navigation requests elsewhere using a `3xx` HTTP redirect status code. Reasons for using this value include: <ul> <li> Redirecting to an authentication website when authentication is not handled by the application </li> <li> Redirecting specific URLs to avoid breaking existing links/bookmarks after a website redesign </li> <li> Redirecting to a different website, such as a server-status page, while a page is temporarily down </li> </ul> | IMPORTANT: The `freshness` strategy usually results in more requests sent to the server, which can increase response latency. It is recommended that you use the default performance strategy whenever possible. ### `applicationMaxAge` This optional property enables you to configure how long the service worker will cache any requests. Within the `maxAge`, files will be served from cache. Beyond it, all requests will only be served from the network, including asset and data requests.
{ "commit_id": "cb34e406ba", "end_byte": 19806, "start_byte": 16267, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/config.md" }
angular/adev/src/content/ecosystem/service-workers/BUILD.bazel_0_638
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "service-workers", srcs = glob([ "*.md", ]), data = [ "//adev/src/content/examples/service-worker-getting-started:src/app/check-for-update.service.ts", "//adev/src/content/examples/service-worker-getting-started:src/app/handle-unrecoverable-state.service.ts", "//adev/src/content/examples/service-worker-getting-started:src/app/log-update.service.ts", "//adev/src/content/examples/service-worker-getting-started:src/app/prompt-update.service.ts", ], visibility = ["//adev:__subpackages__"], )
{ "commit_id": "cb34e406ba", "end_byte": 638, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/BUILD.bazel" }
angular/adev/src/content/ecosystem/service-workers/devops.md_0_9737
# Service worker devops This page is a reference for deploying and supporting production applications that use the Angular service worker. It explains how the Angular service worker fits into the larger production environment, the service worker's behavior under various conditions, and available resources and fail-safes. ## Service worker and caching of application resources Imagine the Angular service worker as a forward cache or a Content Delivery Network (CDN) edge that is installed in the end user's web browser. The service worker responds to requests made by the Angular application for resources or data from a local cache, without needing to wait for the network. Like any cache, it has rules for how content is expired and updated. ### Application versions In the context of an Angular service worker, a "version" is a collection of resources that represent a specific build of the Angular application. Whenever a new build of the application is deployed, the service worker treats that build as a new version of the application. This is true even if only a single file is updated. At any given time, the service worker might have multiple versions of the application in its cache and it might be serving them simultaneously. For more information, see the [Application tabs](#application-tabs) section. To preserve application integrity, the Angular service worker groups all files into a version together. The files grouped into a version usually include HTML, JS, and CSS files. Grouping of these files is essential for integrity because HTML, JS, and CSS files frequently refer to each other and depend on specific content. For example, an `index.html` file might have a `<script>` tag that references `bundle.js` and it might attempt to call a function `startApp()` from within that script. Any time this version of `index.html` is served, the corresponding `bundle.js` must be served with it. For example, assume that the `startApp()` function is renamed to `runApp()` in both files. In this scenario, it is not valid to serve the old `index.html`, which calls `startApp()`, along with the new bundle, which defines `runApp()`. This file integrity is especially important when lazy loading. A JS bundle might reference many lazy chunks, and the filenames of the lazy chunks are unique to the particular build of the application. If a running application at version `X` attempts to load a lazy chunk, but the server has already updated to version `X + 1`, the lazy loading operation fails. The version identifier of the application is determined by the contents of all resources, and it changes if any of them change. In practice, the version is determined by the contents of the `ngsw.json` file, which includes hashes for all known content. If any of the cached files change, the file's hash changes in `ngsw.json`. This change causes the Angular service worker to treat the active set of files as a new version. HELPFUL: The build process creates the manifest file, `ngsw.json`, using information from `ngsw-config.json`. With the versioning behavior of the Angular service worker, an application server can ensure that the Angular application always has a consistent set of files. #### Update checks Every time the user opens or refreshes the application, the Angular service worker checks for updates to the application by looking for updates to the `ngsw.json` manifest. If an update is found, it is downloaded and cached automatically, and is served the next time the application is loaded. ### Resource integrity One of the potential side effects of long caching is inadvertently caching a resource that's not valid. In a normal HTTP cache, a hard refresh or the cache expiring limits the negative effects of caching a file that's not valid. A service worker ignores such constraints and effectively long-caches the entire application. It's important that the service worker gets the correct content, so it keeps hashes of the resources to maintain their integrity. #### Hashed content To ensure resource integrity, the Angular service worker validates the hashes of all resources for which it has a hash. For an application created with the [Angular CLI](tools/cli), this is everything in the `dist` directory covered by the user's `src/ngsw-config.json` configuration. If a particular file fails validation, the Angular service worker attempts to re-fetch the content using a "cache-busting" URL parameter to prevent browser or intermediate caching. If that content also fails validation, the service worker considers the entire version of the application to not be valid and stops serving the application. If necessary, the service worker enters a safe mode where requests fall back on the network. The service worker doesn't use its cache if there's a high risk of serving content that is broken, outdated, or not valid. Hash mismatches can occur for a variety of reasons: * Caching layers between the origin server and the end user could serve stale content * A non-atomic deployment could result in the Angular service worker having visibility of partially updated content * Errors during the build process could result in updated resources without `ngsw.json` being updated. The reverse could also happen resulting in an updated `ngsw.json` without updated resources. #### Unhashed content The only resources that have hashes in the `ngsw.json` manifest are resources that were present in the `dist` directory at the time the manifest was built. Other resources, especially those loaded from CDNs, have content that is unknown at build time or are updated more frequently than the application is deployed. If the Angular service worker does not have a hash to verify a resource is valid, it still caches its contents. At the same time, it honors the HTTP caching headers by using a policy of *stale while revalidate*. The Angular service worker continues to serve a resource even after its HTTP caching headers indicate that it is no longer valid. At the same time, it attempts to refresh the expired resource in the background. This way, broken unhashed resources do not remain in the cache beyond their configured lifetimes. ### Application tabs It can be problematic for an application if the version of resources it's receiving changes suddenly or without warning. See the [Application versions](#application-versions) section for a description of such issues. The Angular service worker provides a guarantee: a running application continues to run the same version of the application. If another instance of the application is opened in a new web browser tab, then the most current version of the application is served. As a result, that new tab can be running a different version of the application than the original tab. IMPORTANT: This guarantee is **stronger** than that provided by the normal web deployment model. Without a service worker, there is no guarantee that lazily loaded code is from the same version as the application's initial code. The Angular service worker might change the version of a running application under error conditions such as: * The current version becomes non-valid due to a failed hash. * An unrelated error causes the service worker to enter safe mode and deactivates it temporarily. The Angular service worker cleans up application versions when no tab is using them. Other reasons the Angular service worker might change the version of a running application are normal events: * The page is reloaded/refreshed. * The page requests an update be immediately activated using the `SwUpdate` service. ### Service worker updates The Angular service worker is a small script that runs in web browsers. From time to time, the service worker is updated with bug fixes and feature improvements. The Angular service worker is downloaded when the application is first opened and when the application is accessed after a period of inactivity. If the service worker changes, it's updated in the background. Most updates to the Angular service worker are transparent to the application. The old caches are still valid and content is still served normally. Occasionally, a bug fix or feature in the Angular service worker might require the invalidation of old caches. In this case, the service worker transparently refreshes the application from the network. ### Bypassing the service worker In some cases, you might want to bypass the service worker entirely and let the browser handle the request. An example is when you rely on a feature that is currently not supported in service workers, such as [reporting progress on uploaded files](https://github.com/w3c/ServiceWorker/issues/1141). To bypass the service worker, set `ngsw-bypass` as a request header, or as a query parameter. The value of the header or query parameter is ignored and can be empty or omitted. ### Service worker requests when the server can't be reached The service worker processes all requests unless the [service worker is explicitly bypassed](#bypassing-the-service-worker). The service worker either returns a cached response or sends the request to the server, depending on the state and configuration of the cache. The service worker only caches responses to non-mutating requests, such as `GET` and `HEAD`. If the service worker receives an error from the server or it doesn't receive a response, it returns an error status that indicates the result of the call. For example, if the service worker doesn't receive a response, it creates a [504 Gateway Timeout](https://developer.mozilla.org/docs/Web/HTTP/Status/504) status to return. The `504` status in this example could be returned because the server is offline or the client is disconnected.
{ "commit_id": "cb34e406ba", "end_byte": 9737, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/devops.md" }
angular/adev/src/content/ecosystem/service-workers/devops.md_9737_18133
## Debugging the Angular service worker Occasionally, it might be necessary to examine the Angular service worker in a running state to investigate issues or whether it's operating as designed. Browsers provide built-in tools for debugging service workers and the Angular service worker itself includes useful debugging features. ### Locating and analyzing debugging information The Angular service worker exposes debugging information under the `ngsw/` virtual directory. Currently, the single exposed URL is `ngsw/state`. Here is an example of this debug page's contents: <docs-code hideCopy language="shell"> NGSW Debug Info: Driver version: 13.3.7 Driver state: NORMAL ((nominal)) Latest manifest hash: eea7f5f464f90789b621170af5a569d6be077e5c Last update check: never === Version eea7f5f464f90789b621170af5a569d6be077e5c === Clients: 7b79a015-69af-4d3d-9ae6-95ba90c79486, 5bc08295-aaf2-42f3-a4cc-9e4ef9100f65 === Idle Task Queue === Last update tick: 1s496u Last update run: never Task queue: * init post-load (update, cleanup) Debug log: </docs-code> #### Driver state The first line indicates the driver state: <docs-code hideCopy language="shell"> Driver state: NORMAL ((nominal)) </docs-code> `NORMAL` indicates that the service worker is operating normally and is not in a degraded state. There are two possible degraded states: | Degraded states | Details | |:--- |:--- | | `EXISTING_CLIENTS_ONLY` | The service worker does not have a clean copy of the latest known version of the application. Older cached versions are safe to use, so existing tabs continue to run from cache, but new loads of the application will be served from the network. The service worker will try to recover from this state when a new version of the application is detected and installed. This happens when a new `ngsw.json` is available. | | `SAFE_MODE` | The service worker cannot guarantee the safety of using cached data. Either an unexpected error occurred or all cached versions are invalid. All traffic will be served from the network, running as little service worker code as possible. | In both cases, the parenthetical annotation provides the error that caused the service worker to enter the degraded state. Both states are temporary; they are saved only for the lifetime of the [ServiceWorker instance](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope). The browser sometimes terminates an idle service worker to conserve memory and processor power, and creates a new service worker instance in response to network events. The new instance starts in the `NORMAL` mode, regardless of the state of the previous instance. #### Latest manifest hash <docs-code hideCopy language="shell"> Latest manifest hash: eea7f5f464f90789b621170af5a569d6be077e5c </docs-code> This is the SHA1 hash of the most up-to-date version of the application that the service worker knows about. #### Last update check <docs-code hideCopy language="shell"> Last update check: never </docs-code> This indicates the last time the service worker checked for a new version, or update, of the application. `never` indicates that the service worker has never checked for an update. In this example debug file, the update check is currently scheduled, as explained the next section. #### Version <docs-code hideCopy language="shell"> === Version eea7f5f464f90789b621170af5a569d6be077e5c === Clients: 7b79a015-69af-4d3d-9ae6-95ba90c79486, 5bc08295-aaf2-42f3-a4cc-9e4ef9100f65 </docs-code> In this example, the service worker has one version of the application cached and being used to serve two different tabs. HELPFUL: This version hash is the "latest manifest hash" listed above. Both clients are on the latest version. Each client is listed by its ID from the `Clients` API in the browser. #### Idle task queue <docs-code hideCopy language="shell"> === Idle Task Queue === Last update tick: 1s496u Last update run: never Task queue: * init post-load (update, cleanup) </docs-code> The Idle Task Queue is the queue of all pending tasks that happen in the background in the service worker. If there are any tasks in the queue, they are listed with a description. In this example, the service worker has one such task scheduled, a post-initialization operation involving an update check and cleanup of stale caches. The last update tick/run counters give the time since specific events happened related to the idle queue. The "Last update run" counter shows the last time idle tasks were actually executed. "Last update tick" shows the time since the last event after which the queue might be processed. #### Debug log <docs-code hideCopy language="shell"> Debug log: </docs-code> Errors that occur within the service worker are logged here. ### Developer tools Browsers such as Chrome provide developer tools for interacting with service workers. Such tools can be powerful when used properly, but there are a few things to keep in mind. * When using developer tools, the service worker is kept running in the background and never restarts. This can cause behavior with Dev Tools open to differ from behavior a user might experience. * If you look in the Cache Storage viewer, the cache is frequently out of date. Right-click the Cache Storage title and refresh the caches. * Stopping and starting the service worker in the Service Worker pane checks for updates ## Service worker safety Bugs or broken configurations could cause the Angular service worker to act in unexpected ways. If this happens, the Angular service worker contains several failsafe mechanisms in case an administrator needs to deactivate the service worker quickly. ### Fail-safe To deactivate the service worker, rename the `ngsw.json` file or delete it. When the service worker's request for `ngsw.json` returns a `404`, then the service worker removes all its caches and de-registers itself, essentially self-destructing. ### Safety worker <!-- vale Angular.Google_Acronyms = NO --> A small script, `safety-worker.js`, is also included in the `@angular/service-worker` NPM package. When loaded, it un-registers itself from the browser and removes the service worker caches. This script can be used as a last resort to get rid of unwanted service workers already installed on client pages. <!-- vale Angular.Google_Acronyms = YES --> CRITICAL: You cannot register this worker directly, as old clients with cached state might not see a new `index.html` which installs the different worker script. Instead, you must serve the contents of `safety-worker.js` at the URL of the Service Worker script you are trying to unregister. You must continue to do so until you are certain all users have successfully unregistered the old worker. For most sites, this means that you should serve the safety worker at the old Service Worker URL forever. This script can be used to deactivate `@angular/service-worker` and remove the corresponding caches. It also removes any other Service Workers which might have been served in the past on your site. ### Changing your application's location IMPORTANT: Service workers don't work behind redirect. You might have already encountered the error `The script resource is behind a redirect, which is disallowed`. This can be a problem if you have to change your application's location. If you set up a redirect from the old location, such as `example.com`, to the new location, `www.example.com` in this example, the worker stops working. Also, the redirect won't even trigger for users who are loading the site entirely from Service Worker. The old worker, which was registered at `example.com`, tries to update and sends a request to the old location `example.com`. This request is redirected to the new location `www.example.com` and creates the error: `The script resource is behind a redirect, which is disallowed`. To remedy this, you might need to deactivate the old worker using one of the preceding techniques: [Fail-safe](#fail-safe) or [Safety Worker](#safety-worker). ## More on Angular service workers You might also be interested in the following: <docs-pill-row> <docs-pill href="ecosystem/service-workers/config" title="Configuration file"/> <docs-pill href="ecosystem/service-workers/communications" title="Communicating with the Service Worker"/> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 18133, "start_byte": 9737, "url": "https://github.com/angular/angular/blob/main/adev/src/content/ecosystem/service-workers/devops.md" }
angular/adev/src/content/tools/devtools.md_0_7623
# DevTools Overview Angular DevTools is a browser extension that provides debugging and profiling capabilities for Angular applications. <docs-video src="https://www.youtube.com/embed/bavWOHZM6zE"/> Install Angular DevTools from the [Chrome Web Store](https://chrome.google.com/webstore/detail/angular-developer-tools/ienfalfjdbdpebioblfackkekamfmbnh) or from [Firefox Addons](https://addons.mozilla.org/firefox/addon/angular-devtools/). You can open Chrome or Firefox DevTools on any web page by pressing <kbd>F12</kbd> or <kbd><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>I</kbd></kbd> (Windows or Linux) and <kbd><kbd>Fn</kbd>+<kbd>F12</kbd></kbd> or <kbd><kbd>Cmd</kbd>+<kbd>Option</kbd>+<kbd>I</kbd></kbd> (Mac). Once browser DevTools is open and Angular DevTools is installed, you can find it under the "Angular" tab. HELPFUL: Chrome's new tab page does not run installed extensions, so the Angular tab will not appear in DevTools. Visit any other page to see it. <img src="assets/images/guide/devtools/devtools.png" alt="An overview of Angular DevTools showing a tree of components for an application."> ## Open your application When you open the extension, you'll see two additional tabs: | Tabs | Details | |:--- |:--- | | [Components](tools/devtools#debug-your-application) | Lets you explore the components and directives in your application and preview or edit their state. | | [Profiler](tools/devtools#profile-your-application) | Lets you profile your application and understand what the performance bottleneck is during change detection execution. | <img src="assets/images/guide/devtools/devtools-tabs.png" alt="A screenshot of the top of Angular DevTools illustrating two tabs in the upper-left corner, one labeled 'Components' and another labeled 'Profiler'."> In the top-right corner of Angular DevTools you'll find which version of Angular is running on the page as well as the latest commit hash for the extension. ### Angular application not detected If you see an error message "Angular application not detected" when opening Angular DevTools, this means it is not able to communicate with an Angular app on the page. The most common reason for this is because the web page you are inspecting does not contain an Angular application. Double check that you are inspecting the right web page and that the Angular app is running. ### We detected an application built with production configuration If you see an error message "We detected an application built with production configuration. Angular DevTools only supports development builds.", this means that an Angular application was found on the page, but it was compiled with production optimizations. When compiling for production, Angular CLI removes various debug features to minimize the amount of the JavaScript on the page to improve performance. This includes features needed to communicate with DevTools. To run DevTools, you need to compile your application with optimizations disabled. `ng serve` does this by default. If you need to debug a deployed application, disable optimizations in your build with the [`optimization` configuration option](reference/configs/workspace-config#optimization-configuration) (`{"optimization": false}`). ## Debug your application The **Components** tab lets you explore the structure of your application. You can visualize the component and directive instances in the DOM and inspect or modify their state. ### Explore the application structure The component tree displays a hierarchical relationship of the *components and directives* within your application. <img src="assets/images/guide/devtools/component-explorer.png" alt="A screenshot of the 'Components' tab showing a tree of Angular components and directives starting the root of the application."> Click the individual components or directives in the component explorer to select them and preview their properties. Angular DevTools displays properties and metadata on the right side of the component tree. To look up a component or directive by name use the search box above the component tree. <img src="assets/images/guide/devtools/search.png" alt="A screenshot of the 'Components' tab. The filter bar immediately underneath the tab is searching for 'todo' and all components with 'todo' in the name are highlighted in the tree. `app-todos` is currently selected and a sidebar to the right displays information about the component's properties. This includes a section of `@Output` fields and another section for other properties."> ### Navigate to the host node To go to the host element of a particular component or directive, double-click it in the component explorer. Angular DevTools will open the Elements tab in Chrome or the Inspector tab in Firefox, and select the associated DOM node. ### Navigate to source For components, Angular DevTools lets you navigate to the component definition in the Sources tab (Chrome) and Debugger tab (Firefox). After you select a particular component, click the icon at the top-right of the properties view: <img src="assets/images/guide/devtools/navigate-source.png" alt="A screenshot of the 'Components' tab. The properties view on the right is visible for a component and the mouse rests in the upper right corner of that view on top of a `<>` icon. An adjacent tooltip reads 'Open component source'."> ### Update property value Like browsers' DevTools, the properties view lets you edit the value of an input, output, or other properties. Right-click on the property value and if edit functionality is available for this value type, a text input will appear. Type the new value and press `Enter` to apply this value to the property. <img src="assets/images/guide/devtools/update-property.png" alt="A screenshot of the 'Components' tab with the properties view open for a component. An `@Input` named `todo` contains a `label` property which is currently selected and has been manually updated to the value 'Buy milk'."> ### Access selected component or directive in console As a shortcut in the console, Angular DevTools provides access to instances of recently selected components or directives. Type `$ng0` to get a reference to the instance of the currently selected component or directive, and type `$ng1` for the previously selected instance, `$ng2` for the instance selected before that, and so on. <img src="assets/images/guide/devtools/access-console.png" alt="A screenshot of the 'Components' tab with the browser console underneath. In the console, the user has typed three commands, `$ng0`, `$ng1`, and `$ng2` to view the three most recently selected elements. After each statement, the console prints a different component reference."> ### Select a directive or component Similar to browsers' DevTools, you can inspect the page to select a particular component or directive. Click the ***Inspect element*** icon in the top left corner within Angular DevTools and hover over a DOM element on the page. The extension recognizes the associated directives and/or components and lets you select the corresponding element in the Component tree. <img src="assets/images/guide/devtools/inspect-element.png" alt="A screenshot of the 'Components' tab with an Angular todo application visible. In the very top-left corner of Angular DevTools, an icon of a screen with a mouse icon inside it is selected. The mouse rests on a todo element in the Angular application UI. The element is highlighted with a `<TodoComponent>` label displayed in an adjacent tooltip.">
{ "commit_id": "cb34e406ba", "end_byte": 7623, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/devtools.md" }
angular/adev/src/content/tools/devtools.md_7623_16210
## Profile your application The **Profiler** tab lets you visualize the execution of Angular's change detection. This is useful for determining when and how change detection impacts your application's performance. <img src="assets/images/guide/devtools/profiler.png" alt="A screenshot of the 'Profiler' tab which reads 'Click the play button to start a new recording, or upload a json file containing profiler data.' Next to this is a record button to being recording a new profile as well as a file picker to select an existing profile."> The Profiler tab lets you start profiling the current application or import an existing profile from a previous run. To start profiling your application, hover over the circle in the top-left corner within the **Profiler** tab and click **Start recording**. During profiling, Angular DevTools captures execution events, such as change detection and lifecycle hook execution. Interact with your application to trigger change detection and generate data Angular DevTools can use. To finish recording, click the circle again to **Stop recording**. You can also import an existing recording. Read more about this feature in the [Import recording](tools/devtools#import-and-export-recordings) section. ### Understand your application's execution After recording or importing a profile, Angular DevTools displays a visualization of change detection cycles. <img src="assets/images/guide/devtools/default-profiler-view.png" alt="A screenshot of the 'Profiler' tab after a profile has been recorded or uploaded. It displays a bar chart illustrating various change detection cycles with some text which reads 'Select a bar to preview a particular change detection cycle'."> Each bar in the sequence represents a change detection cycle in your app. The taller a bar is, the longer the application spent running change detection in this cycle. When you select a bar, DevTools displays useful information about it including: * A bar chart with all the components and directives that it captured during this cycle * How much time Angular spent running change detection in this cycle. * An estimated frame rate as experienced by the user. * The source which triggered change detection. <img src="assets/images/guide/devtools/profiler-selected-bar.png" alt="A screenshot of the 'Profiler' tab. A single bar has been selected by the user and a nearby dropdown menu displays 'Bar chart`, showing a second bar chart underneath it. The new chart has two bars which take up the majority of the space, one labeled `TodosComponent` and the other labeled `NgForOf`. The other bars are small enough to be negligible in comparison."> ### Understand component execution The bar chart displayed after clicking on a change detection cycle displays a detailed view about how much time your application spent running change detection in that particular component or directive. This example shows the total time spent by the `NgForOf` directive and which method was called on it. <img src="assets/images/guide/devtools/directive-details.png" alt="A screenshot of the 'Profiler' tab where the `NgForOf` bar is selected. A detailed view of `NgForOf` is visible to the right where it lists 'Total time spent: 1.76 ms'. It includes a with exactly one row, listing `NgForOf` as a directives with an `ngDoCheck` method which took 1.76 ms. It also includes a list labeled 'Parent Hierarchy' containing the parent components of this directive."> ### Hierarchical views <img src="assets/images/guide/devtools/flame-graph-view.png" alt="A screenshot of the 'Profiler' tab. A single bar has been selected by the user and a nearby dropdown menu now displays 'Flame graph', showing a flame graph underneath it. The flame graph starts with a row called 'Entire application' and another row called 'AppComponent'. Beneath those, the rows start to break up into multiple items, starting with `[RouterOutlet]` and `DemoAppComponent` on the third row. A few layers deep, one cell is highlighted red."> You can also visualize the change detection execution in a flame graph-like view. Each tile in the graph represents an element on the screen at a specific position in the render tree. For example, consider a change detection cycle where a `LoggedOutUserComponent` is removed and in its place Angular rendered a `LoggedInUserComponent`. In this scenario both components will be displayed in the same tile. The x-axis represents the full time it took to render this change detection cycle. The y-axis represents the element hierarchy. Running change detection for an element requires render its directives and child components. Together, this graph visualizes which components are taking the longest time to render and where that time is going. Each tile is colored depending on how much time Angular spent there. Angular DevTools determines the intensity of the color by the time spent relative to the tile where rendering took the most time. When you click on a certain tile, you'll see details about it in the panel on the right. Double-clicking the tile zooms it in so you can more easily view its nested children. ### Debug change detection and `OnPush` components Normally, the graph visualizes the time it takes to *render* an application, for any given change detection frame. However some components such as `OnPush` components will only re-render if their input properties change. It can be useful to visualize the flame graph without these components for particular frames. To visualize only the components in a change detection frame that went through the change detection process, select the **Change detection** checkbox at the top, above the flame graph. This view highlights all the components that went through change detection and displays those that did not in gray, such as `OnPush` components that did not re-render. <img src="assets/images/guide/devtools/debugging-onpush.png" alt="A screenshot of the 'Profiler' tab displaying a flame chart visualization of a change detection cycle. A checkbox labeled 'Show only change detection' is now checked. The flame graph looks very similar to before, however the color of components has changed from orange to blue. Several tiles labeled `[RouterOutlet]` are no longer highlighted with any color."> ### Import and export recordings Click the **Save Profile** button at the top-right of a recorded profiling session to export it as a JSON file and save it to the disk. Later, import the file in the initial view of the profiler by clicking the **Choose file** input. <img src="assets/images/guide/devtools/save-profile.png" alt="A screenshot of the 'Profiler' tab displaying change detection cycles. On the right side a 'Save Profile' button is visible."> ## Inspect your injectors Note: The Injector Tree is available for Angular Applications built with version 17 or higher. ### View the injector hierarchy of your application The **Injector Tree** tab lets you explore the structure of the Injectors configured in your application. Here you will see two trees representing the [injector hierarchy](guide/di/hierarchical-dependency-injection) of your application. One tree is your environment hierarchy, the other is your element hierarchy. <img src="assets/images/guide/devtools/di-injector-tree.png" alt="A screenshot of the 'Profiler' tab displaying the injector tree tab in Angular Devtools visualizing the injector graph for an example application."> ### Visualize resolution paths When a specific injector is selected, the path that Angular's dependency injection algorithm traverses from that injector to the root is highlighted. For element injectors, this includes highlighting the environment injectors that the dependency injection algorithm jumps to when a dependency cannot be resolved in the element hierarchy. See [resolution rules](guide/di/hierarchical-dependency-injection#resolution-rules) for more details about how Angular resolves resolution paths. <img src="assets/images/guide/devtools/di-injector-tree-selected.png" alt="A screenshot of the 'Profiler' tab displaying how the injector tree visualize highlights resolution paths when an injector is selected."> ### View injector providers Clicking an injector that has configured providers will display those providers in a list on the right of the injector tree view. Here you can view the provided token and it's type. <img src="assets/images/guide/devtools/di-injector-tree-providers.png" alt="A screenshot of the 'Profiler' tab displaying how providers are made visible when an injector is selected.">
{ "commit_id": "cb34e406ba", "end_byte": 16210, "start_byte": 7623, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/devtools.md" }
angular/adev/src/content/tools/BUILD.bazel_0_183
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "tools", srcs = glob([ "*.md", ]), visibility = ["//adev:__subpackages__"], )
{ "commit_id": "cb34e406ba", "end_byte": 183, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/BUILD.bazel" }
angular/adev/src/content/tools/language-service.md_0_8127
# Angular Language Service The Angular Language Service provides code editors with a way to get completions, errors, hints, and navigation inside Angular templates. It works with external templates in separate HTML files, and also with in-line templates. ## Configuring compiler options for the Angular Language Service To enable the latest Language Service features, set the `strictTemplates` option in `tsconfig.json` by setting `strictTemplates` to `true`, as shown in the following example: <docs-code language="json"> "angularCompilerOptions": { "strictTemplates": true } </docs-code> For more information, see the [Angular compiler options](reference/configs/angular-compiler-options) guide. ## Features Your editor autodetects that you are opening an Angular file. It then uses the Angular Language Service to read your `tsconfig.json` file, find all the templates you have in your application, and then provide language services for any templates that you open. Language services include: * Completions lists * AOT Diagnostic messages * Quick info * Go to definition ### Autocompletion Autocompletion can speed up your development time by providing you with contextual possibilities and hints as you type. This example shows autocomplete in an interpolation. As you type it out, you can press tab to complete. <img alt="autocompletion" src="assets/images/guide/language-service/language-completion.gif"> There are also completions within elements. Any elements you have as a component selector will show up in the completion list. ### Error checking The Angular Language Service can forewarn you of mistakes in your code. In this example, Angular doesn't know what `orders` is or where it comes from. <img alt="error checking" src="assets/images/guide/language-service/language-error.gif"> ### Quick info and navigation The quick-info feature lets you hover to see where components, directives, and modules come from. You can then click "Go to definition" or press F12 to go directly to the definition. <img alt="navigation" src="assets/images/guide/language-service/language-navigation.gif"> ## Angular Language Service in your editor Angular Language Service is currently available as an extension for [Visual Studio Code](https://code.visualstudio.com), [WebStorm](https://www.jetbrains.com/webstorm), [Sublime Text](https://www.sublimetext.com) and [Eclipse IDE](https://www.eclipse.org/eclipseide). ### Visual Studio Code In [Visual Studio Code](https://code.visualstudio.com), install the extension from the [Extensions: Marketplace](https://marketplace.visualstudio.com/items?itemName=Angular.ng-template). Open the marketplace from the editor using the Extensions icon on the left menu pane, or use VS Quick Open \(⌘+P on Mac, CTRL+P on Windows\) and type "? ext". In the marketplace, search for Angular Language Service extension, and click the **Install** button. The Visual Studio Code integration with the Angular language service is maintained and distributed by the Angular team. ### Visual Studio In [Visual Studio](https://visualstudio.microsoft.com), install the extension from the [Extensions: Marketplace](https://marketplace.visualstudio.com/items?itemName=TypeScriptTeam.AngularLanguageService). Open the marketplace from the editor selecting Extensions on the top menu pane, and then selecting Manage Extensions. In the marketplace, search for Angular Language Service extension, and click the **Install** button. The Visual Studio integration with the Angular language service is maintained and distributed by Microsoft with help from the Angular team. Check out the project [here](https://github.com/microsoft/vs-ng-language-service). ### WebStorm In [WebStorm](https://www.jetbrains.com/webstorm), enable the plugin [Angular and AngularJS](https://plugins.jetbrains.com/plugin/6971-angular-and-angularjs). Since WebStorm 2019.1, the `@angular/language-service` is not required anymore and should be removed from your `package.json`. ### Sublime Text In [Sublime Text](https://www.sublimetext.com), the Language Service supports only in-line templates when installed as a plug-in. You need a custom Sublime plug-in \(or modifications to the current plug-in\) for completions in HTML files. To use the Language Service for in-line templates, you must first add an extension to allow TypeScript, then install the Angular Language Service plug-in. Starting with TypeScript 2.3, TypeScript has a plug-in model that the language service can use. 1. Install the latest version of TypeScript in a local `node_modules` directory: <docs-code language="shell"> npm install --save-dev typescript </docs-code> 1. Install the Angular Language Service package in the same location: <docs-code language="shell"> npm install --save-dev @angular/language-service </docs-code> 1. Once the package is installed, add the following to the `"compilerOptions"` section of your project's `tsconfig.json`. <docs-code header="tsconfig.json" language="json"> "plugins": [ {"name": "@angular/language-service"} ] </docs-code> 1. In your editor's user preferences \(`Cmd+,` or `Ctrl+,`\), add the following: <docs-code header="Sublime Text user preferences" language="json"> "typescript-tsdk": "<path to your folder>/node_modules/typescript/lib" </docs-code> This lets the Angular Language Service provide diagnostics and completions in `.ts` files. ### Eclipse IDE Either directly install the "Eclipse IDE for Web and JavaScript developers" package which comes with the Angular Language Server included, or from other Eclipse IDE packages, use Help > Eclipse Marketplace to find and install [Eclipse Wild Web Developer](https://marketplace.eclipse.org/content/wild-web-developer-html-css-javascript-typescript-nodejs-angular-json-yaml-kubernetes-xml). ### Neovim Angular language service can be used with Neovim by using the [nvim-lspconfig](https://github.com/neovim/nvim-lspconfig) plugin. 1. [Install nvim-lspconfig](https://github.com/neovim/nvim-lspconfig?tab=readme-ov-file#install) 2. [Configure angularls for nvim-lspconfig](https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#angularls) ## How the Language Service works When you use an editor with a language service, the editor starts a separate language-service process and communicates with it through an [RPC](https://en.wikipedia.org/wiki/Remote_procedure_call), using the [Language Server Protocol](https://microsoft.github.io/language-server-protocol). When you type into the editor, the editor sends information to the language-service process to track the state of your project. When you trigger a completion list within a template, the editor first parses the template into an HTML [abstract syntax tree (AST)](https://en.wikipedia.org/wiki/Abstract_syntax_tree). The Angular compiler interprets that tree to determine the context: which module the template is part of, the current scope, the component selector, and where your cursor is in the template AST. It can then determine the symbols that could potentially be at that position. It's a little more involved if you are in an interpolation. If you have an interpolation of `{{data.---}}` inside a `div` and need the completion list after `data.---`, the compiler can't use the HTML AST to find the answer. The HTML AST can only tell the compiler that there is some text with the characters "`{{data.---}}`". That's when the template parser produces an expression AST, which resides within the template AST. The Angular Language Services then looks at `data.---` within its context, asks the TypeScript Language Service what the members of `data` are, and returns the list of possibilities. ## More information * For more in-depth information on the implementation, see the [Angular Language Service source](https://github.com/angular/angular/blob/main/packages/language-service/src) * For more on the design considerations and intentions, see [design documentation here](https://github.com/angular/vscode-ng-language-service/wiki/Design)
{ "commit_id": "cb34e406ba", "end_byte": 8127, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/language-service.md" }
angular/adev/src/content/tools/libraries/angular-package-format.md_0_10358
# Angular package format This document describes the Angular Package Format \(APF\). APF is an Angular specific specification for the structure and format of npm packages that is used by all first-party Angular packages \(`@angular/core`, `@angular/material`, etc.\) and most third-party Angular libraries. APF enables a package to work seamlessly under most common scenarios that use Angular. Packages that use APF are compatible with the tooling offered by the Angular team as well as wider JavaScript ecosystem. It is recommended that third-party library developers follow the same npm package format. HELPFUL: APF is versioned along with the rest of Angular, and every major version improves the package format. You can find the versions of the specification prior to v13 in this [google doc](https://docs.google.com/document/d/1CZC2rcpxffTDfRDs6p1cfbmKNLA6x5O-NtkJglDaBVs/preview). ## Why specify a package format? In today's JavaScript landscape, developers consume packages in many different ways, using many different toolchains \(Webpack, rollup, esbuild, etc.\). These tools may understand and require different inputs - some tools may be able to process the latest ES language version, while others may benefit from directly consuming an older ES version. The Angular distribution format supports all of the commonly used development tools and workflows, and adds emphasis on optimizations that result either in smaller application payload size or faster development iteration cycle \(build time\). Developers can rely on Angular CLI and [ng-packagr](https://github.com/ng-packagr/ng-packagr) \(a build tool Angular CLI uses\) to produce packages in the Angular package format. See the [Creating Libraries](tools/libraries/creating-libraries) guide for more details. ## File layout The following example shows a simplified version of the `@angular/core` package's file layout, with an explanation for each file in the package. ```markdown node_modules/@angular/core ├── README.md ├── package.json ├── index.d.ts ├── fesm2022 │ ├── core.mjs │ ├── core.mjs.map │ ├── testing.mjs │ └── testing.mjs.map └── testing └── index.d.ts ``` This table describes the file layout under `node_modules/@angular/core` annotated to describe the purpose of files and directories: | Files | Purpose | |:--- |:--- | | `README.md` | Package README, used by npmjs web UI. | | `package.json` | Primary `package.json`, describing the package itself as well as all available entrypoints and code formats. This file contains the "exports" mapping used by runtimes and tools to perform module resolution. | | `index.d.ts` | Bundled `.d.ts` for the primary entrypoint `@angular/core`. | | `fesm2022/` <br /> &nbsp;&nbsp;─ `core.mjs` <br /> &nbsp;&nbsp;─ `core.mjs.map` <br /> &nbsp;&nbsp;─ `testing.mjs` <br /> &nbsp;&nbsp;─ `testing.mjs.map` | Code for all entrypoints in flattened \(FESM\) ES2022 format, along with source maps. | | `testing/` | Directory representing the "testing" entrypoint. | | `testing/index.d.ts` | Bundled `.d.ts` for the `@angular/core/testing` entrypoint. | ## `package.json` The primary `package.json` contains important package metadata, including the following: * It [declares](#esm-declaration) the package to be in EcmaScript Module \(ESM\) format * It contains an [`"exports"` field](#exports) which defines the available source code formats of all entrypoints * It contains [keys](#legacy-resolution-keys) which define the available source code formats of the primary `@angular/core` entrypoint, for tools which do not understand `"exports"`. These keys are considered deprecated, and could be removed as the support for `"exports"` rolls out across the ecosystem. * It declares whether the package contains [side effects](#side-effects) ### ESM declaration The top-level `package.json` contains the key: <docs-code language="javascript"> { "type": "module" } </docs-code> This informs resolvers that code within the package is using EcmaScript Modules as opposed to CommonJS modules. ### `"exports"` The `"exports"` field has the following structure: <docs-code language="javascript"> "exports": { "./schematics/*": { "default": "./schematics/*.js" }, "./package.json": { "default": "./package.json" }, ".": { "types": "./core.d.ts", "default": "./fesm2022/core.mjs" }, "./testing": { "types": "./testing/testing.d.ts", "default": "./fesm2022/testing.mjs" } } </docs-code> Of primary interest are the `"."` and the `"./testing"` keys, which define the available code formats for the `@angular/core` primary entrypoint and the `@angular/core/testing` secondary entrypoint, respectively. For each entrypoint, the available formats are: | Formats | Details | |:--- |:--- | | Typings \(`.d.ts` files\) | `.d.ts` files are used by TypeScript when depending on a given package. | | `default` | ES2022 code flattened into a single source. Tooling that is aware of these keys may preferentially select a desirable code format from `"exports"`. Libraries may want to expose additional static files which are not captured by the exports of the JavaScript-based entry-points such as Sass mixins or pre-compiled CSS. For more information, see [Managing assets in a library](tools/libraries/creating-libraries#managing-assets-in-a-library). ### Legacy resolution keys In addition to `"exports"`, the top-level `package.json` also defines legacy module resolution keys for resolvers that don't support `"exports"`. For `@angular/core` these are: <docs-code language="javascript"> { "module": "./fesm2022/core.mjs", "typings": "./core.d.ts", } </docs-code> As shown in the preceding code snippet, a module resolver can use these keys to load a specific code format. ### Side effects The last function of `package.json` is to declare whether the package has [side effects](#sideeffects-flag). <docs-code language="javascript"> { "sideEffects": false } </docs-code> Most Angular packages should not depend on top-level side effects, and thus should include this declaration. ## Entrypoints and code splitting Packages in the Angular Package Format contain one primary entrypoint and zero or more secondary entrypoints \(for example, `@angular/common/http`\). Entrypoints serve several functions. 1. They define the module specifiers from which users import code \(for example, `@angular/core` and `@angular/core/testing`\). Users typically perceive these entrypoints as distinct groups of symbols, with different purposes or capability. Specific entrypoints might only be used for special purposes, such as testing. Such APIs can be separated out from the primary entrypoint to reduce the chance of them being used accidentally or incorrectly. 1. They define the granularity at which code can be lazily loaded. Many modern build tools are only capable of "code splitting" \(aka lazy loading\) at the ES Module level. The Angular Package Format uses primarily a single "flat" ES Module per entry point. This means that most build tooling is not able to split code with a single entry point into multiple output chunks. The general rule for APF packages is to use entrypoints for the smallest sets of logically connected code possible. For example, the Angular Material package publishes each logical component or set of components as a separate entrypoint - one for Button, one for Tabs, etc. This allows each Material component to be lazily loaded separately, if desired. Not all libraries require such granularity. Most libraries with a single logical purpose should be published as a single entrypoint. `@angular/core` for example uses a single entrypoint for the runtime, because the Angular runtime is generally used as a single entity. ### Resolution of secondary entry points Secondary entrypoints can be resolved via the `"exports"` field of the `package.json` for the package. ## README.md The README file in the Markdown format that is used to display description of a package on npm and GitHub. Example README content of @angular/core package: <docs-code language="html"> Angular &equals;&equals;&equals;&equals;&equals;&equals;&equals; The sources for this package are in the main [Angular](https://github.com/angular/angular) repo.Please file issues and pull requests against that repo. License: MIT </docs-code> ## Partial compilation Libraries in the Angular Package Format must be publ
{ "commit_id": "cb34e406ba", "end_byte": 10358, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/libraries/angular-package-format.md" }
angular/adev/src/content/tools/libraries/angular-package-format.md_10358_15853
ished in "partial compilation" mode. This is a compilation mode for `ngc` which produces compiled Angular code that is not tied to a specific Angular runtime version, in contrast to the full compilation used for applications, where the Angular compiler and runtime versions must match exactly. To partially compile Angular code, use the `compilationMode` flag in the `angularCompilerOptions` property of your `tsconfig.json`: <docs-code language="javascript"> { … "angularCompilerOptions": { "compilationMode": "partial", } } </docs-code> Partially compiled library code is then converted to fully compiled code during the application build process by the Angular CLI. If your build pipeline does not use the Angular CLI then refer to the [Consuming partial ivy code outside the Angular CLI](tools/libraries/creating-libraries#consuming-partial-ivy-code-outside-the-angular-cli) guide. ## Optimizations ### Flattening of ES modules The Angular Package Format specifies that code be published in "flattened" ES module format. This significantly reduces the build time of Angular applications as well as download and parse time of the final application bundle. Please check out the excellent post ["The cost of small modules"](https://nolanlawson.com/2016/08/15/the-cost-of-small-modules) by Nolan Lawson. The Angular compiler can generate index ES module files. Tools like Rollup can use these files to generate flattened modules in a *Flattened ES Module* (FESM) file format. FESM is a file format created by flattening all ES Modules accessible from an entrypoint into a single ES Module. It's formed by following all imports from a package and copying that code into a single file while preserving all public ES exports and removing all private imports. The abbreviated name, FESM, pronounced *phe-som*, can be followed by a number such as FESM2020. The number refers to the language level of the JavaScript inside the module. Accordingly a FESM2022 file would be ESM+ES2022 and include import/export statements and ES2022 source code. To generate a flattened ES Module index file, use the following configuration options in your tsconfig.json file: <docs-code language="javascript"> { "compilerOptions": { … "module": "esnext", "target": "es2022", … }, "angularCompilerOptions": { … "flatModuleOutFile": "my-ui-lib.js", "flatModuleId": "my-ui-lib" } } </docs-code> Once the index file \(for example, `my-ui-lib.js`\) is generated by ngc, bundlers and optimizers like Rollup can be used to produce the flattened ESM file. ### "sideEffects" flag By default, EcmaScript Modules are side-effectful: importing from a module ensures that any code at the top level of that module should run. This is often undesirable, as most side-effectful code in typical modules is not truly side-effectful, but instead only affects specific symbols. If those symbols are not imported and used, it's often desirable to remove them in an optimization process known as tree-shaking, and the side-effectful code can prevent this. Build tools such as Webpack support a flag which allows packages to declare that they do not depend on side-effectful code at the top level of their modules, giving the tools more freedom to tree-shake code from the package. The end result of these optimizations should be smaller bundle size and better code distribution in bundle chunks after code-splitting. This optimization can break your code if it contains non-local side-effects - this is however not common in Angular applications and it's usually a sign of bad design. The recommendation is for all packages to claim the side-effect free status by setting the `sideEffects` property to `false`, and that developers follow the [Angular Style Guide](/style-guide) which naturally results in code without non-local side-effects. More info: [webpack docs on side effects](https://github.com/webpack/webpack/tree/master/examples/side-effects) ### ES2022 language level ES2022 Language level is now the default language level that is consumed by Angular CLI and other tooling. The Angular CLI down-levels the bundle to a language level that is supported by all targeted browsers at application build time. ### d.ts bundling / type definition flattening As of APF v8 it is now preferred to run [API Extractor](https://api-extractor.com), to bundle TypeScript definitions so that the entire API appears in a single file. In prior APF versions each entry point would have a `src` directory next to the .d.ts entry point and this directory contained individual d.ts files matching the structure of the original source code. While this distribution format is still allowed and supported, it is highly discouraged because it confuses tools like IDEs that then offer incorrect autocompletion, and allows users to depend on deep-import paths which are typically not considered to be public API of a library or a package. ### Tslib As of APF v10, it is recommended to add tslib as a direct dependency of your primary entry-point. This is because the tslib version is tied to the TypeScript version used to compile your library. ## Examples <docs-pill-row> <docs-pill href="https://unpkg.com/browse/@angular/core@17.0.0/" title="@angular/core package"/> <docs-pill href="https://unpkg.com/browse/@angular/material@17.0.0/" title="@angular/material package"/> </docs-pill-row> ## Definition of terms The following terms are used throughout this document intent
{ "commit_id": "cb34e406ba", "end_byte": 15853, "start_byte": 10358, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/libraries/angular-package-format.md" }
angular/adev/src/content/tools/libraries/angular-package-format.md_15853_20032
ionally. In this section are the definitions of all of them to provide additional clarity. ### Package The smallest set of files that are published to NPM and installed together, for example `@angular/core`. This package includes a manifest called package.json, compiled source code, typescript definition files, source maps, metadata, etc. The package is installed with `npm install @angular/core`. ### Symbol A class, function, constant, or variable contained in a module and optionally made visible to the external world via a module export. ### Module Short for ECMAScript Modules. A file containing statements that import and export symbols. This is identical to the definition of modules in the ECMAScript spec. ### ESM Short for ECMAScript Modules \(see above\). ### FESM Short for Flattened ES Modules and consists of a file format created by flattening all ES Modules accessible from an entry point into a single ES Module. ### Module ID The identifier of a module used in the import statements \(for example, `@angular/core`\). The ID often maps directly to a path on the filesystem, but this is not always the case due to various module resolution strategies. ### Module specifier A module identifier \(see above\). ### Module resolution strategy Algorithm used to convert Module IDs to paths on the filesystem. Node.js has one that is well specified and widely used, TypeScript supports several module resolution strategies, [Closure Compiler](https://developers.google.com/closure/compiler) has yet another strategy. ### Module format Specification of the module syntax that covers at minimum the syntax for the importing and exporting from a file. Common module formats are CommonJS \(CJS, typically used for Node.js applications\) or ECMAScript Modules \(ESM\). The module format indicates only the packaging of the individual modules, but not the JavaScript language features used to make up the module content. Because of this, the Angular team often uses the language level specifier as a suffix to the module format, \(for example, ESM+ES2022 specifies that the module is in ESM format and contains ES2022 code\). ### Bundle An artifact in the form of a single JS file, produced by a build tool \(for example, [Webpack](https://webpack.js.org) or [Rollup](https://rollupjs.org)\) that contains symbols originating in one or more modules. Bundles are a browser-specific workaround that reduce network strain that would be caused if browsers were to start downloading hundreds if not tens of thousands of files. Node.js typically doesn't use bundles. Common bundle formats are UMD and System.register. ### Language level The language of the code \(ES2022\). Independent of the module format. ### Entry point A module intended to be imported by the user. It is referenced by a unique module ID and exports the public API referenced by that module ID. An example is `@angular/core` or `@angular/core/testing`. Both entry points exist in the `@angular/core` package, but they export different symbols. A package can have many entry points. ### Deep import A process of retrieving symbols from modules that are not Entry Points. These module IDs are usually considered to be private APIs that can change over the lifetime of the project or while the bundle for the given package is being created. ### Top-Level import An import coming from an entry point. The available top-level imports are what define the public API and are exposed in "@angular/name" modules, such as `@angular/core` or `@angular/common`. ### Tree-shaking The process of identifying and removing code not used by an application - also known as dead code elimination. This is a global optimization performed at the application level using tools like [Rollup](https://rollupjs.org), [Closure Compiler](https://developers.google.com/closure/compiler), or [Terser](https://github.com/terser/terser). ### AOT compiler The Ahead of Time Compiler for Angular. ### Flattened type definitions The bundled TypeScript definitions generated from [API Extractor](https://api-extractor.com).
{ "commit_id": "cb34e406ba", "end_byte": 20032, "start_byte": 15853, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/libraries/angular-package-format.md" }
angular/adev/src/content/tools/libraries/overview.md_0_2925
# Overview of Angular libraries Many applications need to solve the same general problems, such as presenting a unified user interface, presenting data, and allowing data entry. Developers can create general solutions for particular domains that can be adapted for re-use in different applications. Such a solution can be built as Angular *libraries* and these libraries can be published and shared as *npm packages*. An Angular library is an Angular project that differs from an application in that it cannot run on its own. A library must be imported and used in an application. Libraries extend Angular's base features. For example, to add [reactive forms](guide/forms/reactive-forms) to an application, add the library package using `ng add @angular/forms`, then import the `ReactiveFormsModule` from the `@angular/forms` library in your application code. Similarly, adding the [service worker](ecosystem/service-workers) library to an Angular application is one of the steps for turning an application into a [Progressive Web App](https://developers.google.com/web/progressive-web-apps) \(PWA\). [Angular Material](https://material.angular.io) is an example of a large, general-purpose library that provides sophisticated, reusable, and adaptable UI components. Any application developer can use these and other libraries that have been published as npm packages by the Angular team or by third parties. See [Using Published Libraries](tools/libraries/using-libraries). HELPFUL: Libraries are intended to be used by Angular applications. To add Angular features to non-Angular web applications, use [Angular custom elements](guide/elements). ## Creating libraries If you have developed features that are suitable for reuse, you can create your own libraries. These libraries can be used locally in your workspace, or you can publish them as [npm packages](reference/configs/npm-packages) to share with other projects or other Angular developers. These packages can be published to the npm registry, a private npm Enterprise registry, or a private package management system that supports npm packages. See [Creating Libraries](tools/libraries/creating-libraries). Deciding to package features as a library is an architectural decision. It is comparable to deciding whether a feature is a component or a service, or deciding on the scope of a component. Packaging features as a library forces the artifacts in the library to be decoupled from the application's business logic. This can help to avoid various bad practices or architecture mistakes that can make it difficult to decouple and reuse code in the future. Putting code into a separate library is more complex than simply putting everything in one application. It requires more of an investment in time and thought for managing, maintaining, and updating the library. This complexity can pay off when the library is being used in multiple applications.
{ "commit_id": "cb34e406ba", "end_byte": 2925, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/libraries/overview.md" }
angular/adev/src/content/tools/libraries/creating-libraries.md_0_9256
# Creating libraries This page provides a conceptual overview of how to create and publish new libraries to extend Angular functionality. If you find that you need to solve the same problem in more than one application \(or want to share your solution with other developers\), you have a candidate for a library. A simple example might be a button that sends users to your company website, that would be included in all applications that your company builds. ## Getting started Use the Angular CLI to generate a new library skeleton in a new workspace with the following commands. <docs-code language="shell"> ng new my-workspace --no-create-application cd my-workspace ng generate library my-lib </docs-code> <docs-callout title="Naming your library"> You should be very careful when choosing the name of your library if you want to publish it later in a public package registry such as npm. See [Publishing your library](tools/libraries/creating-libraries#publishing-your-library). Avoid using a name that is prefixed with `ng-`, such as `ng-library`. The `ng-` prefix is a reserved keyword used from the Angular framework and its libraries. The `ngx-` prefix is preferred as a convention used to denote that the library is suitable for use with Angular. It is also an excellent indication to consumers of the registry to differentiate between libraries of different JavaScript frameworks. </docs-callout> The `ng generate` command creates the `projects/my-lib` folder in your workspace, which contains a component and a service inside an NgModule. HELPFUL: For more details on how a library project is structured, refer to the [Library project files](reference/configs/file-structure#library-project-files) section of the [Project File Structure guide](reference/configs/file-structure). Use the monorepo model to use the same workspace for multiple projects. See [Setting up for a multi-project workspace](reference/configs/file-structure#multiple-projects). When you generate a new library, the workspace configuration file, `angular.json`, is updated with a project of type `library`. <docs-code language="json"> "projects": { … "my-lib": { "root": "projects/my-lib", "sourceRoot": "projects/my-lib/src", "projectType": "library", "prefix": "lib", "architect": { "build": { "builder": "@angular-devkit/build-angular:ng-packagr", … </docs-code> Build, test, and lint the project with CLI commands: <docs-code language="shell"> ng build my-lib --configuration development ng test my-lib ng lint my-lib </docs-code> Notice that the configured builder for the project is different from the default builder for application projects. This builder, among other things, ensures that the library is always built with the [AOT compiler](tools/cli/aot-compiler). To make library code reusable you must define a public API for it. This "user layer" defines what is available to consumers of your library. A user of your library should be able to access public functionality \(such as NgModules, service providers and general utility functions\) through a single import path. The public API for your library is maintained in the `public-api.ts` file in your library folder. Anything exported from this file is made public when your library is imported into an application. Use an NgModule to expose services and components. Your library should supply documentation \(typically a README file\) for installation and maintenance. ## Refactoring parts of an application into a library To make your solution reusable, you need to adjust it so that it does not depend on application-specific code. Here are some things to consider in migrating application functionality to a library. * Declarations such as components and pipes should be designed as stateless, meaning they don't rely on or alter external variables. If you do rely on state, you need to evaluate every case and decide whether it is application state or state that the library would manage. * Any observables that the components subscribe to internally should be cleaned up and disposed of during the lifecycle of those components * Components should expose their interactions through inputs for providing context, and outputs for communicating events to other components * Check all internal dependencies. * For custom classes or interfaces used in components or service, check whether they depend on additional classes or interfaces that also need to be migrated * Similarly, if your library code depends on a service, that service needs to be migrated * If your library code or its templates depend on other libraries \(such as Angular Material, for instance\), you must configure your library with those dependencies * Consider how you provide services to client applications. * Services should declare their own providers, rather than declaring providers in the NgModule or a component. Declaring a provider makes that service *tree-shakable*. This practice lets the compiler leave the service out of the bundle if it never gets injected into the application that imports the library. For more about this, see [Tree-shakable providers](guide/di/lightweight-injection-tokens). * If you register global service providers or share providers across multiple NgModules, use the [`forRoot()` and `forChild()` design patterns](guide/ngmodules/singleton-services) provided by the [RouterModule](api/router/RouterModule) * If your library provides optional services that might not be used by all client applications, support proper tree-shaking for that case by using the [lightweight token design pattern](guide/di/lightweight-injection-tokens) ## Integrating with the CLI using code-generation schematics A library typically includes *reusable code* that defines components, services, and other Angular artifacts \(pipes, directives\) that you import into a project. A library is packaged into an npm package for publishing and sharing. This package can also include schematics that provide instructions for generating or transforming code directly in your project, in the same way that the CLI creates a generic new component with `ng generate component`. A schematic that is packaged with a library can, for example, provide the Angular CLI with the information it needs to generate a component that configures and uses a particular feature, or set of features, defined in that library. One example of this is [Angular Material's navigation schematic](https://material.angular.io/guide/schematics#navigation-schematic) which configures the CDK's [BreakpointObserver](https://material.angular.io/cdk/layout/overview#breakpointobserver) and uses it with Material's [MatSideNav](https://material.angular.io/components/sidenav/overview) and [MatToolbar](https://material.angular.io/components/toolbar/overview) components. Create and include the following kinds of schematics: * Include an installation schematic so that `ng add` can add your library to a project * Include generation schematics in your library so that `ng generate` can scaffold your defined artifacts \(components, services, tests\) in a project * Include an update schematic so that `ng update` can update your library's dependencies and provide migrations for breaking changes in new releases What you include in your library depends on your task. For example, you could define a schematic to create a dropdown that is pre-populated with canned data to show how to add it to an application. If you want a dropdown that would contain different passed-in values each time, your library could define a schematic to create it with a given configuration. Developers could then use `ng generate` to configure an instance for their own application. Suppose you want to read a configuration file and then generate a form based on that configuration. If that form needs additional customization by the developer who is using your library, it might work best as a schematic. However, if the form will always be the same and not need much customization by developers, then you could create a dynamic component that takes the configuration and generates the form. In general, the more complex the customization, the more useful the schematic approach. For more information, see [Schematics Overview](tools/cli/schematics) and [Schematics for Libraries](tools/cli/schematics-for-libraries). ## Publishing your library Use the Angular CLI and the npm package manager to build and publish your library as an npm package. Angular CLI uses a tool called [ng-packagr](https://github.com/ng-packagr/ng-packagr/blob/master/README.md) to create packages from your compiled code that can be published to npm. See [Building libraries with Ivy](tools/libraries/creating-libraries#publishing-libraries) for information on the distribution formats supported by `ng-packagr` and guidance on how to choose the right format for your library. You should always build libraries for distribution using the `production` configuration. This ensures that generated output uses the appropriate optimizations and the correct package format for npm. <docs-code language="shell"> ng build my-lib cd dist/my-lib npm publish </docs-code> ## M
{ "commit_id": "cb34e406ba", "end_byte": 9256, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/libraries/creating-libraries.md" }
angular/adev/src/content/tools/libraries/creating-libraries.md_9256_17467
anaging assets in a library In your Angular library, the distributable can include additional assets like theming files, Sass mixins, or documentation \(like a changelog\). For more information [copy assets into your library as part of the build](https://github.com/ng-packagr/ng-packagr/blob/master/docs/copy-assets.md) and [embed assets in component styles](https://github.com/ng-packagr/ng-packagr/blob/master/docs/embed-assets-css.md). IMPORTANT: When including additional assets like Sass mixins or pre-compiled CSS. You need to add these manually to the conditional ["exports"](tools/libraries/angular-package-format#quotexportsquot) in the `package.json` of the primary entrypoint. `ng-packagr` will merge handwritten `"exports"` with the auto-generated ones, allowing for library authors to configure additional export subpaths, or custom conditions. <docs-code language="json"> "exports": { ".": { "sass": "./_index.scss", }, "./theming": { "sass": "./_theming.scss" }, "./prebuilt-themes/indigo-pink.css": { "style": "./prebuilt-themes/indigo-pink.css" } } </docs-code> The above is an extract from the [@angular/material](https://unpkg.com/browse/@angular/material/package.json) distributable. ## Peer dependencies Angular libraries should list any `@angular/*` dependencies the library depends on as peer dependencies. This ensures that when modules ask for Angular, they all get the exact same module. If a library lists `@angular/core` in `dependencies` instead of `peerDependencies`, it might get a different Angular module instead, which would cause your application to break. ## Using your own library in applications You don't have to publish your library to the npm package manager to use it in the same workspace, but you do have to build it first. To use your own library in an application: * Build the library. You cannot use a library before it is built. <docs-code language="shell"> ng build my-lib </docs-code> * In your applications, import from the library by name: <docs-code language="typescript"> import { myExport } from 'my-lib'; </docs-code> ### Building and rebuilding your library The build step is important if you haven't published your library as an npm package and then installed the package back into your application from npm. For instance, if you clone your git repository and run `npm install`, your editor shows the `my-lib` imports as missing if you haven't yet built your library. HELPFUL: When you import something from a library in an Angular application, Angular looks for a mapping between the library name and a location on disk. When you install a library package, the mapping is in the `node_modules` folder. When you build your own library, it has to find the mapping in your `tsconfig` paths. Generating a library with the Angular CLI automatically adds its path to the `tsconfig` file. The Angular CLI uses the `tsconfig` paths to tell the build system where to find the library. For more information, see [Path mapping overview](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping). If you find that changes to your library are not reflected in your application, your application is probably using an old build of the library. You can rebuild your library whenever you make changes to it, but this extra step takes time. *Incremental builds* functionality improves the library-development experience. Every time a file is changed a partial build is performed that emits the amended files. Incremental builds can be run as a background process in your development environment. To take advantage of this feature add the `--watch` flag to the build command: <docs-code language="shell"> ng build my-lib --watch </docs-code> IMPORTANT: The CLI `build` command uses a different builder and invokes a different build tool for libraries than it does for applications. * The build system for applications, `@angular-devkit/build-angular`, is based on `webpack`, and is included in all new Angular CLI projects * The build system for libraries is based on `ng-packagr`. It is only added to your dependencies when you add a library using `ng generate library my-lib`. The two build systems support different things, and even where they support the same things, they do those things differently. This means that the TypeScript source can result in different JavaScript code in a built library than it would in a built application. For this reason, an application that depends on a library should only use TypeScript path mappings that point to the *built library*. TypeScript path mappings should *not* point to the library source `.ts` files. ## Publishing libraries There are two distribution formats to use when publishing a library: | Distribution formats | Details | |:--- |:--- | | Partial-Ivy \(recommended\) | Contains portable code that can be consumed by Ivy applications built with any version of Angular from v12 onwards. | | Full-Ivy | Contains private Angular Ivy instructions, which are not guaranteed to work across different versions of Angular. This format requires that the library and application are built with the *exact* same version of Angular. This format is useful for environments where all library and application code is built directly from source. | For publishing to npm use the partial-Ivy format as it is stable between patch versions of Angular. Avoid compiling libraries with full-Ivy code if you are publishing to npm because the generated Ivy instructions are not part of Angular's public API, and so might change between patch versions. ## Ensuring library version compatibility The Angular version used to build an application should always be the same or greater than the Angular versions used to build any of its dependent libraries. For example, if you had a library using Angular version 13, the application that depends on that library should use Angular version 13 or later. Angular does not support using an earlier version for the application. If you intend to publish your library to npm, compile with partial-Ivy code by setting `"compilationMode": "partial"` in `tsconfig.prod.json`. This partial format is stable between different versions of Angular, so is safe to publish to npm. Code with this format is processed during the application build using the same version of the Angular compiler, ensuring that the application and all of its libraries use a single version of Angular. Avoid compiling libraries with full-Ivy code if you are publishing to npm because the generated Ivy instructions are not part of Angular's public API, and so might change between patch versions. If you've never published a package in npm before, you must create a user account. Read more in [Publishing npm Packages](https://docs.npmjs.com/getting-started/publishing-npm-packages). ## Consuming partial-Ivy code outside the Angular CLI An application installs many Angular libraries from npm into its `node_modules` directory. However, the code in these libraries cannot be bundled directly along with the built application as it is not fully compiled. To finish compilation, use the Angular linker. For applications that don't use the Angular CLI, the linker is available as a [Babel](https://babeljs.io) plugin. The plugin is to be imported from `@angular/compiler-cli/linker/babel`. The Angular linker Babel plugin supports build caching, meaning that libraries only need to be processed by the linker a single time, regardless of other npm operations. Example of integrating the plugin into a custom [Webpack](https://webpack.js.org) build by registering the linker as a [Babel](https://babeljs.io) plugin using [babel-loader](https://webpack.js.org/loaders/babel-loader/#options). <docs-code header="webpack.config.mjs" path="adev/src/content/examples/angular-linker-plugin/webpack.config.mjs" visibleRegion="webpack-config"/> HELPFUL: The Angular CLI integrates the linker plugin automatically, so if consumers of your library are using the CLI, they can install Ivy-native libraries from npm without any additional configuration.
{ "commit_id": "cb34e406ba", "end_byte": 17467, "start_byte": 9256, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/libraries/creating-libraries.md" }
angular/adev/src/content/tools/libraries/using-libraries.md_0_7431
# Usage of Angular libraries published to npm When you build your Angular application, take advantage of sophisticated first-party libraries, as well as a rich ecosystem of third-party libraries. [Angular Material][AngularMaterialMain] is an example of a sophisticated first-party library. ## Install libraries Libraries are published as [npm packages][GuideNpmPackages], usually together with schematics that integrate them with the Angular CLI. To integrate reusable library code into an application, you need to install the package and import the provided functionality in the location you use it. For most published Angular libraries, use the `ng add <lib_name>` Angular CLI command. The `ng add` Angular CLI command uses a package manager to install the library package and invokes schematics that are included in the package to other scaffolding within the project code. Examples of package managers include [npm][NpmjsMain] or [yarn][YarnpkgMain]. Additional scaffolding within the project code includes import statements, fonts, and themes. A published library typically provides a `README` file or other documentation on how to add that library to your application. For an example, see the [Angular Material][AngularMaterialMain] documentation. ### Library typings Typically, library packages include typings in `.d.ts` files; see examples in `node_modules/@angular/material`. If the package of your library does not include typings and your IDE complains, you might need to install the `@types/<lib_name>` package with the library. For example, suppose you have a library named `d3`: <docs-code language="shell"> npm install d3 --save npm install @types/d3 --save-dev </docs-code> Types defined in a `@types/` package for a library installed into the workspace are automatically added to the TypeScript configuration for the project that uses that library. TypeScript looks for types in the `node_modules/@types` directory by default, so you do not have to add each type package individually. If a library does not have typings available at `@types/`, you may use it by manually adding typings for it. To do this: 1. Create a `typings.d.ts` file in your `src/` directory. This file is automatically included as global type definition. 1. Add the following code in `src/typings.d.ts`: <docs-code language="typescript"> declare module 'host' { export interface Host { protocol?: string; hostname?: string; pathname?: string; } export function parse(url: string, queryString?: string): Host; } </docs-code> 1. In the component or file that uses the library, add the following code: <docs-code language="typescript"> import * as host from 'host'; const parsedUrl = host.parse('https://angular.io'); console.log(parsedUrl.hostname); </docs-code> Define more typings as needed. ## Updating libraries A library is able to be updated by the publisher, and also has individual dependencies which need to be kept current. To check for updates to your installed libraries, use the [`ng update`][CliUpdate] Angular CLI command. Use `ng update <lib_name>` Angular CLI command to update individual library versions. The Angular CLI checks the latest published release of the library, and if the latest version is newer than your installed version, downloads it and updates your `package.json` to match the latest version. When you update Angular to a new version, you need to make sure that any libraries you are using are current. If libraries have interdependencies, you might have to update them in a particular order. See the [Angular Update Guide][AngularUpdateMain] for help. ## Adding a library to the runtime global scope If a legacy JavaScript library is not imported into an application, you may add it to the runtime global scope and load it as if it was added in a script tag. Configure the Angular CLI to do this at build time using the `scripts` and `styles` options of the build target in the [`angular.json`][GuideWorkspaceConfig] workspace build configuration file. For example, to use the [Bootstrap 4][GetbootstrapDocs40GettingStartedIntroduction] library 1. Install the library and the associated dependencies using the npm package manager: <docs-code language="shell"> npm install jquery --save npm install popper.js --save npm install bootstrap --save </docs-code> 1. In the `angular.json` configuration file, add the associated script files to the `scripts` array: <docs-code language="json"> "scripts": [ "node_modules/jquery/dist/jquery.slim.js", "node_modules/popper.js/dist/umd/popper.js", "node_modules/bootstrap/dist/js/bootstrap.js" ], </docs-code> 1. Add the `bootstrap.css` CSS file to the `styles` array: <docs-code language="css"> "styles": [ "node_modules/bootstrap/dist/css/bootstrap.css", "src/styles.css" ], </docs-code> 1. Run or restart the `ng serve` Angular CLI command to see Bootstrap 4 work in your application. ### Using runtime-global libraries inside your app After you import a library using the "scripts" array, do **not** import it using an import statement in your TypeScript code. The following code snippet is an example import statement. <docs-code language="typescript"> import * as $ from 'jquery'; </docs-code> If you import it using import statements, you have two different copies of the library: one imported as a global library, and one imported as a module. This is especially bad for libraries with plugins, like JQuery, because each copy includes different plugins. Instead, run the `npm install @types/jquery` Angular CLI command to download typings for your library and then follow the library installation steps. This gives you access to the global variables exposed by that library. ### Defining typings for runtime-global libraries If the global library you need to use does not have global typings, you can declare them manually as `any` in `src/typings.d.ts`. For example: <docs-code language="typescript"> declare var libraryName: any; </docs-code> Some scripts extend other libraries; for instance with JQuery plugins: <docs-code language="typescript"> $('.test').myPlugin(); </docs-code> In this case, the installed `@types/jquery` does not include `myPlugin`, so you need to add an interface in `src/typings.d.ts`. For example: <docs-code language="typescript"> interface JQuery { myPlugin(options?: any): any; } </docs-code> If you do not add the interface for the script-defined extension, your IDE shows an error: <docs-code language="text"> [TS][Error] Property 'myPlugin' does not exist on type 'JQuery' </docs-code> [CliUpdate]: cli/update "ng update | CLI |Angular" [GuideNpmPackages]: reference/configs/npm-packages "Workspace npm dependencies | Angular" [GuideWorkspaceConfig]: reference/configs/workspace-config "Angular workspace configuration | Angular" [Resources]: resources "Explore Angular Resources | Angular" [AngularMaterialMain]: https://material.angular.io "Angular Material | Angular" [AngularUpdateMain]: https://angular.dev/update-guide "Angular Update Guide | Angular" [GetbootstrapDocs40GettingStartedIntroduction]: https://getbootstrap.com/docs/4.0/getting-started/introduction "Introduction | Bootstrap" [NpmjsMain]: https://www.npmjs.com "npm" [YarnpkgMain]: https://yarnpkg.com " Yarn"
{ "commit_id": "cb34e406ba", "end_byte": 7431, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/libraries/using-libraries.md" }
angular/adev/src/content/tools/libraries/BUILD.bazel_0_287
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "libraries", srcs = glob([ "*.md", ]), data = [ "//adev/src/content/examples/angular-linker-plugin:webpack.config.mjs", ], visibility = ["//adev:__subpackages__"], )
{ "commit_id": "cb34e406ba", "end_byte": 287, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/libraries/BUILD.bazel" }
angular/adev/src/content/tools/cli/environments.md_0_7269
# Configuring application environments You can define different named build configurations for your project, such as `development` and `staging`, with different defaults. Each named configuration can have defaults for any of the options that apply to the various builder targets, such as `build`, `serve`, and `test`. The [Angular CLI](tools/cli) `build`, `serve`, and `test` commands can then replace files with appropriate versions for your intended target environment. ## Angular CLI configurations Angular CLI builders support a `configurations` object, which allows overwriting specific options for a builder based on the configuration provided on the command line. <docs-code language="json"> { "projects": { "my-app": { "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { // By default, disable source map generation. "sourceMap": false }, "configurations": { // For the `debug` configuration, enable source maps. "debug": { "sourceMap": true } } }, … } } } } </docs-code> You can choose which configuration to use with the `--configuration` option. <docs-code language="shell"> ng build --configuration debug </docs-code> Configurations can be applied to any Angular CLI builder. Multiple configurations can be specified with a comma separator. The configurations are applied in order, with conflicting options using the value from the last configuration. <docs-code language="shell"> ng build --configuration debug,production,customer-facing </docs-code> ## Configure environment-specific defaults `@angular-devkit/build-angular:browser` supports file replacements, an option for substituting source files before executing a build. Using this in combination with `--configuration` provides a mechanism for configuring environment-specific data in your application. Start by [generating environments](cli/generate/environments) to create the `src/environments/` directory and configure the project to use file replacements. <docs-code language="shell"> ng generate environments </docs-code> The project's `src/environments/` directory contains the base configuration file, `environment.ts`, which provides the default configuration for production. You can override default values for additional environments, such as `development` and `staging`, in target-specific configuration files. For example: <docs-code language="text"> my-app/src/environments ├── environment.development.ts ├── environment.staging.ts └── environment.ts </docs-code> The base file `environment.ts`, contains the default environment settings. For example: <docs-code language="typescript"> export const environment = { production: true }; </docs-code> The `build` command uses this as the build target when no environment is specified. You can add further variables, either as additional properties on the environment object, or as separate objects. For example, the following adds a default for a variable to the default environment: <docs-code language="typescript"> export const environment = { production: true, apiUrl: 'http://my-prod-url' }; </docs-code> You can add target-specific configuration files, such as `environment.development.ts`. The following content sets default values for the development build target: <docs-code language="typescript"> export const environment = { production: false, apiUrl: 'http://my-dev-url' }; </docs-code> ## Using environment-specific variables in your app To use the environment configurations you have defined, your components must import the original environments file: <docs-code language="typescript"> import { environment } from './environments/environment'; </docs-code> This ensures that the build and serve commands can find the configurations for specific build targets. The following code in the component file (`app.component.ts`) uses an environment variable defined in the configuration files. <docs-code language="typescript"> import { environment } from './../environments/environment'; // Fetches from `http://my-prod-url` in production, `http://my-dev-url` in development. fetch(environment.apiUrl); </docs-code> The main CLI configuration file, `angular.json`, contains a `fileReplacements` section in the configuration for each build target, which lets you replace any file in the TypeScript program with a target-specific version of that file. This is useful for including target-specific code or variables in a build that targets a specific environment, such as production or staging. By default no files are replaced, however `ng generate environments` sets up this configuration automatically. You can change or add file replacements for specific build targets by editing the `angular.json` configuration directly. <docs-code language="json"> "configurations": { "development": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.development.ts" } ], … </docs-code> This means that when you build your development configuration with `ng build --configuration development`, the `src/environments/environment.ts` file is replaced with the target-specific version of the file, `src/environments/environment.development.ts`. To add a staging environment, create a copy of `src/environments/environment.ts` called `src/environments/environment.staging.ts`, then add a `staging` configuration to `angular.json`: <docs-code language="json"> "configurations": { "development": { … }, "production": { … }, "staging": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.staging.ts" } ] } } </docs-code> You can add more configuration options to this target environment as well. Any option that your build supports can be overridden in a build target configuration. To build using the staging configuration, run the following command: <docs-code language="shell"> ng build --configuration staging </docs-code> By default, the `build` target includes `production` and `development` configurations and `ng serve` uses the development build of the application. You can also configure `ng serve` to use the targeted build configuration if you set the `buildTarget` option: <docs-code language="json"> "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { … }, "configurations": { "development": { // Use the `development` configuration of the `build` target. "buildTarget": "my-app:build:development" }, "production": { // Use the `production` configuration of the `build` target. "buildTarget": "my-app:build:production" } }, "defaultConfiguration": "development" }, </docs-code> The `defaultConfiguration` option specifies which configuration is used by default. When `defaultConfiguration` is not set, `options` are used directly without modification.
{ "commit_id": "cb34e406ba", "end_byte": 7269, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/environments.md" }
angular/adev/src/content/tools/cli/overview.md_0_2595
# The Angular CLI The Angular CLI is a command-line interface tool which allows you to scaffold, develop, test, deploy, and maintain Angular applications directly from a command shell. Angular CLI is published on npm as the `@angular/cli` package and includes a binary named `ng`. Commands invoking `ng` are using the Angular CLI. <docs-callout title="Try Angular without local setup"> If you are new to Angular, you might want to start with [Try it now!](tutorials/learn-angular), which introduces the essentials of Angular in the context of a ready-made basic online store app for you to examine and modify. This standalone tutorial takes advantage of the interactive [StackBlitz](https://stackblitz.com) environment for online development. You don't need to set up your local environment until you're ready. </docs-callout> <docs-card-container> <docs-card title="Getting Started" link="Get Started" href="tools/cli/setup-local"> Install Angular CLI to create and build your first app. </docs-card> <docs-card title="Command Reference" link="Learn More" href="cli"> Discover CLI commands to make you more productive with Angular. </docs-card> <docs-card title="Schematics" link="Learn More" href="tools/cli/schematics"> Create and run schematics to generate and modify source files in your application automatically. </docs-card> <docs-card title="Builders" link="Learn More" href="tools/cli/cli-builder"> Create and run builders to perform complex transformations from your source code to generated build outputs. </docs-card> </docs-card-container> ## CLI command-language syntax Angular CLI roughly follows Unix/POSIX conventions for option syntax. ### Boolean options Boolean options have two forms: `--this-option` sets the flag to `true`, `--no-this-option` sets it to `false`. You can also use `--this-option=false` or `--this-option=true`. If neither option is supplied, the flag remains in its default state, as listed in the reference documentation. ### Array options Array options can be provided in two forms: `--option value1 value2` or `--option value1 --option value2`. ### Key/value options Some options like `--define` expect an array of `key=value` pairs as their values. Just like array options, key/value options can be provided in two forms: `--define 'KEY_1="value1"' KEY_2=true` or `--define 'KEY_1="value1"' --define KEY_2=true`. ### Relative paths Options that specify files can be given as absolute paths, or as paths relative to the current working directory, which is generally either the workspace or project root.
{ "commit_id": "cb34e406ba", "end_byte": 2595, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/overview.md" }
angular/adev/src/content/tools/cli/schematics-for-libraries.md_0_6077
# Schematics for libraries When you create an Angular library, you can provide and package it with schematics that integrate it with the Angular CLI. With your schematics, your users can use `ng add` to install an initial version of your library, `ng generate` to create artifacts defined in your library, and `ng update` to adjust their project for a new version of your library that introduces breaking changes. All three types of schematics can be part of a collection that you package with your library. ## Creating a schematics collection To start a collection, you need to create the schematic files. The following steps show you how to add initial support without modifying any project files. 1. In your library's root folder, create a `schematics` folder. 1. In the `schematics/` folder, create an `ng-add` folder for your first schematic. 1. At the root level of the `schematics` folder, create a `collection.json` file. 1. Edit the `collection.json` file to define the initial schema for your collection. <docs-code header="projects/my-lib/schematics/collection.json (Schematics Collection)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/collection.1.json"/> * The `$schema` path is relative to the Angular Devkit collection schema. * The `schematics` object describes the named schematics that are part of this collection. * The first entry is for a schematic named `ng-add`. It contains the description, and points to the factory function that is called when your schematic is executed. 1. In your library project's `package.json` file, add a "schematics" entry with the path to your schema file. The Angular CLI uses this entry to find named schematics in your collection when it runs commands. <docs-code header="projects/my-lib/package.json (Schematics Collection Reference)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/package.json" visibleRegion="collection"/> The initial schema that you have created tells the CLI where to find the schematic that supports the `ng add` command. Now you are ready to create that schematic. ## Providing installation support A schematic for the `ng add` command can enhance the initial installation process for your users. The following steps define this type of schematic. 1. Go to the `<lib-root>/schematics/ng-add` folder. 1. Create the main file, `index.ts`. 1. Open `index.ts` and add the source code for your schematic factory function. <docs-code header="projects/my-lib/schematics/ng-add/index.ts (ng-add Rule Factory)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/ng-add/index.ts"/> The Angular CLI will install the latest version of the library automatically, and this example is taking it a step further by adding the `MyLibModule` to the root of the application. The `addRootImport` function accepts a callback that needs to return a code block. You can write any code inside of the string tagged with the `code` function and any external symbol have to be wrapped with the `external` function to ensure that the appropriate import statements are generated. ### Define dependency type Use the `save` option of `ng-add` to configure if the library should be added to the `dependencies`, the `devDependencies`, or not saved at all in the project's `package.json` configuration file. <docs-code header="projects/my-lib/package.json (ng-add Reference)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/package.json" visibleRegion="ng-add"/> Possible values are: | Values | Details | |:--- |:--- | | `false` | Don't add the package to `package.json` | | `true` | Add the package to the dependencies | | `"dependencies"` | Add the package to the dependencies | | `"devDependencies"` | Add the package to the devDependencies | ## Building your schematics To bundle your schematics together with your library, you must configure the library to build the schematics separately, then add them to the bundle. You must build your schematics *after* you build your library, so they are placed in the correct directory. * Your library needs a custom Typescript configuration file with instructions on how to compile your schematics into your distributed library * To add the schematics to the library bundle, add scripts to the library's `package.json` file Assume you have a library project `my-lib` in your Angular workspace. To tell the library how to build the schematics, add a `tsconfig.schematics.json` file next to the generated `tsconfig.lib.json` file that configures the library build. 1. Edit the `tsconfig.schematics.json` file to add the following content. <docs-code header="projects/my-lib/tsconfig.schematics.json (TypeScript Config)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/tsconfig.schematics.json"/> | Options | Details | |:--- |:--- | | `rootDir` | Specifies that your `schematics` folder contains the input files to be compiled. | | `outDir` | Maps to the library's output folder. By default, this is the `dist/my-lib` folder at the root of your workspace. | 1. To make sure your schematics source files get compiled into the library bundle, add the following scripts to the `package.json` file in your library project's root folder \(`projects/my-lib`\). <docs-code header="projects/my-lib/package.json (Build Scripts)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/package.json"/> * The `build` script compiles your schematic using the custom `tsconfig.schematics.json` file * The `postbuild` script copies the schematic files after the `build` script completes * Both the `build` and the `postbuild` scripts require the `copyfiles` and `typescript` dependencies. To install the dependencies, navigate to the path defined in `devDependencies` and run `npm install` before you run the scripts.
{ "commit_id": "cb34e406ba", "end_byte": 6077, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/schematics-for-libraries.md" }
angular/adev/src/content/tools/cli/schematics-for-libraries.md_6077_12002
## Providing generation support You can add a named schematic to your collection that lets your users use the `ng generate` command to create an artifact that is defined in your library. We'll assume that your library defines a service, `my-service`, that requires some setup. You want your users to be able to generate it using the following CLI command. <docs-code language="shell"> ng generate my-lib:my-service </docs-code> To begin, create a new subfolder, `my-service`, in the `schematics` folder. ### Configure the new schematic When you add a schematic to the collection, you have to point to it in the collection's schema, and provide configuration files to define options that a user can pass to the command. 1. Edit the `schematics/collection.json` file to point to the new schematic subfolder, and include a pointer to a schema file that specifies inputs for the new schematic. <docs-code header="projects/my-lib/schematics/collection.json (Schematics Collection)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/collection.json"/> 1. Go to the `<lib-root>/schematics/my-service` folder. 1. Create a `schema.json` file and define the available options for the schematic. <docs-code header="projects/my-lib/schematics/my-service/schema.json (Schematic JSON Schema)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/schema.json"/> * *id*: A unique ID for the schema in the collection. * *title*: A human-readable description of the schema. * *type*: A descriptor for the type provided by the properties. * *properties*: An object that defines the available options for the schematic. Each option associates key with a type, description, and optional alias. The type defines the shape of the value you expect, and the description is displayed when the user requests usage help for your schematic. See the workspace schema for additional customizations for schematic options. 1. Create a `schema.ts` file and define an interface that stores the values of the options defined in the `schema.json` file. <docs-code header="projects/my-lib/schematics/my-service/schema.ts (Schematic Interface)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/schema.ts"/> | Options | Details | |:--- |:--- | | name | The name you want to provide for the created service. | | path | Overrides the path provided to the schematic. The default path value is based on the current working directory. | | project | Provides a specific project to run the schematic on. In the schematic, you can provide a default if the option is not provided by the user. | ### Add template files To add artifacts to a project, your schematic needs its own template files. Schematic templates support special syntax to execute code and variable substitution. 1. Create a `files/` folder inside the `schematics/my-service/` folder. 1. Create a file named `__name@dasherize__.service.ts.template` that defines a template to use for generating files. This template will generate a service that already has Angular's `HttpClient` injected into its constructor. <docs-code lang="typescript" header="projects/my-lib/schematics/my-service/files/__name@dasherize__.service.ts.template (Schematic Template)"> import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class <%= classify(name) %>Service { constructor(private http: HttpClient) { } } </docs-code> * The `classify` and `dasherize` methods are utility functions that your schematic uses to transform your source template and filename. * The `name` is provided as a property from your factory function. It is the same `name` you defined in the schema. ### Add the factory function Now that you have the infrastructure in place, you can define the main function that performs the modifications you need in the user's project. The Schematics framework provides a file templating system, which supports both path and content templates. The system operates on placeholders defined inside files or paths that loaded in the input `Tree`. It fills these in using values passed into the `Rule`. For details of these data structures and syntax, see the [Schematics README](https://github.com/angular/angular-cli/blob/main/packages/angular_devkit/schematics/README.md). 1. Create the main file `index.ts` and add the source code for your schematic factory function. 1. First, import the schematics definitions you will need. The Schematics framework offers many utility functions to create and use rules when running a schematic. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Imports)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="schematics-imports"/> 1. Import the defined schema interface that provides the type information for your schematic's options. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Schema Import)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="schema-imports"/> 1. To build up the generation schematic, start with an empty rule factory. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Initial Rule)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.1.ts" visibleRegion="factory"/> This rule factory returns the tree without modification. The options are the option values passed through from the `ng generate` command.
{ "commit_id": "cb34e406ba", "end_byte": 12002, "start_byte": 6077, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/schematics-for-libraries.md" }
angular/adev/src/content/tools/cli/schematics-for-libraries.md_12002_18919
## Define a generation rule You now have the framework in place for creating the code that actually modifies the user's application to set it up for the service defined in your library. The Angular workspace where the user installed your library contains multiple projects \(applications and libraries\). The user can specify the project on the command line, or let it default. In either case, your code needs to identify the specific project to which this schematic is being applied, so that you can retrieve information from the project configuration. Do this using the `Tree` object that is passed in to the factory function. The `Tree` methods give you access to the complete file tree in your workspace, letting you read and write files during the execution of the schematic. ### Get the project configuration 1. To determine the destination project, use the `workspaces.readWorkspace` method to read the contents of the workspace configuration file, `angular.json`. To use `workspaces.readWorkspace` you need to create a `workspaces.WorkspaceHost` from the `Tree`. Add the following code to your factory function. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Schema Import)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="workspace"/> Be sure to check that the context exists and throw the appropriate error. 1. Now that you have the project name, use it to retrieve the project-specific configuration information. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Project)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="project-info"/> The `workspace.projects` object contains all the project-specific configuration information. 1. The `options.path` determines where the schematic template files are moved to once the schematic is applied. The `path` option in the schematic's schema is substituted by default with the current working directory. If the `path` is not defined, use the `sourceRoot` from the project configuration along with the `projectType`. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Project Info)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="path"/> ### Define the rule A `Rule` can use external template files, transform them, and return another `Rule` object with the transformed template. Use the templating to generate any custom files required for your schematic. 1. Add the following code to your factory function. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Template transform)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="template"/> | Methods | Details | |:--- |:--- | | `apply()` | Applies multiple rules to a source and returns the transformed source. It takes 2 arguments, a source and an array of rules. | | `url()` | Reads source files from your filesystem, relative to the schematic. | | `applyTemplates()` | Receives an argument of methods and properties you want make available to the schematic template and the schematic filenames. It returns a `Rule`. This is where you define the `classify()` and `dasherize()` methods, and the `name` property. | | `classify()` | Takes a value and returns the value in title case. For example, if the provided name is `my service`, it is returned as `MyService`. | | `dasherize()` | Takes a value and returns the value in dashed and lowercase. For example, if the provided name is MyService, it is returned as `my-service`. | | `move()` | Moves the provided source files to their destination when the schematic is applied. | 1. Finally, the rule factory must return a rule. <docs-code header="projects/my-lib/schematics/my-service/index.ts (Chain Rule)" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts" visibleRegion="chain"/> The `chain()` method lets you combine multiple rules into a single rule, so that you can perform multiple operations in a single schematic. Here you are only merging the template rules with any code executed by the schematic. See a complete example of the following schematic rule function. <docs-code header="projects/my-lib/schematics/my-service/index.ts" path="adev/src/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts"/> For more information about rules and utility methods, see [Provided Rules](https://github.com/angular/angular-cli/tree/main/packages/angular_devkit/schematics#provided-rules). ## Running your library schematic After you build your library and schematics, you can install the schematics collection to run against your project. The following steps show you how to generate a service using the schematic you created earlier. ### Build your library and schematics From the root of your workspace, run the `ng build` command for your library. <docs-code language="shell"> ng build my-lib </docs-code> Then, you change into your library directory to build the schematic <docs-code language="shell"> cd projects/my-lib npm run build </docs-code> ### Link the library Your library and schematics are packaged and placed in the `dist/my-lib` folder at the root of your workspace. For running the schematic, you need to link the library into your `node_modules` folder. From the root of your workspace, run the `npm link` command with the path to your distributable library. <docs-code language="shell"> npm link dist/my-lib </docs-code> ### Run the schematic Now that your library is installed, run the schematic using the `ng generate` command. <docs-code language="shell"> ng generate my-lib:my-service --name my-data </docs-code> In the console, you see that the schematic was run and the `my-data.service.ts` file was created in your application folder. <docs-code language="shell" hideCopy> CREATE src/app/my-data.service.ts (208 bytes) </docs-code>
{ "commit_id": "cb34e406ba", "end_byte": 18919, "start_byte": 12002, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/schematics-for-libraries.md" }
angular/adev/src/content/tools/cli/setup-local.md_0_6110
# Setting up the local environment and workspace This guide explains how to set up your environment for Angular development using the [Angular CLI](cli "CLI command reference"). It includes information about installing the CLI, creating an initial workspace and starter app, and running that app locally to verify your setup. <docs-callout title="Try Angular without local setup"> If you are new to Angular, you might want to start with [Try it now!](tutorials/learn-angular), which introduces the essentials of Angular in your browser. This standalone tutorial takes advantage of the interactive [StackBlitz](https://stackblitz.com) environment for online development. You don't need to set up your local environment until you're ready. </docs-callout> ## Before you start To use Angular CLI, you should be familiar with the following: <docs-pill-row> <docs-pill href="https://developer.mozilla.org/docs/Web/JavaScript/A_re-introduction_to_JavaScript" title="JavaScript"/> <docs-pill href="https://developer.mozilla.org/docs/Learn/HTML/Introduction_to_HTML" title="HTML"/> <docs-pill href="https://developer.mozilla.org/docs/Learn/CSS/First_steps" title="CSS"/> </docs-pill-row> You should also be familiar with usage of command line interface (CLI) tools and have a general understanding of command shells. Knowledge of [TypeScript](https://www.typescriptlang.org) is helpful, but not required. ## Dependencies To install Angular CLI on your local system, you need to install [Node.js](https://nodejs.org/). Angular CLI uses Node and its associated package manager, npm, to install and run JavaScript tools outside the browser. [Download and install Node.js](https://nodejs.org/en/download), which will include the `npm` CLI as well. Angular requires an [active LTS or maintenance LTS](https://nodejs.org/en/about/previous-releases) version of Node.js. See [Angular's version compatibility](reference/versions) guide for more information. ## Install the Angular CLI To install the Angular CLI, open a terminal window and run the following command: <docs-code language="shell"> npm install -g @angular/cli </docs-code> ### Powershell execution policy On Windows client computers, the execution of PowerShell scripts is disabled by default, so the above command may fail with an error. To allow the execution of PowerShell scripts, which is needed for npm global binaries, you must set the following <a href="https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_execution_policies">execution policy</a>: <docs-code language="sh"> Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned </docs-code> Carefully read the message displayed after executing the command and follow the instructions. Make sure you understand the implications of setting an execution policy. ### Unix permissions On some Unix-like setups, global npm scripts may be owned by the root user, so to the above command may fail with a permission error. Run with `sudo` to execute the command as the root user and enter your password when prompted: <docs-code language="sh"> sudo npm install -g @angular/cli </docs-code> Make sure you understand the implications of running commands as root. ## Create a workspace and initial application You develop apps in the context of an Angular **workspace**. To create a new workspace and initial starter app, run the CLI command `ng new` and provide the name `my-app`, as shown here, then answer prompts about features to include: <docs-code language="shell"> ng new my-app </docs-code> The Angular CLI installs the necessary Angular npm packages and other dependencies. This can take a few minutes. The CLI creates a new workspace and a small welcome app in a new directory with the same name as the workspace, ready to run. Navigate to the new directory so subsequent commands use this workspace. <docs-code language="shell"> cd my-app </docs-code> ## Run the application The Angular CLI includes a development server, for you to build and serve your app locally. Run the following command: <docs-code language="shell"> ng serve --open </docs-code> The `ng serve` command launches the server, watches your files, as well as rebuilds the app and reloads the browser as you make changes to those files. The `--open` (or just `-o`) option automatically opens your browser to `http://localhost:4200/` to view the generated application. ## Workspaces and project files The [`ng new`](cli/new) command creates an [Angular workspace](reference/configs/workspace-config) folder and generates a new application inside it. A workspace can contain multiple applications and libraries. The initial application created by the [`ng new`](cli/new) command is at the root directory of the workspace. When you generate an additional application or library in an existing workspace, it goes into a `projects/` subfolder by default. A newly generated application contains the source files for a root component and template. Each application has a `src` folder that contains its components, data, and assets. You can edit the generated files directly, or add to and modify them using CLI commands. Use the [`ng generate`](cli/generate) command to add new files for additional components, directives, pipes, services, and more. Commands such as [`ng add`](cli/add) and [`ng generate`](cli/generate), which create or operate on applications and libraries, must be executed from within a workspace. By contrast, commands such as `ng new` must be executed *outside* a workspace because they will create a new one. ## Next steps * Learn more about the [file structure](reference/configs/file-structure) and [configuration](reference/configs/workspace-config) of the generated workspace. * Test your new application with [`ng test`](cli/test). * Generate boilerplate like components, directives, and pipes with [`ng generate`](cli/generate). * Deploy your new application and make it available to real users with [`ng deploy`](cli/deploy). * Set up and run end-to-end tests of your application with [`ng e2e`](cli/e2e).
{ "commit_id": "cb34e406ba", "end_byte": 6110, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/setup-local.md" }
angular/adev/src/content/tools/cli/schematics.md_0_7829
# Generating code using schematics A schematic is a template-based code generator that supports complex logic. It is a set of instructions for transforming a software project by generating or modifying code. Schematics are packaged into collections and installed with npm. The schematic collection can be a powerful tool for creating, modifying, and maintaining any software project, but is particularly useful for customizing Angular projects to suit the particular needs of your own organization. You might use schematics, for example, to generate commonly-used UI patterns or specific components, using predefined templates or layouts. Use schematics to enforce architectural rules and conventions, making your projects consistent and interoperative. ## Schematics for the Angular CLI Schematics are part of the Angular ecosystem. The Angular CLI uses schematics to apply transforms to a web-app project. You can modify these schematics, and define new ones to do things like update your code to fix breaking changes in a dependency, for example, or to add a new configuration option or framework to an existing project. Schematics that are included in the `@schematics/angular` collection are run by default by the commands `ng generate` and `ng add`. The package contains named schematics that configure the options that are available to the CLI for `ng generate` sub-commands, such as `ng generate component` and `ng generate service`. The sub-commands for `ng generate` are shorthand for the corresponding schematic. To specify and generate a particular schematic, or a collection of schematics, using the long form: <docs-code language="shell"> ng generate my-schematic-collection:my-schematic-name </docs-code> or <docs-code language="shell"> ng generate my-schematic-name --collection collection-name </docs-code> ### Configuring CLI schematics A JSON schema associated with a schematic tells the Angular CLI what options are available to commands and sub-commands, and determines the defaults. These defaults can be overridden by providing a different value for an option on the command line. See [Workspace Configuration](reference/configs/workspace-config) for information about how to change the generation option defaults for your workspace. The JSON schemas for the default schematics used by the CLI to generate projects and parts of projects are collected in the package [`@schematics/angular`](https://github.com/angular/angular-cli/tree/main/packages/schematics/angular). The schema describes the options available to the CLI for each of the `ng generate` sub-commands, as shown in the `--help` output. ## Developing schematics for libraries As a library developer, you can create your own collections of custom schematics to integrate your library with the Angular CLI. * An *add schematic* lets developers install your library in an Angular workspace using `ng add` * *Generation schematics* can tell the `ng generate` sub-commands how to modify projects, add configurations and scripts, and scaffold artifacts that are defined in your library * An *update schematic* can tell the `ng update` command how to update your library's dependencies and adjust for breaking changes when you release a new version For more details of what these look like and how to create them, see: <docs-pill-row> <docs-pill href="tools/cli/schematics-authoring" title="Authoring Schematics"/> <docs-pill href="tools/cli/schematics-for-libraries" title="Schematics for Libraries"/> </docs-pill-row> ### Add schematics An *add schematic* is typically supplied with a library, so that the library can be added to an existing project with `ng add`. The `add` command uses your package manager to download new dependencies, and invokes an installation script that is implemented as a schematic. For example, the [`@angular/material`](https://material.angular.io/guide/schematics) schematic tells the `add` command to install and set up Angular Material and theming, and register new starter components that can be created with `ng generate`. Look at this one as an example and model for your own add schematic. Partner and third party libraries also support the Angular CLI with add schematics. For example, `@ng-bootstrap/schematics` adds [ng-bootstrap](https://ng-bootstrap.github.io) to an app, and `@clr/angular` installs and sets up [Clarity from VMWare](https://clarity.design/documentation/get-started). An *add schematic* can also update a project with configuration changes, add additional dependencies \(such as polyfills\), or scaffold package-specific initialization code. For example, the `@angular/pwa` schematic turns your application into a PWA by adding an application manifest and service worker. ### Generation schematics Generation schematics are instructions for the `ng generate` command. The documented sub-commands use the default Angular generation schematics, but you can specify a different schematic \(in place of a sub-command\) to generate an artifact defined in your library. Angular Material, for example, supplies generation schematics for the UI components that it defines. The following command uses one of these schematics to render an Angular Material `<mat-table>` that is pre-configured with a datasource for sorting and pagination. <docs-code language="shell"> ng generate @angular/material:table <component-name> </docs-code> ### Update schematics The `ng update` command can be used to update your workspace's library dependencies. If you supply no options or use the help option, the command examines your workspace and suggests libraries to update. <docs-code language="shell"> ng update We analyzed your package.json, there are some packages to update: Name Version Command to update &hyphen;------------------------------------------------------------------------------- @angular/cdk 7.2.2 -> 7.3.1 ng update @angular/cdk @angular/cli 7.2.3 -> 7.3.0 ng update @angular/cli @angular/core 7.2.2 -> 7.2.3 ng update @angular/core @angular/material 7.2.2 -> 7.3.1 ng update @angular/material rxjs 6.3.3 -> 6.4.0 ng update rxjs There might be additional packages that are outdated. Run "ng update --all" to try to update all at the same time. </docs-code> If you pass the command a set of libraries to update \(or the `--all` flag\), it updates those libraries, their peer dependencies, and the peer dependencies that depend on them. HELPFUL: If there are inconsistencies \(for example, if peer dependencies cannot be matched by a simple [semver](https://semver.io) range\), the command generates an error and does not change anything in the workspace. We recommend that you do not force an update of all dependencies by default. Try updating specific dependencies first. For more about how the `ng update` command works, see [Update Command](https://github.com/angular/angular-cli/blob/main/docs/specifications/update.md). If you create a new version of your library that introduces potential breaking changes, you can provide an *update schematic* to enable the `ng update` command to automatically resolve any such changes in the project being updated. For example, suppose you want to update the Angular Material library. <docs-code language="shell"> ng update @angular/material </docs-code> This command updates both `@angular/material` and its dependency `@angular/cdk` in your workspace's `package.json`. If either package contains an update schematic that covers migration from the existing version to a new version, the command runs that schematic on your workspace.
{ "commit_id": "cb34e406ba", "end_byte": 7829, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/schematics.md" }
angular/adev/src/content/tools/cli/template-typecheck.md_0_3821
# Template type checking ## Overview of template type checking Just as TypeScript catches type errors in your code, Angular checks the expressions and bindings within the templates of your application and can report any type errors it finds. Angular currently has three modes of doing this, depending on the value of the `fullTemplateTypeCheck` and `strictTemplates` flags in [Angular's compiler options](reference/configs/angular-compiler-options). ### Basic mode In the most basic type-checking mode, with the `fullTemplateTypeCheck` flag set to `false`, Angular validates only top-level expressions in a template. If you write `<map [city]="user.address.city">`, the compiler verifies the following: * `user` is a property on the component class * `user` is an object with an address property * `user.address` is an object with a city property The compiler does not verify that the value of `user.address.city` is assignable to the city input of the `<map>` component. The compiler also has some major limitations in this mode: * Importantly, it doesn't check embedded views, such as `*ngIf`, `*ngFor`, other `<ng-template>` embedded view. * It doesn't figure out the types of `#refs`, the results of pipes, or the type of `$event` in event bindings. In many cases, these things end up as type `any`, which can cause subsequent parts of the expression to go unchecked. ### Full mode If the `fullTemplateTypeCheck` flag is set to `true`, Angular is more aggressive in its type-checking within templates. In particular: * Embedded views \(such as those within an `*ngIf` or `*ngFor`\) are checked * Pipes have the correct return type * Local references to directives and pipes have the correct type \(except for any generic parameters, which will be `any`\) The following still have type `any`. * Local references to DOM elements * The `$event` object * Safe navigation expressions IMPORTANT: The `fullTemplateTypeCheck` flag has been deprecated in Angular 13. The `strictTemplates` family of compiler options should be used instead. ### Strict mode Angular maintains the behavior of the `fullTemplateTypeCheck` flag, and introduces a third "strict mode". Strict mode is a superset of full mode, and is accessed by setting the `strictTemplates` flag to true. This flag supersedes the `fullTemplateTypeCheck` flag. In addition to the full mode behavior, Angular does the following: * Verifies that component/directive bindings are assignable to their `@Input()`s * Obeys TypeScript's `strictNullChecks` flag when validating the preceding mode * Infers the correct type of components/directives, including generics * Infers template context types where configured \(for example, allowing correct type-checking of `NgFor`\) * Infers the correct type of `$event` in component/directive, DOM, and animation event bindings * Infers the correct type of local references to DOM elements, based on the tag name \(for example, the type that `document.createElement` would return for that tag\) ## Checking of `*ngFor` The three modes of type-checking treat embedded views differently. Consider the following example. <docs-code language="typescript" header="User interface"> interface User { name: string; address: { city: string; state: string; } } </docs-code> <docs-code language="html"> <div *ngFor="let user of users"> <h2>{{config.title}}</h2> <span>City: {{user.address.city}}</span> </div> </docs-code> The `<h2>` and the `<span>` are in the `*ngFor` embedded view. In basic mode, Angular doesn't check either of them. However, in full mode, Angular checks that `config` and `user` exist and assumes a type of `any`. In strict mode, Angular knows that the `user` in the `<span>` has a type of `User`, and that `address` is an object with a `city` property of type `string`.
{ "commit_id": "cb34e406ba", "end_byte": 3821, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/template-typecheck.md" }
angular/adev/src/content/tools/cli/template-typecheck.md_3821_11008
## Troubleshooting template errors With strict mode, you might encounter template errors that didn't arise in either of the previous modes. These errors often represent genuine type mismatches in the templates that were not caught by the previous tooling. If this is the case, the error message should make it clear where in the template the problem occurs. There can also be false positives when the typings of an Angular library are either incomplete or incorrect, or when the typings don't quite line up with expectations as in the following cases. * When a library's typings are wrong or incomplete \(for example, missing `null | undefined` if the library was not written with `strictNullChecks` in mind\) * When a library's input types are too narrow and the library hasn't added appropriate metadata for Angular to figure this out. This usually occurs with disabled or other common Boolean inputs used as attributes, for example, `<input disabled>`. * When using `$event.target` for DOM events \(because of the possibility of event bubbling, `$event.target` in the DOM typings doesn't have the type you might expect\) In case of a false positive like these, there are a few options: * Use the `$any()` type-cast function in certain contexts to opt out of type-checking for a part of the expression * Disable strict checks entirely by setting `strictTemplates: false` in the application's TypeScript configuration file, `tsconfig.json` * Disable certain type-checking operations individually, while maintaining strictness in other aspects, by setting a *strictness flag* to `false` * If you want to use `strictTemplates` and `strictNullChecks` together, opt out of strict null type checking specifically for input bindings using `strictNullInputTypes` Unless otherwise commented, each following option is set to the value for `strictTemplates` \(`true` when `strictTemplates` is `true` and conversely, the other way around\). | Strictness flag | Effect | |:--- |:--- | | `strictInputTypes` | Whether the assignability of a binding expression to the `@Input()` field is checked. Also affects the inference of directive generic types. | | `strictInputAccessModifiers` | Whether access modifiers such as `private`/`protected`/`readonly` are honored when assigning a binding expression to an `@Input()`. If disabled, the access modifiers of the `@Input` are ignored; only the type is checked. This option is `false` by default, even with `strictTemplates` set to `true`. | | `strictNullInputTypes` | Whether `strictNullChecks` is honored when checking `@Input()` bindings \(per `strictInputTypes`\). Turning this off can be useful when using a library that was not built with `strictNullChecks` in mind. | | `strictAttributeTypes` | Whether to check `@Input()` bindings that are made using text attributes. For example, <docs-code hideCopy language="html"> <input matInput disabled="true"> </docs-code> \(setting the `disabled` property to the string `'true'`\) vs <docs-code hideCopy language="html"> <input matInput [disabled]="true"> </docs-code> \(setting the `disabled` property to the boolean `true`\). | | `strictSafeNavigationTypes` | Whether the return type of safe navigation operations \(for example, `user?.name` will be correctly inferred based on the type of `user`\). If disabled, `user?.name` will be of type `any`. | | `strictDomLocalRefTypes` | Whether local references to DOM elements will have the correct type. If disabled `ref` will be of type `any` for `<input #ref>`. | | `strictOutputEventTypes` | Whether `$event` will have the correct type for event bindings to component/directive an `@Output()`, or to animation events. If disabled, it will be `any`. | | `strictDomEventTypes` | Whether `$event` will have the correct type for event bindings to DOM events. If disabled, it will be `any`. | | `strictContextGenerics` | Whether the type parameters of generic components will be inferred correctly \(including any generic bounds\). If disabled, any type parameters will be `any`. | | `strictLiteralTypes` | Whether object and array literals declared in the template will have their type inferred. If disabled, the type of such literals will be `any`. This flag is `true` when *either* `fullTemplateTypeCheck` or `strictTemplates` is set to `true`. | If you still have issues after troubleshooting with these flags, fall back to full mode by disabling `strictTemplates`. If that doesn't work, an option of last resort is to turn off full mode entirely with `fullTemplateTypeCheck: false`. A type-checking error that you cannot resolve with any of the recommended methods can be the result of a bug in the template type-checker itself. If you get errors that require falling back to basic mode, it is likely to be such a bug. If this happens, [file an issue](https://github.com/angular/angular/issues) so the team can address it.
{ "commit_id": "cb34e406ba", "end_byte": 11008, "start_byte": 3821, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/template-typecheck.md" }
angular/adev/src/content/tools/cli/template-typecheck.md_11008_19189
## Inputs and type-checking The template type checker checks whether a binding expression's type is compatible with that of the corresponding directive input. As an example, consider the following component: <docs-code language="typescript"> export interface User { name: string; } @Component({ selector: 'user-detail', template: '{{ user.name }}', }) export class UserDetailComponent { @Input() user: User; } </docs-code> The `AppComponent` template uses this component as follows: <docs-code language="typescript"> @Component({ selector: 'app-root', template: '<user-detail [user]="selectedUser"></user-detail>', }) export class AppComponent { selectedUser: User | null = null; } </docs-code> Here, during type checking of the template for `AppComponent`, the `[user]="selectedUser"` binding corresponds with the `UserDetailComponent.user` input. Therefore, Angular assigns the `selectedUser` property to `UserDetailComponent.user`, which would result in an error if their types were incompatible. TypeScript checks the assignment according to its type system, obeying flags such as `strictNullChecks` as they are configured in the application. Avoid run-time type errors by providing more specific in-template type requirements to the template type checker. Make the input type requirements for your own directives as specific as possible by providing template-guard functions in the directive definition. See [Improving template type checking for custom directives](guide/directives/structural-directives#directive-type-checks) in this guide. ### Strict null checks When you enable `strictTemplates` and the TypeScript flag `strictNullChecks`, typecheck errors might occur for certain situations that might not easily be avoided. For example: * A nullable value that is bound to a directive from a library which did not have `strictNullChecks` enabled. For a library compiled without `strictNullChecks`, its declaration files will not indicate whether a field can be `null` or not. For situations where the library handles `null` correctly, this is problematic, as the compiler will check a nullable value against the declaration files which omit the `null` type. As such, the compiler produces a type-check error because it adheres to `strictNullChecks`. * Using the `async` pipe with an Observable which you know will emit synchronously. The `async` pipe currently assumes that the Observable it subscribes to can be asynchronous, which means that it's possible that there is no value available yet. In that case, it still has to return something —which is `null`. In other words, the return type of the `async` pipe includes `null`, which might result in errors in situations where the Observable is known to emit a non-nullable value synchronously. There are two potential workarounds to the preceding issues: * In the template, include the non-null assertion operator `!` at the end of a nullable expression, such as <docs-code hideCopy language="html"> <user-detail [user]="user!"></user-detail> </docs-code> In this example, the compiler disregards type incompatibilities in nullability, just as in TypeScript code. In the case of the `async` pipe, notice that the expression needs to be wrapped in parentheses, as in <docs-code hideCopy language="html"> <user-detail [user]="(user$ | async)!"></user-detail> </docs-code> * Disable strict null checks in Angular templates completely. When `strictTemplates` is enabled, it is still possible to disable certain aspects of type checking. Setting the option `strictNullInputTypes` to `false` disables strict null checks within Angular templates. This flag applies for all components that are part of the application. ### Advice for library authors As a library author, you can take several measures to provide an optimal experience for your users. First, enabling `strictNullChecks` and including `null` in an input's type, as appropriate, communicates to your consumers whether they can provide a nullable value or not. Additionally, it is possible to provide type hints that are specific to the template type checker. See [Improving template type checking for custom directives](guide/directives/structural-directives#directive-type-checks), and [Input setter coercion](#input-setter-coercion). ## Input setter coercion Occasionally it is desirable for the `@Input()` of a directive or component to alter the value bound to it, typically using a getter/setter pair for the input. As an example, consider this custom button component: Consider the following directive: <docs-code language="typescript"> @Component({ selector: 'submit-button', template: ` <div class="wrapper"> <button [disabled]="disabled">Submit</button> </div> `, }) class SubmitButton { private _disabled: boolean; @Input() get disabled(): boolean { return this._disabled; } set disabled(value: boolean) { this._disabled = value; } } </docs-code> Here, the `disabled` input of the component is being passed on to the `<button>` in the template. All of this works as expected, as long as a `boolean` value is bound to the input. But, suppose a consumer uses this input in the template as an attribute: <docs-code language="html"> <submit-button disabled></submit-button> </docs-code> This has the same effect as the binding: <docs-code language="html"> <submit-button [disabled]="''"></submit-button> </docs-code> At runtime, the input will be set to the empty string, which is not a `boolean` value. Angular component libraries that deal with this problem often "coerce" the value into the right type in the setter: <docs-code language="typescript"> set disabled(value: boolean) { this._disabled = (value === '') || value; } </docs-code> It would be ideal to change the type of `value` here, from `boolean` to `boolean|''`, to match the set of values which are actually accepted by the setter. TypeScript prior to version 4.3 requires that both the getter and setter have the same type, so if the getter should return a `boolean` then the setter is stuck with the narrower type. If the consumer has Angular's strictest type checking for templates enabled, this creates a problem: the empty string \(`''`\) is not actually assignable to the `disabled` field, which creates a type error when the attribute form is used. As a workaround for this problem, Angular supports checking a wider, more permissive type for `@Input()` than is declared for the input field itself. Enable this by adding a static property with the `ngAcceptInputType_` prefix to the component class: <docs-code language="typescript"> class SubmitButton { private _disabled: boolean; @Input() get disabled(): boolean { return this._disabled; } set disabled(value: boolean) { this._disabled = (value === '') || value; } static ngAcceptInputType_disabled: boolean|''; } </docs-code> Since TypeScript 4.3, the setter could have been declared to accept `boolean|''` as type, making the input setter coercion field obsolete. As such, input setters coercion fields have been deprecated. This field does not need to have a value. Its existence communicates to the Angular type checker that the `disabled` input should be considered as accepting bindings that match the type `boolean|''`. The suffix should be the `@Input` *field* name. Care should be taken that if an `ngAcceptInputType_` override is present for a given input, then the setter should be able to handle any values of the overridden type. ## Disabling type checking using `$any()` Disable checking of a binding expression by surrounding the expression in a call to the `$any()` cast pseudo-function. The compiler treats it as a cast to the `any` type just like in TypeScript when a `<any>` or `as any` cast is used. In the following example, casting `person` to the `any` type suppresses the error `Property address does not exist`. <docs-code language="typescript"> @Component({ selector: 'my-component', template: '{{$any(person).address.street}}' }) class MyComponent { person?: Person; } </docs-code>
{ "commit_id": "cb34e406ba", "end_byte": 19189, "start_byte": 11008, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/template-typecheck.md" }
angular/adev/src/content/tools/cli/aot-compiler.md_0_7525
# Ahead-of-time (AOT) compilation An Angular application consists mainly of components and their HTML templates. Because the components and templates provided by Angular cannot be understood by the browser directly, Angular applications require a compilation process before they can run in a browser. The Angular ahead-of-time (AOT) compiler converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase *before* the browser downloads and runs that code. Compiling your application during the build process provides a faster rendering in the browser. This guide explains how to specify metadata and apply available compiler options to compile your applications efficiently using the AOT compiler. HELPFUL: [Watch Alex Rickabaugh explain the Angular compiler](https://www.youtube.com/watch?v=anphffaCZrQ) at AngularConnect 2019. Here are some reasons you might want to use AOT. | Reasons | Details | |:--- |:--- | | Faster rendering | With AOT, the browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application immediately, without waiting to compile the application first. | | Fewer asynchronous requests | The compiler *inlines* external HTML templates and CSS style sheets within the application JavaScript, eliminating separate ajax requests for those source files. | | Smaller Angular framework download size | There's no need to download the Angular compiler if the application is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload. | | Detect template errors earlier | The AOT compiler detects and reports template binding errors during the build step before users can see them. | | Better security | AOT compiles HTML templates and components into JavaScript files long before they are served to the client. With no templates to read and no risky client-side HTML or JavaScript evaluation, there are fewer opportunities for injection attacks. | ## Choosing a compiler Angular offers two ways to compile your application: | Angular compile | Details | |:--- |:--- | | Just-in-Time \(JIT\) | Compiles your application in the browser at runtime. This was the default until Angular 8. | | Ahead-of-Time \(AOT\) | Compiles your application and libraries at build time. This is the default starting in Angular 9. | When you run the [`ng build`](cli/build) \(build only\) or [`ng serve`](cli/serve) \(build and serve locally\) CLI commands, the type of compilation \(JIT or AOT\) depends on the value of the `aot` property in your build configuration specified in `angular.json`. By default, `aot` is set to `true` for new CLI applications. See the [CLI command reference](cli) and [Building and serving Angular apps](tools/cli/build) for more information. ## How AOT works The Angular AOT compiler extracts **metadata** to interpret the parts of the application that Angular is supposed to manage. You can specify the metadata explicitly in **decorators** such as `@Component()` and `@Input()`, or implicitly in the constructor declarations of the decorated classes. The metadata tells Angular how to construct instances of your application classes and interact with them at runtime. In the following example, the `@Component()` metadata object and the class constructor tell Angular how to create and display an instance of `TypicalComponent`. <docs-code language="typescript"> @Component({ selector: 'app-typical', template: '<div>A typical component for {{data.name}}</div>' }) export class TypicalComponent { @Input() data: TypicalData; constructor(private someService: SomeService) { … } } </docs-code> The Angular compiler extracts the metadata *once* and generates a *factory* for `TypicalComponent`. When it needs to create a `TypicalComponent` instance, Angular calls the factory, which produces a new visual element, bound to a new instance of the component class with its injected dependency. ### Compilation phases There are three phases of AOT compilation. | | Phase | Details | |:--- |:--- |:--- | | 1 | code analysis | In this phase, the TypeScript compiler and *AOT collector* create a representation of the source. The collector does not attempt to interpret the metadata it collects. It represents the metadata as best it can and records errors when it detects a metadata syntax violation. | | 2 | code generation | In this phase, the compiler's `StaticReflector` interprets the metadata collected in phase 1, performs additional validation of the metadata, and throws an error if it detects a metadata restriction violation. | | 3 | template type checking | In this optional phase, the Angular *template compiler* uses the TypeScript compiler to validate the binding expressions in templates. You can enable this phase explicitly by setting the `strictTemplates` configuration option; see [Angular compiler options](reference/configs/angular-compiler-options). | ### Metadata restrictions You write metadata in a *subset* of TypeScript that must conform to the following general constraints: * Limit [expression syntax](#expression-syntax-limitations) to the supported subset of JavaScript * Only reference exported symbols after [code folding](#code-folding) * Only call [functions supported](#supported-classes-and-functions) by the compiler * Input/Outputs and data-bound class members must be public or protected.For additional guidelines and instructions on preparing an application for AOT compilation, see [Angular: Writing AOT-friendly applications](https://medium.com/sparkles-blog/angular-writing-aot-friendly-applications-7b64c8afbe3f). HELPFUL: Errors in AOT compilation commonly occur because of metadata that does not conform to the compiler's requirements \(as described more fully below\). For help in understanding and resolving these problems, see [AOT Metadata Errors](tools/cli/aot-metadata-errors). ### Configuring AOT compilation You can provide options in the [TypeScript configuration file](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html) that controls the compilation process. See [Angular compiler options](reference/configs/angular-compiler-options) for a complete list of available options. ##
{ "commit_id": "cb34e406ba", "end_byte": 7525, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/aot-compiler.md" }
angular/adev/src/content/tools/cli/aot-compiler.md_7525_16010
Phase 1: Code analysis The TypeScript compiler does some of the analytic work of the first phase. It emits the `.d.ts` *type definition files* with type information that the AOT compiler needs to generate application code. At the same time, the AOT **collector** analyzes the metadata recorded in the Angular decorators and outputs metadata information in **`.metadata.json`** files, one per `.d.ts` file. You can think of `.metadata.json` as a diagram of the overall structure of a decorator's metadata, represented as an [abstract syntax tree (AST)](https://en.wikipedia.org/wiki/Abstract_syntax_tree). HELPFUL: Angular's [schema.ts](https://github.com/angular/angular/blob/main/packages/compiler-cli/src/metadata/schema.ts) describes the JSON format as a collection of TypeScript interfaces. ### Expression syntax limitations The AOT collector only understands a subset of JavaScript. Define metadata objects with the following limited syntax: | Syntax | Example | |:--- |:--- | | Literal object | `{cherry: true, apple: true, mincemeat: false}` | | Literal array | `['cherries', 'flour', 'sugar']` | | Spread in literal array | `['apples', 'flour', …]` | | Calls | `bake(ingredients)` | | New | `new Oven()` | | Property access | `pie.slice` | | Array index | `ingredients[0]` | | Identity reference | `Component` | | A template string | <code>`pie is ${multiplier} times better than cake`</code> | | Literal string | `'pi'` | | Literal number | `3.14153265` | | Literal boolean | `true` | | Literal null | `null` | | Supported prefix operator | `!cake` | | Supported binary operator | `a+b` | | Conditional operator | `a ? b : c` | | Parentheses | `(a+b)` | If an expression uses unsupported syntax, the collector writes an error node to the `.metadata.json` file. The compiler later reports the error if it needs that piece of metadata to generate the application code. HELPFUL: If you want `ngc` to report syntax errors immediately rather than produce a `.metadata.json` file with errors, set the `strictMetadataEmit` option in the TypeScript configuration file. <docs-code language="json"> "angularCompilerOptions": { … "strictMetadataEmit" : true } </docs-code> Angular libraries have this option to ensure that all Angular `.metadata.json` files are clean and it is a best practice to do the same when building your own libraries. ### No arrow functions The AOT compiler does not support [function expressions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/function) and [arrow functions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Functions/Arrow_functions), also called *lambda* functions. Consider the following component decorator: <docs-code language="typescript"> @Component({ … providers: [{provide: server, useFactory: () => new Server()}] }) </docs-code> The AOT collector does not support the arrow function, `() => new Server()`, in a metadata expression. It generates an error node in place of the function. When the compiler later interprets this node, it reports an error that invites you to turn the arrow function into an *exported function*. You can fix the error by converting to this: <docs-code language="typescript"> export function serverFactory() { return new Server(); } @Component({ … providers: [{provide: server, useFactory: serverFactory}] }) </docs-code> In version 5 and later, the compiler automatically performs this rewriting while emitting the `.js` file. ### Code folding The compiler can only resolve references to ***exported*** symbols. The collector, however, can evaluate an expression during collection and record the result in the `.metadata.json`, rather than the original expression. This allows you to make limited use of non-exported symbols within expressions. For example, the collector can evaluate the expression `1 + 2 + 3 + 4` and replace it with the result, `10`. This process is called *folding*. An expression that can be reduced in this manner is *foldable*. The collector can evaluate references to module-local `const` declarations and initialized `var` and `let` declarations, effectively removing them from the `.metadata.json` file. Consider the following component definition: <docs-code language="typescript"> const template = '<div>{{hero.name}}</div>'; @Component({ selector: 'app-hero', template: template }) export class HeroComponent { @Input() hero: Hero; } </docs-code> The compiler could not refer to the `template` constant because it isn't exported. The collector, however, can fold the `template` constant into the metadata definition by in-lining its contents. The effect is the same as if you had written: <docs-code language="typescript"> @Component({ selector: 'app-hero', template: '<div>{{hero.name}}</div>' }) export class HeroComponent { @Input() hero: Hero; } </docs-code> There is no longer a reference to `template` and, therefore, nothing to trouble the compiler when it later interprets the *collector's* output in `.metadata.json`. You can take this example a step further by including the `template` constant in another expression: <docs-code language="typescript"> const template = '<div>{{hero.name}}</div>'; @Component({ selector: 'app-hero', template: template + '<div>{{hero.title}}</div>' }) export class HeroComponent { @Input() hero: Hero; } </docs-code> The collector reduces this expression to its equivalent *folded* string: <docs-code language="typescript"> '<div>{{hero.name}}</div><div>{{hero.title}}</div>' </docs-code> #### Foldable syntax The following table describes which expressions the collector can and cannot fold: | Syntax | Foldable | |:--- |:--- | | Literal object | yes | | Literal array | yes | | Spread in literal array | no | | Calls | no | | New | no | | Property access | yes, if target is foldable | | Array index | yes, if target and index are foldable | | Identity reference | yes, if it is a reference to a local | | A template with no substitutions | yes | | A template with substitutions | yes, if the substitutions are foldable | | Literal string | yes | | Literal number | yes | | Literal boolean | yes | | Literal null | yes | | Supported prefix operator | yes, if operand is foldable | | Supported binary operator | yes, if both left and right are foldable | | Conditional operator | yes, if condition is foldable | | Parentheses | yes, if the expression is foldable | If an expression is not foldable, the collector writes it to `.metadata.json` as an [AST](https://en.wikipedia.org/wiki/Abstract*syntax*tree) for the compiler to resolve. ## Phase 2
{ "commit_id": "cb34e406ba", "end_byte": 16010, "start_byte": 7525, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/aot-compiler.md" }
angular/adev/src/content/tools/cli/aot-compiler.md_16010_25531
: code generation The collector makes no attempt to understand the metadata that it collects and outputs to `.metadata.json`. It represents the metadata as best it can and records errors when it detects a metadata syntax violation. It's the compiler's job to interpret the `.metadata.json` in the code generation phase. The compiler understands all syntax forms that the collector supports, but it may reject *syntactically* correct metadata if the *semantics* violate compiler rules. ### Public or protected symbols The compiler can only reference *exported symbols*. * Decorated component class members must be public or protected. You cannot make an `@Input()` property private. * Data bound properties must also be public or protected ### Supported classes and functions The collector can represent a function call or object creation with `new` as long as the syntax is valid. The compiler, however, can later refuse to generate a call to a *particular* function or creation of a *particular* object. The compiler can only create instances of certain classes, supports only core decorators, and only supports calls to macros \(functions or static methods\) that return expressions. | Compiler action | Details | |:--- |:--- | | New instances | The compiler only allows metadata that create instances of the class `InjectionToken` from `@angular/core`. | | Supported decorators | The compiler only supports metadata for the [Angular decorators in the `@angular/core` module](api/core#decorators). | | Function calls | Factory functions must be exported, named functions. The AOT compiler does not support lambda expressions \("arrow functions"\) for factory functions. | ### Functions and static method calls The collector accepts any function or static method that contains a single `return` statement. The compiler, however, only supports macros in the form of functions or static methods that return an *expression*. For example, consider the following function: <docs-code language="typescript"> export function wrapInArray<T>(value: T): T[] { return [value]; } </docs-code> You can call the `wrapInArray` in a metadata definition because it returns the value of an expression that conforms to the compiler's restrictive JavaScript subset. You might use `wrapInArray()` like this: <docs-code language="typescript"> @NgModule({ declarations: wrapInArray(TypicalComponent) }) export class TypicalModule {} </docs-code> The compiler treats this usage as if you had written: <docs-code language="typescript"> @NgModule({ declarations: [TypicalComponent] }) export class TypicalModule {} </docs-code> The Angular [`RouterModule`](api/router/RouterModule) exports two macro static methods, `forRoot` and `forChild`, to help declare root and child routes. Review the [source code](https://github.com/angular/angular/blob/main/packages/router/src/router_module.ts#L139 "RouterModule.forRoot source code") for these methods to see how macros can simplify configuration of complex [NgModules](guide/ngmodules). ### Metadata rewriting The compiler treats object literals containing the fields `useClass`, `useValue`, `useFactory`, and `data` specially, converting the expression initializing one of these fields into an exported variable that replaces the expression. This process of rewriting these expressions removes all the restrictions on what can be in them because the compiler doesn't need to know the expression's value — it just needs to be able to generate a reference to the value. You might write something like: <docs-code language="typescript"> class TypicalServer { } @NgModule({ providers: [{provide: SERVER, useFactory: () => TypicalServer}] }) export class TypicalModule {} </docs-code> Without rewriting, this would be invalid because lambdas are not supported and `TypicalServer` is not exported. To allow this, the compiler automatically rewrites this to something like: <docs-code language="typescript"> class TypicalServer { } export const θ0 = () => new TypicalServer(); @NgModule({ providers: [{provide: SERVER, useFactory: θ0}] }) export class TypicalModule {} </docs-code> This allows the compiler to generate a reference to `θ0` in the factory without having to know what the value of `θ0` contains. The compiler does the rewriting during the emit of the `.js` file. It does not, however, rewrite the `.d.ts` file, so TypeScript doesn't recognize it as being an export. And it does not interfere with the ES module's exported API. ## Phase 3: Template type checking One of the Angular compiler's most helpful features is the ability to type-check expressions within templates, and catch any errors before they cause crashes at runtime. In the template type-checking phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates. Enable this phase explicitly by adding the compiler option `"fullTemplateTypeCheck"` in the `"angularCompilerOptions"` of the project's TypeScript configuration file (see [Angular Compiler Options](reference/configs/angular-compiler-options)). Template validation produces error messages when a type error is detected in a template binding expression, similar to how type errors are reported by the TypeScript compiler against code in a `.ts` file. For example, consider the following component: <docs-code language="typescript"> @Component({ selector: 'my-component', template: '{{person.addresss.street}}' }) class MyComponent { person?: Person; } </docs-code> This produces the following error: <docs-code hideCopy language="shell"> my.component.ts.MyComponent.html(1,1): : Property 'addresss' does not exist on type 'Person'. Did you mean 'address'? </docs-code> The file name reported in the error message, `my.component.ts.MyComponent.html`, is a synthetic file generated by the template compiler that holds contents of the `MyComponent` class template. The compiler never writes this file to disk. The line and column numbers are relative to the template string in the `@Component` annotation of the class, `MyComponent` in this case. If a component uses `templateUrl` instead of `template`, the errors are reported in the HTML file referenced by the `templateUrl` instead of a synthetic file. The error location is the beginning of the text node that contains the interpolation expression with the error. If the error is in an attribute binding such as `[value]="person.address.street"`, the error location is the location of the attribute that contains the error. The validation uses the TypeScript type checker and the options supplied to the TypeScript compiler to control how detailed the type validation is. For example, if the `strictTypeChecks` is specified, the error <docs-code hideCopy language="shell"> my.component.ts.MyComponent.html(1,1): : Object is possibly 'undefined' </docs-code> is reported as well as the above error message. ### Type narrowing The expression used in an `ngIf` directive is used to narrow type unions in the Angular template compiler, the same way the `if` expression does in TypeScript. For example, to avoid `Object is possibly 'undefined'` error in the template above, modify it to only emit the interpolation if the value of `person` is initialized as shown below: <docs-code language="typescript"> @Component({ selector: 'my-component', template: '<span *ngIf="person"> {{person.address.street}} </span>' }) class MyComponent { person?: Person; } </docs-code> Using `*ngIf` allows the TypeScript compiler to infer that the `person` used in the binding expression will never be `undefined`. For more information about input type narrowing, see [Improving template type checking for custom directives](guide/directives/structural-directives#directive-type-checks). ### Non-null type assertion operator Use the non-null type assertion operator to suppress the `Object is possibly 'undefined'` error when it is inconvenient to use `*ngIf` or when some constraint in the component ensures that the expression is always non-null when the binding expression is interpolated. In the following example, the `person` and `address` properties are always set together, implying that `address` is always non-null if `person` is non-null. There is no convenient way to describe this constraint to TypeScript and the template compiler, but the error is suppressed in the example by using `address!.street`. <docs-code language="typescript"> @Component({ selector: 'my-component', template: '<span *ngIf="person"> {{person.name}} lives on {{address!.street}} </span>' }) class MyComponent { person?: Person; address?: Address; setData(person: Person, address: Address) { this.person = person; this.address = address; } } </docs-code> The non-null assertion operator should be used sparingly as refactoring of the component might break this constraint. In this example it is recommended to include the checking of `address` in the `*ngIf` as shown below: <docs-code language="typescript"> @Component({ selector: 'my-component', template: '<span *ngIf="person &amp;&amp; address"> {{person.name}} lives on {{address.street}} </span>' }) class MyComponent { person?: Person; address?: Address; setData(person: Person, address: Address) { this.person = person; this.address = address; } } </docs-code>
{ "commit_id": "cb34e406ba", "end_byte": 25531, "start_byte": 16010, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/aot-compiler.md" }
angular/adev/src/content/tools/cli/end-to-end.md_0_3024
# End to End Testing End-to-end or (E2E) testing is a form of testing used to assert your entire application works as expected from start to finish or _"end-to-end"_. E2E testing differs from unit testing in that it is completely decoupled from the underlying implementation details of your code. It is typically used to validate an application in a way that mimics the way a user would interact with it. This page serves as a guide to getting started with end-to-end testing in Angular using the Angular CLI. ## Setup E2E Testing The Angular CLI downloads and installs everything you need to run end-to-end tests for your Angular application. <docs-code language="shell"> ng e2e </docs-code> The `ng e2e` command will first check your project for the "e2e" target. If it can't locate it, the CLI will then prompt you which e2e package you would like to use and walk you through the setup. <docs-code language="shell"> Cannot find "e2e" target for the specified project. You can add a package that implements these capabilities. For example: Cypress: ng add @cypress/schematic Nightwatch: ng add @nightwatch/schematics WebdriverIO: ng add @wdio/schematics Playwright: ng add playwright-ng-schematics Puppeteer: ng add @puppeteer/ng-schematics Would you like to add a package with "e2e" capabilities now? No ❯ Cypress Nightwatch WebdriverIO Playwright Puppeteer </docs-code> If you don't find the test runner you would like you use from the list above, you can add manually add a package using `ng add`. ## Running E2E Tests Now that your application is configured for end-to-end testing we can now run the same command to execute your tests. <docs-code language="shell"> ng e2e </docs-code> Note, their isn't anything "special" about running your tests with any of the integrated e2e packages. The `ng e2e` command is really just running the `e2e` builder under the hood. You can always [create your own custom builder](tools/cli/cli-builder#creating-a-builder) named `e2e` and run it using `ng e2e`. ## More information on end-to-end testing tools | Testing Tool | Details | | :----------- | :------------------------------------------------------------------------------------------------------------------- | | Cypress | [Getting started with Cypress](https://docs.cypress.io/guides/end-to-end-testing/writing-your-first-end-to-end-test) | | Nightwatch | [Getting started with Nightwatch](https://nightwatchjs.org/guide/writing-tests/introduction.html) | | WebdriverIO | [Getting started with Webdriver.io](https://webdriver.io/docs/gettingstarted) | | Playwright | [Getting started with Playwright](https://playwright.dev/docs/writing-tests) | | Puppeteer | [Getting started with Puppeteer](https://pptr.dev) |
{ "commit_id": "cb34e406ba", "end_byte": 3024, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/end-to-end.md" }
angular/adev/src/content/tools/cli/deployment.md_0_9613
# Deployment When you are ready to deploy your Angular application to a remote server, you have various options. ## Automatic deployment with the CLI The Angular CLI command `ng deploy` executes the `deploy` [CLI builder](tools/cli/cli-builder) associated with your project. A number of third-party builders implement deployment capabilities to different platforms. You can add any of them to your project with `ng add`. When you add a package with deployment capability, it will automatically update your workspace configuration (`angular.json` file) with a `deploy` section for the selected project. You can then use the `ng deploy` command to deploy that project. For example, the following command automatically deploys a project to [Firebase](https://firebase.google.com/). <docs-code language="shell"> ng add @angular/fire ng deploy </docs-code> The command is interactive. In this case, you must have or create a Firebase account and authenticate using it. The command prompts you to select a Firebase project for deployment before building your application and uploading the production assets to Firebase. The table below lists tools which implement deployment functionality to different platforms. The `deploy` command for each package may require different command line options. You can read more by following the links associated with the package names below: | Deployment to | Setup Command | |:--- |:--- | | [Firebase hosting](https://firebase.google.com/docs/hosting) | [`ng add @angular/fire`](https://npmjs.org/package/@angular/fire) | | [Vercel](https://vercel.com/solutions/angular) | [`vercel init angular`](https://github.com/vercel/vercel/tree/main/examples/angular) | | [Netlify](https://www.netlify.com) | [`ng add @netlify-builder/deploy`](https://npmjs.org/package/@netlify-builder/deploy) | | [GitHub pages](https://pages.github.com) | [`ng add angular-cli-ghpages`](https://npmjs.org/package/angular-cli-ghpages) | | [Amazon Cloud S3](https://aws.amazon.com/s3/?nc2=h_ql_prod_st_s3) | [`ng add @jefiozie/ngx-aws-deploy`](https://www.npmjs.com/package/@jefiozie/ngx-aws-deploy) | If you're deploying to a self-managed server or there's no builder for your favorite cloud platform, you can either [create a builder](tools/cli/cli-builder) that allows you to use the `ng deploy` command, or read through this guide to learn how to manually deploy your application. ## Manual deployment to a remote server To manually deploy your application, create a production build and copy the output directory to a web server or content delivery network (CDN). By default, `ng build` uses the `production` configuration. If you have customized your build configurations, you may want to confirm [production optimizations](tools/cli/deployment#production-optimizations) are being applied before deploying. `ng build` outputs the built artifacts to `dist/my-app/` by default, however this path can be configured with the `outputPath` option in the `@angular-devkit/build-angular:browser` builder. Copy this directory to the server and configure it to serve the directory. While this is a minimal deployment solution, there are a few requirements for the server to serve your Angular application correctly. ## Server configuration This section covers changes you may need to configure on the server to run your Angular application. ### Routed apps must fall back to `index.html` Client-side rendered Angular applications are perfect candidates for serving with a static HTML server because all the content is static and generated at build time. If the application uses the Angular router, you must configure the server to return the application's host page (`index.html`) when asked for a file that it does not have. A routed application should support "deep links". A *deep link* is a URL that specifies a path to a component inside the application. For example, `http://my-app.test/users/42` is a *deep link* to the user detail page that displays the user with `id` 42. There is no issue when the user initially loads the index page and then navigates to that URL from within a running client. The Angular router performs the navigation *client-side* and does not request a new HTML page. But clicking a deep link in an email, entering it in the browser address bar, or even refreshing the browser while already on the deep linked page will all be handled by the browser itself, *outside* the running application. The browser makes a direct request to the server for `/users/42`, bypassing Angular's router. A static server routinely returns `index.html` when it receives a request for `http://my-app.test/`. But most servers by default will reject `http://my-app.test/users/42` and returns a `404 - Not Found` error *unless* it is configured to return `index.html` instead. Configure the fallback route or 404 page to `index.html` for your server, so Angular is served for deep links and can display the correct route. Some servers call this fallback behavior "Single-Page Application" (SPA) mode. Once the browser loads the application, Angular router will read the URL to determine which page it is on and display `/users/42` correctly. For "real" 404 pages such as `http://my-app.test/does-not-exist`, the server does not require any additional configuration. [404 pages implemented in the Angular router](guide/routing/common-router-tasks#displaying-a-404-page) will be displayed correctly. ### Requesting data from a different server (CORS) Web developers may encounter a [*cross-origin resource sharing*](https://developer.mozilla.org/docs/Web/HTTP/CORS "Cross-origin resource sharing") error when making a network request to a server other than the application's own host server. Browsers forbid such requests unless the server explicitly permits them. There isn't anything Angular or the client application can do about these errors. The _server_ must be configured to accept the application's requests. Read about how to enable CORS for specific servers at [enable-cors.org](https://enable-cors.org/server.html "Enabling CORS server"). ## Production optimizations `ng build` uses the `production` configuration unless configured otherwise. This configuration enables the following build optimization features. | Features | Details | |:--- |:--- | | [Ahead-of-Time (AOT) Compilation](tools/cli/aot-compiler) | Pre-compiles Angular component templates. | | [Production mode](tools/cli/deployment#development-only-features) | Optimizes the application for the best runtime performance | | Bundling | Concatenates your many application and library files into a minimum number of deployed files. | | Minification | Removes excess whitespace, comments, and optional tokens. | | Mangling | Renames functions, classes, and variables to use shorter, arbitrary identifiers. | | Dead code elimination | Removes unreferenced modules and unused code. | See [`ng build`](cli/build) for more about CLI build options and their effects. ### Development-only features When you run an application locally using `ng serve`, Angular uses the development configuration at runtime which enables: * Extra safety checks such as [`expression-changed-after-checked`](errors/NG0100) detection. * More detailed error messages. * Additional debugging utilities such as the global `ng` variable with [debugging functions](api#core-global) and [Angular DevTools](tools/devtools) support. These features are helpful during development, but they require extra code in the app, which is undesirable in production. To ensure these features do not negatively impact bundle size for end users, Angular CLI removes development-only code from the bundle when building for production. Building your application with `ng build` by default uses the `production` configuration which removes these features from the output for optimal bundle size. ## `--deploy-url` `--deploy-url` is a command line option used to specify the base path for resolving relative URLs for assets such as images, scripts, and style sheets at *compile* time. <docs-code language="shell"> ng build --deploy-url /my/assets </docs-code> The effect and purpose of `--deploy-url` overlaps with [`<base href>`](guide/routing/common-router-tasks). Both can be used for initial scripts, stylesheets, lazy scripts, and css resources. Unlike `<base href>` which can be defined in a single place at runtime, the `--deploy-url` needs to be hard-coded into an application at build time. Prefer `<base href>` where possible.
{ "commit_id": "cb34e406ba", "end_byte": 9613, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/deployment.md" }
angular/adev/src/content/tools/cli/build-system-migration.md_0_9244
# Migrating to the new build system In v17 and higher, the new build system provides an improved way to build Angular applications. This new build system includes: - A modern output format using ESM, with dynamic import expressions to support lazy module loading. - Faster build-time performance for both initial builds and incremental rebuilds. - Newer JavaScript ecosystem tools such as [esbuild](https://esbuild.github.io/) and [Vite](https://vitejs.dev/). - Integrated SSR and prerendering capabilities. This new build system is stable and fully supported for use with Angular applications. You can migrate to the new build system with applications that use the `browser` builder. If using a custom builder, please refer to the documentation for that builder on possible migration options. IMPORTANT: The existing Webpack-based build system is still considered stable and fully supported. Applications can continue to use the `browser` builder and will not be automatically migrated when updating. ## For new applications New applications will use this new build system by default via the `application` builder. ## For existing applications Both automated and manual procedures are available dependening on the requirements of the project. Starting with v18, the update process will ask if you would like to migrate existing applications to use the new build system via the automated migration. HELPFUL: Remember to remove any CommonJS assumptions in the application server code if using SSR such as `require`, `__filename`, `__dirname`, or other constructs from the [CommonJS module scope](https://nodejs.org/api/modules.html#the-module-scope). All application code should be ESM compatible. This does not apply to third-party dependencies. ### Automated migration (Recommended) The automated migration will adjust both the application configuration within `angular.json` as well as code and stylesheets to remove previous Webpack-specific feature usage. While many changes can be automated and most applications will not require any further changes, each application is unique and there may be some manual changes required. After the migration, please attempt a build of the application as there could be new errors that will require adjustments within the code. The errors will attempt to provide solutions to the problem when possible and the later sections of this guide describe some of the more common situations that you may encounter. When updating to Angular v18 via `ng update`, you will be asked to execute the migration. This migration is entirely optional for v18 and can also be run manually at anytime after an update via the following command: <docs-code language="shell"> ng update @angular/cli --name use-application-builder </docs-code> The migration does the following: * Converts existing `browser` or `browser-esbuild` target to `application` * Removes any previous SSR builders (because `application` does that now). * Updates configuration accordingly. * Merges `tsconfig.server.json` with `tsconfig.app.json` and adds the TypeScript option `"esModuleInterop": true` to ensure `express` imports are [ESM compliant](#esm-default-imports-vs-namespace-imports). * Updates application server code to use new bootstrapping and output directory structure. * Removes any Webpack-specific builder stylesheet usage such as the tilde or caret in `@import`/`url()` and updates the configuration to provide equivalent behavior * Converts to use the new lower dependency `@angular/build` Node.js package if no other `@angular-devkit/build-angular` usage is found. ### Manual migration Additionally for existing projects, you can manually opt-in to use the new builder on a per-application basis with two different options. Both options are considered stable and fully supported by the Angular team. The choice of which option to use is a factor of how many changes you will need to make to migrate and what new features you would like to use in the project. - The `browser-esbuild` builder builds only the client-side bundle of an application designed to be compatible with the existing `browser` builder that provides the preexisting build system. It serves as a drop-in replacement for existing `browser` applications. - The `application` builder covers an entire application, such as the client-side bundle, as well as optionally building a server for server-side rendering and performing build-time prerendering of static pages. The `application` builder is generally preferred as it improves server-side rendered (SSR) builds, and makes it easier for client-side rendered projects to adopt SSR in the future. However it requires a little more migration effort, particularly for existing SSR applications if performed manually. If the `application` builder is difficult for your project to adopt, `browser-esbuild` can be an easier solution which gives most of the build performance benefits with fewer breaking changes. #### Manual migration to the compatibility builder A builder named `browser-esbuild` is available within the `@angular-devkit/build-angular` package that is present in an Angular CLI generated application. You can try out the new build system for applications that use the `browser` builder. If using a custom builder, please refer to the documentation for that builder on possible migration options. The compatibility option was implemented to minimize the amount of changes necessary to initially migrate your applications. This is provided via an alternate builder (`browser-esbuild`). You can update the `build` target for any application target to migrate to the new build system. The following is what you would typically find in `angular.json` for an application: <docs-code language="json"> ... "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", ... </docs-code> Changing the `builder` field is the only change you will need to make. <docs-code language="json"> ... "architect": { "build": { "builder": "@angular-devkit/build-angular:browser-esbuild", ... </docs-code> #### Manual migration to the new `application` builder A builder named `application` is also available within the `@angular-devkit/build-angular` package that is present in an Angular CLI generated application. This builder is the default for all new applications created via `ng new`. The following is what you would typically find in `angular.json` for an application: <docs-code language="json"> ... "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", ... </docs-code> Changing the `builder` field is the first change you will need to make. <docs-code language="json"> ... "architect": { "build": { "builder": "@angular-devkit/build-angular:application", ... </docs-code> Once the builder name has been changed, options within the `build` target will need to be updated. The following list discusses all the `browser` builder options that will need to be adjusted. - `main` should be renamed to `browser`. - `polyfills` should be an array, rather than a single file. - `buildOptimizer` should be removed, as this is covered by the `optimization` option. - `resourcesOutputPath` should be removed, this is now always `media`. - `vendorChunk` should be removed, as this was a performance optimization which is no longer needed. - `commonChunk` should be removed, as this was a performance optimization which is no longer needed. - `deployUrl` should be removed and is not supported. Prefer [`<base href>`](guide/routing/common-router-tasks) instead. See [deployment documentation](tools/cli/deployment#--deploy-url) for more information. - `ngswConfigPath` should be renamed to `serviceWorker`. If the application is not using SSR currently, this should be the final step to allow `ng build` to function. After executing `ng build` for the first time, there may be new warnings or errors based on behavioral differences or application usage of Webpack-specific features. Many of the warnings will provide suggestions on how to remedy that problem. If it appears that a warning is incorrect or the solution is not apparent, please open an issue on [GitHub](https://github.com/angular/angular-cli/issues). Also, the later sections of this guide provide additional information on several specific cases as well as current known issues. For applications new to SSR, the [Angular SSR Guide](guide/ssr) provides additional information regarding the setup process for adding SSR to an application. For applications that are already using SSR, additional adjustments will be needed to update the application server to support the new integrated SSR capabilities. The `application` builder now provides the integrated functionality for all of the following preexisting builders: - `app-shell` - `prerender` - `server` - `ssr-dev-server` The `ng update` process will automatically remove usages of the `@nguniversal` scope packages where some of these builders were previously located. The new `@angular/ssr` package will also be automatically added and used with configuration and code being adjusted during the update. The `@angular/ssr` package supports the `browser` builder as well as the `application` builder.
{ "commit_id": "cb34e406ba", "end_byte": 9244, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/build-system-migration.md" }
angular/adev/src/content/tools/cli/build-system-migration.md_9244_15806
## Executing a build Once you have updated the application configuration, builds can be performed using `ng build` as was previously done. Depending on the choice of builder migration, some of the command line options may be different. If the build command is contained in any `npm` or other scripts, ensure they are reviewed and updated. For applications that have migrated to the `application` builder and that use SSR and/or prererending, you also may be able to remove extra `ng run` commands from scripts now that `ng build` has integrated SSR support. <docs-code language="shell"> ng build </docs-code> ## Starting the development server The development server will automatically detect the new build system and use it to build the application. To start the development server no changes are necessary to the `dev-server` builder configuration or command line. <docs-code language="shell"> ng serve </docs-code> You can continue to use the [command line options](/cli/serve) you have used in the past with the development server. ## Hot module replacement JavaScript-based hot module replacement (HMR) is currently not supported. However, global stylesheet (`styles` build option) HMR is available and enabled by default. Angular focused HMR capabilities are currently planned and will be introduced in a future version. ## Unimplemented options and behavior Several build options are not yet implemented but will be added in the future as the build system moves towards a stable status. If your application uses these options, you can still try out the build system without removing them. Warnings will be issued for any unimplemented options but they will otherwise be ignored. However, if your application relies on any of these options to function, you may want to wait to try. - [WASM imports](https://github.com/angular/angular-cli/issues/25102) -- WASM can still be loaded manually via [standard web APIs](https://developer.mozilla.org/docs/WebAssembly/Loading_and_running). ## ESM default imports vs. namespace imports TypeScript by default allows default exports to be imported as namespace imports and then used in call expressions. This is unfortunately a divergence from the ECMAScript specification. The underlying bundler (`esbuild`) within the new build system expects ESM code that conforms to the specification. The build system will now generate a warning if your application uses an incorrect type of import of a package. However, to allow TypeScript to accept the correct usage, a TypeScript option must be enabled within the application's `tsconfig` file. When enabled, the [`esModuleInterop`](https://www.typescriptlang.org/tsconfig#esModuleInterop) option provides better alignment with the ECMAScript specification and is also recommended by the TypeScript team. Once enabled, you can update package imports where applicable to an ECMAScript conformant form. Using the [`moment`](https://npmjs.com/package/moment) package as an example, the following application code will cause runtime errors: ```ts import * as moment from 'moment'; console.log(moment().format()); ``` The build will generate a warning to notify you that there is a potential problem. The warning will be similar to: <docs-code language="text"> ▲ [WARNING] Calling "moment" will crash at run-time because it's an import namespace object, not a function [call-import-namespace] src/main.ts:2:12: 2 │ console.log(moment().format()); ╵ ~~~~~~ Consider changing "moment" to a default import instead: src/main.ts:1:7: 1 │ import * as moment from 'moment'; │ ~~~~~~~~~~~ ╵ moment </docs-code> However, you can avoid the runtime errors and the warning by enabling the `esModuleInterop` TypeScript option for the application and changing the import to the following: ```ts import moment from 'moment'; console.log(moment().format()); ``` ## Vite as a development server The usage of Vite in the Angular CLI is currently within a _development server capacity only_. Even without using the underlying Vite build system, Vite provides a full-featured development server with client side support that has been bundled into a low dependency npm package. This makes it an ideal candidate to provide comprehensive development server functionality. The current development server process uses the new build system to generate a development build of the application in memory and passes the results to Vite to serve the application. The usage of Vite, much like the Webpack-based development server, is encapsulated within the Angular CLI `dev-server` builder and currently cannot be directly configured. ## Known Issues There are currently several known issues that you may encounter when trying the new build system. This list will be updated to stay current. If any of these issues are currently blocking you from trying out the new build system, please check back in the future as it may have been solved. ### Type-checking of Web Worker code and processing of nested Web Workers Web Workers can be used within application code using the same syntax (`new Worker(new URL('<workerfile>', import.meta.url))`) that is supported with the `browser` builder. However, the code within the Worker will not currently be type-checked by the TypeScript compiler. TypeScript code is supported just not type-checked. Additionally, any nested workers will not be processed by the build system. A nested worker is a Worker instantiation within another Worker file. ### Order-dependent side-effectful imports in lazy modules Import statements that are dependent on a specific ordering and are also used in multiple lazy modules can cause top-level statements to be executed out of order. This is not common as it depends on the usage of side-effectful modules and does not apply to the `polyfills` option. This is caused by a [defect](https://github.com/evanw/esbuild/issues/399) in the underlying bundler but will be addressed in a future update. IMPORTANT: Avoiding the use of modules with non-local side effects (outside of polyfills) is recommended whenever possible regardless of the build system being used and avoids this particular issue. Modules with non-local side effects can have a negative effect on both application size and runtime performance as well. ## Bug reports Report issues and feature requests on [GitHub](https://github.com/angular/angular-cli/issues). Please provide a minimal reproduction where possible to aid the team in addressing issues.
{ "commit_id": "cb34e406ba", "end_byte": 15806, "start_byte": 9244, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/build-system-migration.md" }
angular/adev/src/content/tools/cli/build.md_0_17185
# Building Angular apps You can build your Angular CLI application or library with the `ng build` command. This will compile your TypeScript code to JavaScript, as well as optimize, bundle, and minify the output as appropriate. `ng build` only executes the builder for the `build` target in the default project as specified in `angular.json`. Angular CLI includes four builders typically used as `build` targets: | Builder | Purpose | | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `@angular-devkit/build-angular:browser` | Bundles a client-side application for use in a browser with [Webpack](https://webpack.js.org/). | | `@angular-devkit/build-angular:browser-esbuild` | Bundles a client-side application for use in a browser with [esbuild](https://esbuild.github.io/). See [`browser-esbuild` documentation](tools/cli/build-system-migration#manual-migration-to-the-compatibility-builder) for more information. | | `@angular-devkit/build-angular:application` | Builds an application with a client-side bundle, a Node server, and build-time prerendered routes with [esbuild](https://esbuild.github.io/). | | `@angular-devkit/build-angular:ng-packagr` | Builds an Angular library adhering to [Angular Package Format](tools/libraries/angular-package-format). | Applications generated by `ng new` use `@angular-devkit/build-angular:application` by default. Libraries generated by `ng generate library` use `@angular-devkit/build-angular:ng-packagr` by default. You can determine which builder is being used for a particular project by looking up the `build` target for that project. <docs-code language="json"> { "projects": { "my-app": { "architect": { // `ng build` invokes the Architect target named `build`. "build": { "builder": "@angular-devkit/build-angular:application", … }, "serve": { … } "test": { … } … } } } } </docs-code> This page discusses usage and options of `@angular-devkit/build-angular:application`. ## Output directory The result of this build process is output to a directory (`dist/${PROJECT_NAME}` by default). ## Configuring size budgets As applications grow in functionality, they also grow in size. The CLI lets you set size thresholds in your configuration to ensure that parts of your application stay within size boundaries that you define. Define your size boundaries in the CLI configuration file, `angular.json`, in a `budgets` section for each [configured environment](tools/cli/environments). <docs-code language="json"> { … "configurations": { "production": { … "budgets": [ { "type": "initial", "maximumWarning": "250kb", "maximumError": "500kb" }, ] } } } </docs-code> You can specify size budgets for the entire app, and for particular parts. Each budget entry configures a budget of a given type. Specify size values in the following formats: | Size value | Details | | :-------------- | :-------------------------------------------------------------------------- | | `123` or `123b` | Size in bytes. | | `123kb` | Size in kilobytes. | | `123mb` | Size in megabytes. | | `12%` | Percentage of size relative to baseline. \(Not valid for baseline values.\) | When you configure a budget, the builder warns or reports an error when a given part of the application reaches or exceeds a boundary size that you set. Each budget entry is a JSON object with the following properties: | Property | Value | | :------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | type | The type of budget. One of: <table> <thead> <tr> <th> Value </th> <th> Details </th> </tr> </thead> <tbody> <tr> <td> <code>bundle</code> </td> <td> The size of a specific bundle. </td> </tr> <tr> <td> <code>initial</code> </td> <td> The size of JavaScript needed for bootstrapping the application. Defaults to warning at 500kb and erroring at 1mb. </td> </tr> <tr> <td> <code>allScript</code> </td> <td> The size of all scripts. </td> </tr> <tr> <td> <code>all</code> </td> <td> The size of the entire application. </td> </tr> <tr> <td> <code>anyComponentStyle</code> </td> <td> This size of any one component stylesheet. Defaults to warning at 2kb and erroring at 4kb. </td> </tr> <tr> <td> <code>anyScript</code> </td> <td> The size of any one script. </td> </tr> <tr> <td> <code>any</code> </td> <td> The size of any file. </td> </tr> </tbody> </table> | | name | The name of the bundle (for `type=bundle`). | | baseline | The baseline size for comparison. | | maximumWarning | The maximum threshold for warning relative to the baseline. | | maximumError | The maximum threshold for error relative to the baseline. | | minimumWarning | The minimum threshold for warning relative to the baseline. | | minimumError | The minimum threshold for error relative to the baseline. | | warning | The threshold for warning relative to the baseline (min & max). | | error | The threshold for error relative to the baseline (min & max). | ## Configuring CommonJS dependencies Always prefer native [ECMAScript modules](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Statements/import) (ESM) throughout your application and its dependencies. ESM is a fully specified web standard and JavaScript language feature with strong static analysis support. This makes bundle optimizations more powerful than other module formats. Angular CLI also supports importing [CommonJS](https://nodejs.org/api/modules.html) dependencies into your project and will bundle these dependencies automatically. However, CommonJS modules can prevent bundlers and minifiers from optimizing those modules effectively, which results in larger bundle sizes. For more information, see [How CommonJS is making your bundles larger](https://web.dev/commonjs-larger-bundles). Angular CLI outputs warnings if it detects that your browser application depends on CommonJS modules. When you encounter a CommonJS dependency, consider asking the maintainer to support ECMAScript modules, contributing that support yourself, or using an alternative dependency which meets your needs. If the best option is to use a CommonJS dependency, you can disable these warnings by adding the CommonJS module name to `allowedCommonJsDependencies` option in the `build` options located in `angular.json`. <docs-code language="json"> "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "allowedCommonJsDependencies": [ "lodash" ] … } … }, </docs-code> ## Configuring browser compatibility The Angular CLI uses [Browserslist](https://github.com/browserslist/browserslist) to ensure compatibility with different browser versions. Depending on supported browsers, Angular will automatically transform certain JavaScript and CSS features to ensure the built application does not use a feature which has not been implemented by a supported browser. However, the Angular CLI will not automatically add polyfills to supplement missing Web APIs. Use the `polyfills` option in `angular.json` to add polyfills. Internally, the Angular CLI uses the below default `browserslist` configuration which matches the [browsers that are supported](reference/versions#browser-support) by Angular. <docs-code language="text"> last 2 Chrome versions last 1 Firefox version last 2 Edge major versions last 2 Safari major versions last 2 iOS major versions last 2 Android major versions Firefox ESR </docs-code> To override the internal configuration, run [`ng generate config browserslist`](cli/generate/config), which generates a `.browserslistrc` configuration file in the project directory. See the [browserslist repository](https://github.com/browserslist/browserslist) for more examples of how to target specific browsers and versions. Avoid expanding this list to more browsers. Even if your application code more broadly compatible, Angular itself might not be. You should only ever _reduce_ the set of browsers or versions in this list. HELPFUL: Use [browsersl.ist](https://browsersl.ist) to display compatible browsers for a `browserslist` query.
{ "commit_id": "cb34e406ba", "end_byte": 17185, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/build.md" }
angular/adev/src/content/tools/cli/BUILD.bazel_0_1315
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "cli", srcs = glob([ "*.md", ]), data = [ "//adev/src/content/examples/cli-builder:src/my-builder.spec.ts", "//adev/src/content/examples/cli-builder:src/my-builder.ts", "//adev/src/content/examples/schematics-for-libraries:projects/my-lib/package.json", "//adev/src/content/examples/schematics-for-libraries:projects/my-lib/schematics/collection.1.json", "//adev/src/content/examples/schematics-for-libraries:projects/my-lib/schematics/collection.json", "//adev/src/content/examples/schematics-for-libraries:projects/my-lib/schematics/my-service/index.1.ts", "//adev/src/content/examples/schematics-for-libraries:projects/my-lib/schematics/my-service/index.ts", "//adev/src/content/examples/schematics-for-libraries:projects/my-lib/schematics/my-service/schema.json", "//adev/src/content/examples/schematics-for-libraries:projects/my-lib/schematics/my-service/schema.ts", "//adev/src/content/examples/schematics-for-libraries:projects/my-lib/schematics/ng-add/index.ts", "//adev/src/content/examples/schematics-for-libraries:projects/my-lib/tsconfig.schematics.json", ], visibility = ["//adev:__subpackages__"], )
{ "commit_id": "cb34e406ba", "end_byte": 1315, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/BUILD.bazel" }
angular/adev/src/content/tools/cli/cli-builder.md_0_6649
# Angular CLI builders A number of Angular CLI commands run a complex process on your code, such as building, testing, or serving your application. The commands use an internal tool called Architect to run *CLI builders*, which invoke another tool (bundler, test runner, server) to accomplish the desired task. Custom builders can perform an entirely new task, or to change which third-party tool is used by an existing command. This document explains how CLI builders integrate with the workspace configuration file, and shows how you can create your own builder. HELPFUL: Find the code from the examples used here in this [GitHub repository](https://github.com/mgechev/cli-builders-demo). ## CLI builders The internal Architect tool delegates work to handler functions called *builders*. A builder handler function receives two arguments: | Argument | Type | |:--- |:--- | | `options` | `JSONObject` | | `context` | `BuilderContext` | The separation of concerns here is the same as with [schematics](tools/cli/schematics-authoring), which are used for other CLI commands that touch your code (such as `ng generate`). * The `options` object is provided by the CLI user's options and configuration, while the `context` object is provided by the CLI Builder API automatically. * In addition to the contextual information, the `context` object also provides access to a scheduling method, `context.scheduleTarget()`. The scheduler executes the builder handler function with a given target configuration. The builder handler function can be synchronous (return a value), asynchronous (return a `Promise`), or watch and return multiple values (return an `Observable`). The return values must always be of type `BuilderOutput`. This object contains a Boolean `success` field and an optional `error` field that can contain an error message. Angular provides some builders that are used by the CLI for commands such as `ng build` and `ng test`. Default target configurations for these and other built-in CLI builders can be found and configured in the "architect" section of the [workspace configuration file](reference/configs/workspace-config), `angular.json`. Also, extend and customize Angular by creating your own builders, which you can run directly using the [`ng run` CLI command](cli/run). ### Builder project structure A builder resides in a "project" folder that is similar in structure to an Angular workspace, with global configuration files at the top level, and more specific configuration in a source folder with the code files that define the behavior. For example, your `myBuilder` folder could contain the following files. | Files | Purpose | |:--- | :--- | | `src/my-builder.ts` | Main source file for the builder definition. | | `src/my-builder.spec.ts` | Source file for tests. | | `src/schema.json` | Definition of builder input options. | | `builders.json` | Builders definition. | | `package.json` | Dependencies. See [https://docs.npmjs.com/files/package.json](https://docs.npmjs.com/files/package.json). | | `tsconfig.json` | [TypeScript configuration](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html). | Builders can be published to `npm`, see [Publishing your Library](tools/libraries/creating-libraries). ## Creating a builder As an example, create a builder that copies a file to a new location. To create a builder, use the `createBuilder()` CLI Builder function, and return a `Promise<BuilderOutput>` object. <docs-code header="src/my-builder.ts (builder skeleton)" path="adev/src/content/examples/cli-builder/src/my-builder.ts" visibleRegion="builder-skeleton"/> Now let's add some logic to it. The following code retrieves the source and destination file paths from user options and copies the file from the source to the destination \(using the [Promise version of the built-in NodeJS `copyFile()` function](https://nodejs.org/api/fs.html#fs_fspromises_copyfile_src_dest_mode)\). If the copy operation fails, it returns an error with a message about the underlying problem. <docs-code header="src/my-builder.ts (builder)" path="adev/src/content/examples/cli-builder/src/my-builder.ts" visibleRegion="builder"/> ### Handling output By default, `copyFile()` does not print anything to the process standard output or error. If an error occurs, it might be difficult to understand exactly what the builder was trying to do when the problem occurred. Add some additional context by logging additional information using the `Logger` API. This also lets the builder itself be executed in a separate process, even if the standard output and error are deactivated. You can retrieve a `Logger` instance from the context. <docs-code header="src/my-builder.ts (handling output)" path="adev/src/content/examples/cli-builder/src/my-builder.ts" visibleRegion="handling-output"/> ### Progress and status reporting The CLI Builder API includes progress and status reporting tools, which can provide hints for certain functions and interfaces. To report progress, use the `context.reportProgress()` method, which takes a current value, optional total, and status string as arguments. The total can be any number. For example, if you know how many files you have to process, the total could be the number of files, and current should be the number processed so far. The status string is unmodified unless you pass in a new string value. In our example, the copy operation either finishes or is still executing, so there's no need for a progress report, but you can report status so that a parent builder that called our builder would know what's going on. Use the `context.reportStatus()` method to generate a status string of any length. HELPFUL: There's no guarantee that a long string will be shown entirely; it could be cut to fit the UI that displays it. Pass an empty string to remove the status. <docs-code header="src/my-builder.ts (progress reporting)" path="adev/src/content/examples/cli-builder/src/my-builder.ts" visibleRegion="progress-reporting"/>
{ "commit_id": "cb34e406ba", "end_byte": 6649, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/cli-builder.md" }
angular/adev/src/content/tools/cli/cli-builder.md_6649_11934
## Builder input You can invoke a builder indirectly through a CLI command such as `ng build`, or directly with the Angular CLI `ng run` command. In either case, you must provide required inputs, but can let other inputs default to values that are pre-configured for a specific *target*, specified by a [configuration](tools/cli/environments), or set on the command line. ### Input validation You define builder inputs in a JSON schema associated with that builder. Similar to schematics, the Architect tool collects the resolved input values into an `options` object, and validates their types against the schema before passing them to the builder function. For our example builder, `options` should be a `JsonObject` with two keys: a `source` and a `destination`, each of which are a string. You can provide the following schema for type validation of these values. <docs-code header="src/schema.json" language="json"> { "$schema": "http://json-schema.org/schema", "type": "object", "properties": { "source": { "type": "string" }, "destination": { "type": "string" } } } </docs-code> HELPFUL: This is a minimal example, but the use of a schema for validation can be very powerful. For more information, see the [JSON schemas website](http://json-schema.org). To link our builder implementation with its schema and name, you need to create a *builder definition* file, which you can point to in `package.json`. Create a file named `builders.json` that looks like this: <docs-code header="builders.json" language="json"> { "builders": { "copy": { "implementation": "./dist/my-builder.js", "schema": "./src/schema.json", "description": "Copies a file." } } } </docs-code> In the `package.json` file, add a `builders` key that tells the Architect tool where to find our builder definition file. <docs-code header="package.json" language="json"> { "name": "@example/copy-file", "version": "1.0.0", "description": "Builder for copying files", "builders": "builders.json", "dependencies": { "@angular-devkit/architect": "~0.1200.0", "@angular-devkit/core": "^12.0.0" } } </docs-code> The official name of our builder is now `@example/copy-file:copy`. The first part of this is the package name and the second part is the builder name as specified in the `builders.json` file. These values are accessed on `options.source` and `options.destination`. <docs-code header="src/my-builder.ts (report status)" path="adev/src/content/examples/cli-builder/src/my-builder.ts" visibleRegion="report-status"/> ### Target configuration A builder must have a defined target that associates it with a specific input configuration and project. Targets are defined in the `angular.json` [CLI configuration file](reference/configs/workspace-config). A target specifies the builder to use, its default options configuration, and named alternative configurations. Architect in the Angular CLI uses the target definition to resolve input options for a given run. The `angular.json` file has a section for each project, and the "architect" section of each project configures targets for builders used by CLI commands such as 'build', 'test', and 'serve'. By default, for example, the `ng build` command runs the builder `@angular-devkit/build-angular:browser` to perform the build task, and passes in default option values as specified for the `build` target in `angular.json`. <docs-code header="angular.json" language="json"> … "myApp": { … "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { "outputPath": "dist/myApp", "index": "src/index.html", … }, "configurations": { "production": { "fileReplacements": [ { "replace": "src/environments/environment.ts", "with": "src/environments/environment.prod.ts" } ], "optimization": true, "outputHashing": "all", … } } }, … } } … </docs-code> The command passes the builder the set of default options specified in the "options" section. If you pass the `--configuration=production` flag, it uses the override values specified in the `production` configuration. Specify further option overrides individually on the command line. #### Target strings The generic `ng run` CLI command takes as its first argument a target string of the following form. <docs-code language="shell"> project:target[:configuration] </docs-code> | | Details | |:--- |:--- | | project | The name of the Angular CLI project that the target is associated with. | | target | A named builder configuration from the `architect` section of the `angular.json` file. | | configuration | (optional) The name of a specific configuration override for the given target, as defined in the `angular.json` file. | If your builder calls another builder, it might need to read a passed target string. Parse this string into an object by using the `targetFromTargetString()` utility function from `@angular-devkit/architect`. ## Schedule
{ "commit_id": "cb34e406ba", "end_byte": 11934, "start_byte": 6649, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/cli-builder.md" }
angular/adev/src/content/tools/cli/cli-builder.md_11934_19951
and run Architect runs builders asynchronously. To invoke a builder, you schedule a task to be run when all configuration resolution is complete. The builder function is not executed until the scheduler returns a `BuilderRun` control object. The CLI typically schedules tasks by calling the `context.scheduleTarget()` function, and then resolves input options using the target definition in the `angular.json` file. Architect resolves input options for a given target by taking the default options object, then overwriting values from the configuration, then further overwriting values from the overrides object passed to `context.scheduleTarget()`. For the Angular CLI, the overrides object is built from command line arguments. Architect validates the resulting options values against the schema of the builder. If inputs are valid, Architect creates the context and executes the builder. For more information see [Workspace Configuration](reference/configs/workspace-config). HELPFUL: You can also invoke a builder directly from another builder or test by calling `context.scheduleBuilder()`. You pass an `options` object directly to the method, and those option values are validated against the schema of the builder without further adjustment. Only the `context.scheduleTarget()` method resolves the configuration and overrides through the `angular.json` file. ### Default architect configuration Let's create a simple `angular.json` file that puts target configurations into context. You can publish the builder to npm (see [Publishing your Library](tools/libraries/creating-libraries#publishing-your-library)), and install it using the following command: <docs-code language="shell"> npm install @example/copy-file </docs-code> If you create a new project with `ng new builder-test`, the generated `angular.json` file looks something like this, with only default builder configurations. <docs-code header="angular.json" language="json"> { "projects": { "builder-test": { "architect": { "build": { "builder": "@angular-devkit/build-angular:browser", "options": { // more options... "outputPath": "dist/builder-test", "index": "src/index.html", "main": "src/main.ts", "polyfills": "src/polyfills.ts", "tsConfig": "src/tsconfig.app.json" }, "configurations": { "production": { // more options... "optimization": true, "aot": true, "buildOptimizer": true } } } } } } } </docs-code> ### Adding a target Add a new target that will run our builder to copy a file. This target tells the builder to copy the `package.json` file. * We will add a new target section to the `architect` object for our project * The target named `copy-package` uses our builder, which you published to `@example/copy-file`. * The options object provides default values for the two inputs that you defined. * `source` - The existing file you are copying. * `destination` - The path you want to copy to. <docs-code header="angular.json" language="json"> { "projects": { "builder-test": { "architect": { "copy-package": { "builder": "@example/copy-file:copy", "options": { "source": "package.json", "destination": "package-copy.json" } }, // Existing targets... } } } } </docs-code> ### Running the builder To run our builder with the new target's default configuration, use the following CLI command. <docs-code language="shell"> ng run builder-test:copy-package </docs-code> This copies the `package.json` file to `package-copy.json`. Use command-line arguments to override the configured defaults. For example, to run with a different `destination` value, use the following CLI command. <docs-code language="shell"> ng run builder-test:copy-package --destination=package-other.json </docs-code> This copies the file to `package-other.json` instead of `package-copy.json`. Because you did not override the *source* option, it will still copy from the default `package.json` file. ## Testing a builder Use integration testing for your builder, so that you can use the Architect scheduler to create a context, as in this [example](https://github.com/mgechev/cli-builders-demo). In the builder source directory, create a new test file `my-builder.spec.ts`. The test creates new instances of `JsonSchemaRegistry` (for schema validation), `TestingArchitectHost` (an in-memory implementation of `ArchitectHost`), and `Architect`. Here's an example of a test that runs the copy file builder. The test uses the builder to copy the `package.json` file and validates that the copied file's contents are the same as the source. <docs-code header="src/my-builder.spec.ts" path="adev/src/content/examples/cli-builder/src/my-builder.spec.ts"/> HELPFUL: When running this test in your repo, you need the [`ts-node`](https://github.com/TypeStrong/ts-node) package. You can avoid this by renaming `my-builder.spec.ts` to `my-builder.spec.js`. ### Watch mode Most builders to run once and return. However, this behavior is not entirely compatible with a builder that watches for changes (like a devserver, for example). Architect can support watch mode, but there are some things to look out for. * To be used with watch mode, a builder handler function should return an `Observable`. Architect subscribes to the `Observable` until it completes and might reuse it if the builder is scheduled again with the same arguments. * The builder should always emit a `BuilderOutput` object after each execution. Once it's been executed, it can enter a watch mode, to be triggered by an external event. If an event triggers it to restart, the builder should execute the `context.reportRunning()` function to tell Architect that it is running again. This prevents Architect from stopping the builder if another run is scheduled. When your builder calls `BuilderRun.stop()` to exit watch mode, Architect unsubscribes from the builder's `Observable` and calls the builder's teardown logic to clean up. This behavior also allows for long-running builds to be stopped and cleaned up. In general, if your builder is watching an external event, you should separate your run into three phases. | Phases | Details | |:--- |:--- | | Running | The task being performed, such as invoking a compiler. This ends when the compiler finishes and your builder emits a `BuilderOutput` object. | | Watching | Between two runs, watch an external event stream. For example, watch the file system for any changes. This ends when the compiler restarts, and `context.reportRunning()` is called. | | Completion | Either the task is fully completed, such as a compiler which needs to run a number of times, or the builder run was stopped (using `BuilderRun.stop()`). Architect executes teardown logic and unsubscribes from your builder's `Observable`. | ## Summary The CLI Builder API provides a means of changing the behavior of the Angular CLI by using builders to execute custom logic. * Builders can be synchronous or asynchronous, execute once or watch for external events, and can schedule other builders or targets. * Builders have option defaults specified in the `angular.json` configuration file, which can be overwritten by an alternate configuration for the target, and further overwritten by command line flags * The Angular team recommends that you use integration tests to test Architect builders. Use unit tests to validate the logic that the builder executes. * If your builder returns an `Observable`, it should clean up the builder in the teardown logic of that `Observable`.
{ "commit_id": "cb34e406ba", "end_byte": 19951, "start_byte": 11934, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/cli-builder.md" }
angular/adev/src/content/tools/cli/serve.md_0_3201
# Serving Angular apps for development You can serve your Angular CLI application with the `ng serve` command. This will compile your application, skip unnecessary optimizations, start a devserver, and automatically rebuild and live reload any subsequent changes. You can stop the server by pressing `Ctrl+C`. `ng serve` only executes the builder for the `serve` target in the default project as specified in `angular.json`. While any builder can be used here, the most common (and default) builder is `@angular-devkit/build-angular:dev-server`. You can determine which builder is being used for a particular project by looking up the `serve` target for that project. <docs-code language="json"> { "projects": { "my-app": { "architect": { // `ng serve` invokes the Architect target named `serve`. "serve": { "builder": "@angular-devkit/build-angular:dev-server", // ... }, "build": { /* ... */ } "test": { /* ... */ } } } } } </docs-code> This page discusses usage and options of `@angular-devkit/build-angular:dev-server`. ## Proxying to a backend server Use [proxying support](https://webpack.js.org/configuration/dev-server/#devserverproxy) to divert certain URLs to a backend server, by passing a file to the `--proxy-config` build option. For example, to divert all calls for `http://localhost:4200/api` to a server running on `http://localhost:3000/api`, take the following steps. 1. Create a file `proxy.conf.json` in your project's `src/` folder. 1. Add the following content to the new proxy file: <docs-code language="json"> { "/api": { "target": "http://localhost:3000", "secure": false } } </docs-code> 1. In the CLI configuration file, `angular.json`, add the `proxyConfig` option to the `serve` target: <docs-code language="json"> { "projects": { "my-app": { "architect": { "serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "proxyConfig": "src/proxy.conf.json" } } } } } } </docs-code> 1. To run the development server with this proxy configuration, call `ng serve`. Edit the proxy configuration file to add configuration options; following are some examples. For a description of all options, see [webpack DevServer documentation](https://webpack.js.org/configuration/dev-server/#devserverproxy). NOTE: If you edit the proxy configuration file, you must relaunch the `ng serve` process to make your changes effective. ## `localhost` resolution As of Node version 17, Node will _not_ always resolve `http://localhost:<port>` to `http://127.0.0.1:<port>` depending on each machine's configuration. If you get an `ECONNREFUSED` error using a proxy targeting a `localhost` URL, you can fix this issue by updating the target from `http://localhost:<port>` to `http://127.0.0.1:<port>`. See [the `http-proxy-middleware` documentation](https://github.com/chimurai/http-proxy-middleware#nodejs-17-econnrefused-issue-with-ipv6-and-localhost-705) for more information.
{ "commit_id": "cb34e406ba", "end_byte": 3201, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/serve.md" }
angular/adev/src/content/tools/cli/schematics-authoring.md_0_4650
# Authoring schematics You can create your own schematics to operate on Angular projects. Library developers typically package schematics with their libraries to integrate them with the Angular CLI. You can also create stand-alone schematics to manipulate the files and constructs in Angular applications as a way of customizing them for your development environment and making them conform to your standards and constraints. Schematics can be chained, running other schematics to perform complex operations. Manipulating the code in an application has the potential to be both very powerful and correspondingly dangerous. For example, creating a file that already exists would be an error, and if it was applied immediately, it would discard all the other changes applied so far. The Angular Schematics tooling guards against side effects and errors by creating a virtual file system. A schematic describes a pipeline of transformations that can be applied to the virtual file system. When a schematic runs, the transformations are recorded in memory, and only applied in the real file system once they're confirmed to be valid. ## Schematics concepts The public API for schematics defines classes that represent the basic concepts. * The virtual file system is represented by a `Tree`. The `Tree` data structure contains a *base* \(a set of files that already exists\) and a *staging area* \(a list of changes to be applied to the base\). When making modifications, you don't actually change the base, but add those modifications to the staging area. * A `Rule` object defines a function that takes a `Tree`, applies transformations, and returns a new `Tree`. The main file for a schematic, `index.ts`, defines a set of rules that implement the schematic's logic. * A transformation is represented by an `Action`. There are four action types: `Create`, `Rename`, `Overwrite`, and `Delete`. * Each schematic runs in a context, represented by a `SchematicContext` object. The context object passed into a rule provides access to utility functions and metadata that the schematic might need to work with, including a logging API to help with debugging. The context also defines a *merge strategy* that determines how changes are merged from the staged tree into the base tree. A change can be accepted or ignored, or throw an exception. ### Defining rules and actions When you create a new blank schematic with the [Schematics CLI](#schematics-cli), the generated entry function is a *rule factory*. A `RuleFactory` object defines a higher-order function that creates a `Rule`. <docs-code header="index.ts" language="typescript"> import { Rule, SchematicContext, Tree } from '@angular-devkit/schematics'; // You don't have to export the function as default. // You can also have more than one rule factory per file. export function helloWorld(_options: any): Rule { return (tree: Tree,_context: SchematicContext) => { return tree; }; } </docs-code> Your rules can make changes to your projects by calling external tools and implementing logic. You need a rule, for example, to define how a template in the schematic is to be merged into the hosting project. Rules can make use of utilities provided with the `@schematics/angular` package. Look for helper functions for working with modules, dependencies, TypeScript, AST, JSON, Angular CLI workspaces and projects, and more. <docs-code header="index.ts" language="typescript"> import { JsonAstObject, JsonObject, JsonValue, Path, normalize, parseJsonAst, strings, } from '@angular-devkit/core'; </docs-code> ### Defining input options with a schema and interfaces Rules can collect option values from the caller and inject them into templates. The options available to your rules, with their allowed values and defaults, are defined in the schematic's JSON schema file, `<schematic>/schema.json`. Define variable or enumerated data types for the schema using TypeScript interfaces. The schema defines the types and default values of variables used in the schematic. For example, the hypothetical "Hello World" schematic might have the following schema. <docs-code header="src/hello-world/schema.json" language="json"> { "properties": { "name": { "type": "string", "minLength": 1, "default": "world" }, "useColor": { "type": "boolean" } } } </docs-code> See examples of schema files for the Angular CLI command schematics in [`@schematics/angular`](https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/application/schema.json).
{ "commit_id": "cb34e406ba", "end_byte": 4650, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/schematics-authoring.md" }
angular/adev/src/content/tools/cli/schematics-authoring.md_4650_11396
### Schematic prompts Schematic *prompts* introduce user interaction into schematic execution. Configure schematic options to display a customizable question to the user. The prompts are displayed before the execution of the schematic, which then uses the response as the value for the option. This lets users direct the operation of the schematic without requiring in-depth knowledge of the full spectrum of available options. The "Hello World" schematic might, for example, ask the user for their name, and display that name in place of the default name "world". To define such a prompt, add an `x-prompt` property to the schema for the `name` variable. Similarly, you can add a prompt to let the user decide whether the schematic uses color when executing its hello action. The schema with both prompts would be as follows. <docs-code header="src/hello-world/schema.json" language="json"> { "properties": { "name": { "type": "string", "minLength": 1, "default": "world", "x-prompt": "What is your name?" }, "useColor": { "type": "boolean", "x-prompt": "Would you like the response in color?" } } } </docs-code> #### Prompt short-form syntax These examples use a shorthand form of the prompt syntax, supplying only the text of the question. In most cases, this is all that is required. Notice however, that the two prompts expect different types of input. When using the shorthand form, the most appropriate type is automatically selected based on the property's schema. In the example, the `name` prompt uses the `input` type because it is a string property. The `useColor` prompt uses a `confirmation` type because it is a Boolean property. In this case, "yes" corresponds to `true` and "no" corresponds to `false`. There are three supported input types. | Input type | Details | |:--- |:---- | | confirmation | A yes or no question; ideal for Boolean options. | | input | Textual input; ideal for string or number options. | | list | A predefined set of allowed values. | In the short form, the type is inferred from the property's type and constraints. | Property schema | Prompt type | |:--- |:--- | | "type": "boolean" | confirmation \("yes"=`true`, "no"=`false`\) | | "type": "string" | input | | "type": "number" | input \(only valid numbers accepted\) | | "type": "integer" | input \(only valid numbers accepted\) | | "enum": […] | list \(enum members become list selections\) | In the following example, the property takes an enumerated value, so the schematic automatically chooses the list type, and creates a menu from the possible values. <docs-code header="schema.json" language="json"> "style": { "description": "The file extension or preprocessor to use for style files.", "type": "string", "default": "css", "enum": [ "css", "scss", "sass", "less", "styl" ], "x-prompt": "Which stylesheet format would you like to use?" } </docs-code> The prompt runtime automatically validates the provided response against the constraints provided in the JSON schema. If the value is not acceptable, the user is prompted for a new value. This ensures that any values passed to the schematic meet the expectations of the schematic's implementation, so that you do not need to add additional checks within the schematic's code. #### Prompt long-form syntax The `x-prompt` field syntax supports a long form for cases where you require additional customization and control over the prompt. In this form, the `x-prompt` field value is a JSON object with subfields that customize the behavior of the prompt. | Field | Data value | |:--- |:--- | | type | `confirmation`, `input`, or `list` \(selected automatically in short form\) | | message | string \(required\) | | items | string and/or label/value object pair \(only valid with type `list`\) | The following example of the long form is from the JSON schema for the schematic that the CLI uses to [generate applications](https://github.com/angular/angular-cli/blob/ba8a6ea59983bb52a6f1e66d105c5a77517f062e/packages/schematics/angular/application/schema.json#L56). It defines the prompt that lets users choose which style preprocessor they want to use for the application being created. By using the long form, the schematic can provide more explicit formatting of the menu choices. <docs-code header="package/schematics/angular/application/schema.json" language="json"> "style": { "description": "The file extension or preprocessor to use for style files.", "type": "string", "default": "css", "enum": [ "css", "scss", "sass", "less" ], "x-prompt": { "message": "Which stylesheet format would you like to use?", "type": "list", "items": [ { "value": "css", "label": "CSS" }, { "value": "scss", "label": "SCSS [ https://sass-lang.com/documentation/syntax#scss ]" }, { "value": "sass", "label": "Sass [ https://sass-lang.com/documentation/syntax#the-indented-syntax ]" }, { "value": "less", "label": "Less [ https://lesscss.org/ ]" } ] }, }, </docs-code> #### x-prompt schema The JSON schema that defines a schematic's options supports extensions to allow the declarative definition of prompts and their respective behavior. No additional logic or changes are required to the code of a schematic to support the prompts. The following JSON schema is a complete description of the long-form syntax for the `x-prompt` field. <docs-code header="x-prompt schema" language="json"> { "oneOf": [ { "type": "string" }, { "type": "object", "properties": { "type": { "type": "string" }, "message": { "type": "string" }, "items": { "type": "array", "items": { "oneOf": [ { "type": "string" }, { "type": "object", "properties": { "label": { "type": "string" }, "value": { } }, "required": [ "value" ] } ] } } }, "required": [ "message" ] } ] } </docs-code> ##
{ "commit_id": "cb34e406ba", "end_byte": 11396, "start_byte": 4650, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/schematics-authoring.md" }
angular/adev/src/content/tools/cli/schematics-authoring.md_11396_17458
Schematics CLI Schematics come with their own command-line tool. Using Node 6.9 or later, install the Schematics command line tool globally: <docs-code language="shell"> npm install -g @angular-devkit/schematics-cli </docs-code> This installs the `schematics` executable, which you can use to create a new schematics collection in its own project folder, add a new schematic to an existing collection, or extend an existing schematic. In the following sections, you will create a new schematics collection using the CLI to introduce the files and file structure, and some of the basic concepts. The most common use of schematics, however, is to integrate an Angular library with the Angular CLI. Do this by creating the schematic files directly within the library project in an Angular workspace, without using the Schematics CLI. See [Schematics for Libraries](tools/cli/schematics-for-libraries). ### Creating a schematics collection The following command creates a new schematic named `hello-world` in a new project folder of the same name. <docs-code language="shell"> schematics blank --name=hello-world </docs-code> The `blank` schematic is provided by the Schematics CLI. The command creates a new project folder \(the root folder for the collection\) and an initial named schematic in the collection. Go to the collection folder, install your npm dependencies, and open your new collection in your favorite editor to see the generated files. For example, if you are using VS Code: <docs-code language="shell"> cd hello-world npm install npm run build code . </docs-code> The initial schematic gets the same name as the project folder, and is generated in `src/hello-world`. Add related schematics to this collection, and modify the generated skeleton code to define your schematic's functionality. Each schematic name must be unique within the collection. ### Running a schematic Use the `schematics` command to run a named schematic. Provide the path to the project folder, the schematic name, and any mandatory options, in the following format. <docs-code language="shell"> schematics <path-to-schematics-project>:<schematics-name> --<required-option>=<value> </docs-code> The path can be absolute or relative to the current working directory where the command is executed. For example, to run the schematic you just generated \(which has no required options\), use the following command. <docs-code language="shell"> schematics .:hello-world </docs-code> ### Adding a schematic to a collection To add a schematic to an existing collection, use the same command you use to start a new schematics project, but run the command inside the project folder. <docs-code language="shell"> cd hello-world schematics blank --name=goodbye-world </docs-code> The command generates the new named schematic inside your collection, with a main `index.ts` file and its associated test spec. It also adds the name, description, and factory function for the new schematic to the collection's schema in the `collection.json` file. ## Collection contents The top level of the root project folder for a collection contains configuration files, a `node_modules` folder, and a `src/` folder. The `src/` folder contains subfolders for named schematics in the collection, and a schema, `collection.json`, which describes the collected schematics. Each schematic is created with a name, description, and factory function. <docs-code language="json"> { "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json", "schematics": { "hello-world": { "description": "A blank schematic.", "factory": "./hello-world/index#helloWorld" } } } </docs-code> * The `$schema` property specifies the schema that the CLI uses for validation. * The `schematics` property lists named schematics that belong to this collection. Each schematic has a plain-text description, and points to the generated entry function in the main file. * The `factory` property points to the generated entry function. In this example, you invoke the `hello-world` schematic by calling the `helloWorld()` factory function. * The optional `schema` property points to a JSON schema file that defines the command-line options available to the schematic. * The optional `aliases` array specifies one or more strings that can be used to invoke the schematic. For example, the schematic for the Angular CLI "generate" command has an alias "g", that lets you use the command `ng g`. ### Named schematics When you use the Schematics CLI to create a blank schematics project, the new blank schematic is the first member of the collection, and has the same name as the collection. When you add a new named schematic to this collection, it is automatically added to the `collection.json` schema. In addition to the name and description, each schematic has a `factory` property that identifies the schematic's entry point. In the example, you invoke the schematic's defined functionality by calling the `helloWorld()` function in the main file, `hello-world/index.ts`. <img alt="overview" src="assets/images/guide/schematics/collection-files.gif"> Each named schematic in the collection has the following main parts. | Parts | Details | |:--- |:--- | | `index.ts` | Code that defines the transformation logic for a named schematic. | | `schema.json` | Schematic variable definition. | | `schema.d.ts` | Schematic variables. | | `files/` | Optional component/template files to replicate. | It is possible for a schematic to provide all of its logic in the `index.ts` file, without additional templates. You can create dynamic schematics for Angular, however, by providing components and templates in the `files` folder, like those in standalone Angular projects. The logic in the index file configures these templates by defining rules that inject data and modify variables.
{ "commit_id": "cb34e406ba", "end_byte": 17458, "start_byte": 11396, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/schematics-authoring.md" }
angular/adev/src/content/tools/cli/aot-metadata-errors.md_0_8292
# AOT metadata errors The following are metadata errors you may encounter, with explanations and suggested corrections. ## Expression form not supported HELPFUL: The compiler encountered an expression it didn't understand while evaluating Angular metadata. Language features outside of the compiler's [restricted expression syntax](tools/cli/aot-compiler#expression-syntax) can produce this error, as seen in the following example: <docs-code language="typescript"> // ERROR export class Fooish { … } … const prop = typeof Fooish; // typeof is not valid in metadata … // bracket notation is not valid in metadata { provide: 'token', useValue: { [prop]: 'value' } }; … </docs-code> You can use `typeof` and bracket notation in normal application code. You just can't use those features within expressions that define Angular metadata. Avoid this error by sticking to the compiler's [restricted expression syntax](tools/cli/aot-compiler#expression-syntax) when writing Angular metadata and be wary of new or unusual TypeScript features. ## Reference to a local (non-exported) symbol HELPFUL: Reference to a local \(non-exported\) symbol 'symbol name'. Consider exporting the symbol. The compiler encountered a reference to a locally defined symbol that either wasn't exported or wasn't initialized. Here's a `provider` example of the problem. <docs-code language="typescript"> // ERROR let foo: number; // neither exported nor initialized @Component({ selector: 'my-component', template: … , providers: [ { provide: Foo, useValue: foo } ] }) export class MyComponent {} </docs-code> The compiler generates the component factory, which includes the `useValue` provider code, in a separate module. *That* factory module can't reach back to *this* source module to access the local \(non-exported\) `foo` variable. You could fix the problem by initializing `foo`. <docs-code language="typescript"> let foo = 42; // initialized </docs-code> The compiler will [fold](tools/cli/aot-compiler#code-folding) the expression into the provider as if you had written this. <docs-code language="typescript"> providers: [ { provide: Foo, useValue: 42 } ] </docs-code> Alternatively, you can fix it by exporting `foo` with the expectation that `foo` will be assigned at runtime when you actually know its value. <docs-code language="typescript"> // CORRECTED export let foo: number; // exported @Component({ selector: 'my-component', template: … , providers: [ { provide: Foo, useValue: foo } ] }) export class MyComponent {} </docs-code> Adding `export` often works for variables referenced in metadata such as `providers` and `animations` because the compiler can generate *references* to the exported variables in these expressions. It doesn't need the *values* of those variables. Adding `export` doesn't work when the compiler needs the *actual value* in order to generate code. For example, it doesn't work for the `template` property. <docs-code language="typescript"> // ERROR export let someTemplate: string; // exported but not initialized @Component({ selector: 'my-component', template: someTemplate }) export class MyComponent {} </docs-code> The compiler needs the value of the `template` property *right now* to generate the component factory. The variable reference alone is insufficient. Prefixing the declaration with `export` merely produces a new error, "[`Only initialized variables and constants can be referenced`](#only-initialized-variables)". ## Only initialized variables and constants HELPFUL: *Only initialized variables and constants can be referenced because the value of this variable is needed by the template compiler.* The compiler found a reference to an exported variable or static field that wasn't initialized. It needs the value of that variable to generate code. The following example tries to set the component's `template` property to the value of the exported `someTemplate` variable which is declared but *unassigned*. <docs-code language="typescript"> // ERROR export let someTemplate: string; @Component({ selector: 'my-component', template: someTemplate }) export class MyComponent {} </docs-code> You'd also get this error if you imported `someTemplate` from some other module and neglected to initialize it there. <docs-code language="typescript"> // ERROR - not initialized there either import { someTemplate } from './config'; @Component({ selector: 'my-component', template: someTemplate }) export class MyComponent {} </docs-code> The compiler cannot wait until runtime to get the template information. It must statically derive the value of the `someTemplate` variable from the source code so that it can generate the component factory, which includes instructions for building the element based on the template. To correct this error, provide the initial value of the variable in an initializer clause *on the same line*. <docs-code language="typescript"> // CORRECTED export let someTemplate = '<h1>Greetings from Angular</h1>'; @Component({ selector: 'my-component', template: someTemplate }) export class MyComponent {} </docs-code> ## Reference to a non-exported class HELPFUL: *Reference to a non-exported class `<class name>`.* *Consider exporting the class.* Metadata referenced a class that wasn't exported. For example, you may have defined a class and used it as an injection token in a providers array but neglected to export that class. <docs-code language="typescript"> // ERROR abstract class MyStrategy { } … providers: [ { provide: MyStrategy, useValue: … } ] … </docs-code> Angular generates a class factory in a separate module and that factory [can only access exported classes](tools/cli/aot-compiler#exported-symbols). To correct this error, export the referenced class. <docs-code language="typescript"> // CORRECTED export abstract class MyStrategy { } … providers: [ { provide: MyStrategy, useValue: … } ] … </docs-code> ## Reference to a non-exported function HELPFUL: *Metadata referenced a function that wasn't exported.* For example, you may have set a providers `useFactory` property to a locally defined function that you neglected to export. <docs-code language="typescript"> // ERROR function myStrategy() { … } … providers: [ { provide: MyStrategy, useFactory: myStrategy } ] … </docs-code> Angular generates a class factory in a separate module and that factory [can only access exported functions](tools/cli/aot-compiler#exported-symbols). To correct this error, export the function. <docs-code language="typescript"> // CORRECTED export function myStrategy() { … } … providers: [ { provide: MyStrategy, useFactory: myStrategy } ] … </docs-code> ## Function calls are not supported HELPFUL: *Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function.* The compiler does not currently support [function expressions or lambda functions](tools/cli/aot-compiler#function-expression). For example, you cannot set a provider's `useFactory` to an anonymous function or arrow function like this. <docs-code language="typescript"> // ERROR … providers: [ { provide: MyStrategy, useFactory: function() { … } }, { provide: OtherStrategy, useFactory: () => { … } } ] … </docs-code> You also get this error if you call a function or method in a provider's `useValue`. <docs-code language="typescript"> // ERROR import { calculateValue } from './utilities'; … providers: [ { provide: SomeValue, useValue: calculateValue() } ] … </docs-code> To correct this error, export a function from the module and refer to the function in a `useFactory` provider instead. <docs-code language="typescript"> // CORRECTED import { calculateValue } from './utilities'; export function myStrategy() { … } export function otherStrategy() { … } export function someValueFactory() { return calculateValue(); } … providers: [ { provide: MyStrategy, useFactory: myStrategy }, { provide: OtherStrategy, useFactory: otherStrategy }, { provide: SomeValue, useFactory: someValueFactory } ] … </docs-code> ## Destructured variable or constant not supported HELP
{ "commit_id": "cb34e406ba", "end_byte": 8292, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/aot-metadata-errors.md" }
angular/adev/src/content/tools/cli/aot-metadata-errors.md_8292_13822
FUL: *Referencing an exported destructured variable or constant is not supported by the template compiler. Consider simplifying this to avoid destructuring.* The compiler does not support references to variables assigned by [destructuring](https://www.typescriptlang.org/docs/handbook/variable-declarations.html#destructuring). For example, you cannot write something like this: <docs-code language="typescript"> // ERROR import { configuration } from './configuration'; // destructured assignment to foo and bar const {foo, bar} = configuration; … providers: [ {provide: Foo, useValue: foo}, {provide: Bar, useValue: bar}, ] … </docs-code> To correct this error, refer to non-destructured values. <docs-code language="typescript"> // CORRECTED import { configuration } from './configuration'; … providers: [ {provide: Foo, useValue: configuration.foo}, {provide: Bar, useValue: configuration.bar}, ] … </docs-code> ## Could not resolve type HELPFUL: *The compiler encountered a type and can't determine which module exports that type.* This can happen if you refer to an ambient type. For example, the `Window` type is an ambient type declared in the global `.d.ts` file. You'll get an error if you reference it in the component constructor, which the compiler must statically analyze. <docs-code language="typescript"> // ERROR @Component({ }) export class MyComponent { constructor (private win: Window) { … } } </docs-code> TypeScript understands ambient types so you don't import them. The Angular compiler does not understand a type that you neglect to export or import. In this case, the compiler doesn't understand how to inject something with the `Window` token. Do not refer to ambient types in metadata expressions. If you must inject an instance of an ambient type, you can finesse the problem in four steps: 1. Create an injection token for an instance of the ambient type. 1. Create a factory function that returns that instance. 1. Add a `useFactory` provider with that factory function. 1. Use `@Inject` to inject the instance. Here's an illustrative example. <docs-code language="typescript"> // CORRECTED import { Inject } from '@angular/core'; export const WINDOW = new InjectionToken('Window'); export function _window() { return window; } @Component({ … providers: [ { provide: WINDOW, useFactory: _window } ] }) export class MyComponent { constructor (@Inject(WINDOW) private win: Window) { … } } </docs-code> The `Window` type in the constructor is no longer a problem for the compiler because it uses the `@Inject(WINDOW)` to generate the injection code. Angular does something similar with the `DOCUMENT` token so you can inject the browser's `document` object \(or an abstraction of it, depending upon the platform in which the application runs\). <docs-code language="typescript"> import { Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Component({ … }) export class MyComponent { constructor (@Inject(DOCUMENT) private doc: Document) { … } } </docs-code> ## Name expected HELPFUL: *The compiler expected a name in an expression it was evaluating.* This can happen if you use a number as a property name as in the following example. <docs-code language="typescript"> // ERROR provider: [{ provide: Foo, useValue: { 0: 'test' } }] </docs-code> Change the name of the property to something non-numeric. <docs-code language="typescript"> // CORRECTED provider: [{ provide: Foo, useValue: { '0': 'test' } }] </docs-code> ## Unsupported enum member name HELPFUL: *Angular couldn't determine the value of the [enum member](https://www.typescriptlang.org/docs/handbook/enums.html) that you referenced in metadata.* The compiler can understand simple enum values but not complex values such as those derived from computed properties. <docs-code language="typescript"> // ERROR enum Colors { Red = 1, White, Blue = "Blue".length // computed } … providers: [ { provide: BaseColor, useValue: Colors.White } // ok { provide: DangerColor, useValue: Colors.Red } // ok { provide: StrongColor, useValue: Colors.Blue } // bad ] … </docs-code> Avoid referring to enums with complicated initializers or computed properties. ## Tagged template expressions are not supported HELPFUL: *Tagged template expressions are not supported in metadata.* The compiler encountered a JavaScript ES2015 [tagged template expression](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals) such as the following. <docs-code language="typescript"> // ERROR const expression = 'funky'; const raw = String.raw`A tagged template ${expression} string`; … template: '<div>' + raw + '</div>' … </docs-code> [`String.raw()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/raw) is a *tag function* native to JavaScript ES2015. The AOT compiler does not support tagged template expressions; avoid them in metadata expressions. ## Symbol reference expected HELPFUL: *The compiler expected a reference to a symbol at the location specified in the error message.* This error can occur if you use an expression in the `extends` clause of a class. <!--todo: Chuck: After reviewing your PR comment I'm still at a loss. See [comment there](https://github.com/angular/angular/pull/17712#discussion_r132025495). -->
{ "commit_id": "cb34e406ba", "end_byte": 13822, "start_byte": 8292, "url": "https://github.com/angular/angular/blob/main/adev/src/content/tools/cli/aot-metadata-errors.md" }
angular/adev/src/content/introduction/what-is-angular.md_0_7550
<docs-decorative-header title="What is Angular?" imgSrc="adev/src/assets/images/what_is_angular.svg"> <!-- markdownlint-disable-line --> </docs-decorative-header> <big style="margin-top: 2em"> Angular is a web framework that empowers developers to build fast, reliable applications. </big> Maintained by a dedicated team at Google, Angular provides a broad suite of tools, APIs, and libraries to simplify and streamline your development workflow. Angular gives you a solid platform on which to build fast, reliable applications that scale with both the size of your team and the size of your codebase. **Want to see some code?** Jump over to our [Essentials](essentials) for a quick overview of what it's like to use Angular, or get started in the [Tutorial](tutorials/learn-angular) if you prefer following step-by-step instructions. ## Features that power your development <docs-card-container> <docs-card title="Keep your codebase organized with an opinionated component model and flexible dependency injection system" href="guide/components" link="Get started with Components"> Angular components make it easy to split your code into well-encapsulated parts. The versatile dependency injection helps you keep your code modular, loosely-coupled, and testable. </docs-card> <docs-card title="Get fast state updates with fine-grained reactivity based on Signals" href="guide/signals" link="Explore Angular Signals"> Our fine-grained reactivity model, combined with compile-time optimizations, simplifies development and helps build faster apps by default. Granularly track how and where state is used throughout an application, giving the framework the power to render fast updates via highly optimized instructions. </docs-card> <docs-card title="Meet your performance targets with SSR, SSG, hydration, and next-generation deferred loading" href="guide/ssr" link="Read about SSR"> Angular supports both server-side rendering (SSR) and static site generation (SSG) along with full DOM hydration. `@defer` blocks in templates make it simple to declaratively divide your templates into lazy-loadable parts. </docs-card> <docs-card title="Guarantee everything works together with Angular's first-party modules for forms, routing, and more"> [Angular's router](guide/routing) provides a feature-rich navigation toolkit, including support for route guards, data resolution, lazy-loading, and much more. [Angular's forms module](guide/forms) provides a standardized system for form participation and validation. </docs-card> </docs-card-container> ## Develop applications faster than ever <docs-card-container> <docs-card title="Effortlessly build, serve, test, deploy with Angular CLI" href="tools/cli" link="Angular CLI"> Angular CLI gets your project running in under a minute with the commands you need to grow into a deployed production application. </docs-card> <docs-card title="Visually debug, analyze, and optimize your code with the Angular DevTools browser extension" href="tools/devtools" link="Angular DevTools"> Angular DevTools sits alongside your browser's developer tools. It helps debug and analyze your app, including a component tree inspector, dependency injection tree view, and custom performance profiling flame chart. </docs-card> <docs-card title="Never miss a version with ng update" href="cli/update" link="ng update"> Angular CLI's `ng update` runs automated code transformations that automatically handle routine breaking changes, dramatically simplifying major version updates. Keeping up with the latest version keeps your app as fast and secure as possible. </docs-card> <docs-card title="Stay productive with IDE integration in your favorite editor" href="tools/language-service" link="Language service"> Angular's IDE language services powers code completion, navigation, refactoring, and real-time diagnostics in your favorite editor. </docs-card> </docs-card-container> ## Ship with confidence <docs-card-container> <docs-card title="Verified commit-by-commit against Google's colossal monorepo" href="https://cacm.acm.org/magazines/2016/7/204032-why-google-stores-billions-of-lines-of-code-in-a-single-repository/fulltext" link="Learn about Google's monorepo"> Every Angular commit is checked against _hundreds of thousands_ of tests in Google's internal code repository, representing countless real-world scenarios. Angular is committed to stability for some of Google’s largest products, including Google Cloud. This commitment ensures changes are well-tested, backwards compatible, and include migration tools whenever possible. </docs-card> <docs-card title="Clear support policies and predictable release schedule" href="reference/releases" link="Versioning & releasing"> Angular's predictable, time-based release schedule gives your organization confidence in the stability and backwards compatibility of the framework. Long Term Support (LTS) windows make sure you get critical security fixes when you need them. First-party update tools, guides and automated migration schematics help keep your apps up-to-date with the latest advancements to the framework and the web platform. </docs-card> </docs-card-container> ## Works at any scale <docs-card-container> <docs-card title="Reach users everywhere with internationalization support" href="guide/i18n" link="Internationalization"> Angular's internationalization features handle message translations and formatting, including support for unicode standard ICU syntax. </docs-card> <docs-card title="Protect your users with security by default" href="best-practices/security" link="Security"> In collaboration with Google's world-class security engineers, Angular aims to make development safe by default. Built-in security features, including HTML sanitization and trusted type support, help protect your users from common vulnerabilities like cross-site scripting and cross-site request forgery. </docs-card> <docs-card title="Keep large teams productive with Vite and esbuild" href="tools/cli/build-system-migration" link="ESBuild and Vite"> Angular CLI includes a fast, modern build pipeline using Vite and ESBuild. Developers report building projects with hundreds of thousands of lines of code in less than a minute. </docs-card> <docs-card title="Proven in some of Google's largest web apps"> Large Google products build on top of Angular's architecture and help develop new features that further improve Angular's scalability, from [Google Fonts](https://fonts.google.com/) to [Google Cloud](https://console.cloud.google.com). </docs-card> </docs-card-container> ## Open-source first <docs-card-container> <docs-card title="Made in the open on GitHub" href="https://github.com/angular/angular" link="Star our GitHub"> Curious what we’re working on? Every PR and commit is available on our GitHub. Run into an issue or bug? We triage GitHub issues regularly to ensure we’re responsive and engaged with our community, and solving the real world problems you’re facing. </docs-card> <docs-card title="Built with transparency" href="roadmap" link="Read our public roadmap"> Our team publishes a public roadmap of our current and future work and values your feedback. We publish Request for Comments (RFCs) to collect feedback on larger feature changes and ensure the community voice is heard while shaping the future direction of Angular. </docs-card> </docs-card-container> ## A thr
{ "commit_id": "cb34e406ba", "end_byte": 7550, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/what-is-angular.md" }
angular/adev/src/content/introduction/what-is-angular.md_7550_10102
iving community <docs-card-container> <docs-card title="Courses, blogs and resources" href="https://devlibrary.withgoogle.com/products/angular?sort=added" link="Check out DevLibrary"> Our community is composed of talented developers, writers, instructors, podcasters, and more. The Google for Developers library is just a sample of the high quality resources available for new and experienced developers to continue developing. </docs-card> <docs-card title="Open Source" href="https://github.com/angular/angular/blob/main/CONTRIBUTING.md" link="Contribute to Angular"> We are thankful for the open source contributors who make Angular a better framework for everyone. From fixing a typo in the docs, to adding major features, we encourage anyone interested to get started on our GitHub. </docs-card> <docs-card title="Community partnerships" href="https://developers.google.com/community/experts/directory?specialization=angular" link="Meet the Angular GDEs"> Our team partners with individuals, educators, and enterprises to ensure we consistently are supporting developers. Angular Google Developer Experts (GDEs) represent community leaders around the world educating, organizing, and developing with Angular. Enterprise partnerships help ensure that Angular scales well for technology industry leaders. </docs-card> <docs-card title="Partnering with other Google technologies"> Angular partners closely with other Google technologies and teams to improve the web. Our ongoing partnership with Chrome’s Aurora actively explores improvements to user experience across the web, developing built-in performance optimizations like NgOptimizedImage and improvements to Angular’s Core Web Vitals. We are also working with [Firebase](https://firebase.google.com/), [Tensorflow](https://www.tensorflow.org/), [Flutter](https://flutter.dev/), [Material Design](https://m3.material.io/), and [Google Cloud](https://cloud.google.com/) to ensure we provide meaningful integrations across the developer workflow. </docs-card> </docs-card-container> <docs-callout title="Join the momentum!"> <docs-pill-row> <docs-pill href="roadmap" title="Read Angular's roadmap"/> <docs-pill href="playground" title="Try out our playground"/> <docs-pill href="tutorials" title="Learn with tutorials"/> <docs-pill href="https://youtube.com/playlist?list=PL1w1q3fL4pmj9k1FrJ3Pe91EPub2_h4jF" title="Watch our YouTube course"/> <docs-pill href="api" title="Reference our APIs"/> </docs-pill-row> </docs-callout>
{ "commit_id": "cb34e406ba", "end_byte": 10102, "start_byte": 7550, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/what-is-angular.md" }
angular/adev/src/content/introduction/BUILD.bazel_0_266
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "introduction", srcs = glob([ "*.md", ]), data = [ "//adev/src/assets/images:what_is_angular.svg", ], visibility = ["//adev:__subpackages__"], )
{ "commit_id": "cb34e406ba", "end_byte": 266, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/BUILD.bazel" }
angular/adev/src/content/introduction/installation.md_0_3372
<docs-decorative-header title="Installation" imgSrc="adev/src/assets/images/what_is_angular.svg"> <!-- markdownlint-disable-line --> </docs-decorative-header> Get started with Angular quickly with online starters or locally with your terminal. ## Play Online If you just want to play around with Angular in your browser without setting up a project, you can use our online sandbox: <docs-card-container> <docs-card title="" href="/playground" link="Open on Playground"> The fastest way to play with an Angular app. No setup required. </docs-card> </docs-card-container> ## Setup a new project locally If you're starting a new project, you'll most likely want to create a local project so that you can use tooling such as Git. ### Prerequisites - **Node.js** - v[^18.19.1 or newer](/reference/versions) - **Text editor** - We recommend [Visual Studio Code](https://code.visualstudio.com/) - **Terminal** - Required for running Angular CLI commands ### Instructions The following guide will walk you through setting up a local Angular project. #### Install Angular CLI Open a terminal (if you're using [Visual Studio Code](https://code.visualstudio.com/), you can open an [integrated terminal](https://code.visualstudio.com/docs/editor/integrated-terminal)) and run the following command: <docs-code language="shell"> npm install -g @angular/cli </docs-code> If you are having issues running this command in Windows or Unix, check out the [CLI docs](/tools/cli/setup-local#install-the-angular-cli) for more info. #### Create a new project In your terminal, run the CLI command `ng new` with the desired project name. In the following examples, we'll be using the example project name of `my-first-angular-app`. <docs-code language="shell"> ng new <project-name> </docs-code> You will be presented with some configuration options for your project. Use the arrow and enter keys to navigate and select which options you desire. If you don't have any preferences, just hit the enter key to take the default options and continue with the setup. After you select the configuration options and the CLI runs through the setup, you should see the following message: ```shell ✔ Packages installed successfully. Successfully initialized git. ``` At this point, you're now ready to run your project locally! #### Running your new project locally In your terminal, switch to your new Angular project. <docs-code language="shell"> cd my-first-angular-app </docs-code> All of your dependencies should be installed at this point (which you can verify by checking for the existent for a `node_modules` folder in your project), so you can start your project by running the command: <docs-code language="shell"> npm start </docs-code> If everything is successful, you should see a similar confirmation message in your terminal: ```shell Watch mode enabled. Watching for file changes... NOTE: Raw file sizes do not reflect development server per-request transformations. ➜ Local: http://localhost:4200/ ➜ press h + enter to show help ``` And now you can visit the path in `Local` (e.g., `http://localhost:4200`) to see your application. Happy coding! 🎉 ## Next steps Now that you've created your Angular project, you can learn more about Angular in our [Essentials guide](/essentials) or choose a topic in our in-depth guides!
{ "commit_id": "cb34e406ba", "end_byte": 3372, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/installation.md" }
angular/adev/src/content/introduction/essentials/overview.md_0_1049
<docs-decorative-header title="Overview" imgSrc="adev/src/assets/images/what_is_angular.svg"> <!-- markdownlint-disable-line --> </docs-decorative-header> ## Before you start Like most modern frameworks, Angular expects you to be familiar with HTML, CSS and JavaScript. If you are totally new to frontend development, it might not be the best idea to jump right into a framework as your first step. Grasp the basics and then come back! Prior experience with other frameworks helps, but is not required. In addition, you should be familiar with the following concepts: - [JavaScript Classes](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes) - [TypeScript fundamentals](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) - [TypeScript Decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) ## Next Step Ready to jump in? It's time to learn about components in Angular! <docs-pill-row> <docs-pill title="Composing with Components" href="essentials/components" /> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 1049, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/essentials/overview.md" }
angular/adev/src/content/introduction/essentials/rendering-dynamic-templates.md_0_3414
<docs-decorative-header title="Rendering Dynamic Templates" imgSrc="adev/src/assets/images/templates.svg"> <!-- markdownlint-disable-line --> Use Angular's template syntax to create dynamic HTML. </docs-decorative-header> What you've learned so far enables you to break an application up into components of HTML, but this limits you to static templates (i.e., content that doesn't change). The next step is to learn how to make use of Angular's template syntax to create dynamic HTML. ## Rendering Dynamic Data When you need to display dynamic content in your template, Angular uses the double curly brace syntax in order to distinguish between static and dynamic content. Here is a simplified example from a `TodoListItem` component. ```angular-ts @Component({ selector: 'todo-list-item', template: ` <p>Title: {{ taskTitle }}</p> `, }) export class TodoListItem { taskTitle = 'Read cup of coffee'; } ``` When Angular renders the component you'll see the output: ```angular-html <p>Title: Read cup of coffee</p> ``` This syntax declares an **interpolation** between the dynamic data property inside of the HTML. As a result, whenever the data changes, Angular will automatically update the DOM reflecting the new value of the property. ## Dynamic Properties When you need to dynamically set the value of standard DOM properties on an HTML element, the property is wrapped in square brackets to inform Angular that the declared value should be interpreted as a JavaScript-like statement ([with some Angular enhancements](guide/templates/binding#render-dynamic-text-with-text-interpolation)) instead of a plain string. For example, a common example of dynamically updating properties in your HTML is determining whether the form submit button should be disabled based on whether the form is valid or not. Wrap the desired property in square brackets to tell Angular that the assigned value is dynamic (i.e., not a static string). ```angular-ts @Component({ selector: 'sign-up-form', template: ` <button type="submit" [disabled]="formIsInvalid">Submit</button> `, }) export class SignUpForm { formIsInvalid = true; } ``` In this example, because `formIsInvalid` is true, the rendered HTML would be: ```angular-html <button type="submit" disabled>Submit</button> ``` ## Dynamic Attributes In the event you want to dynamically bind custom HTML attributes (e.g., `aria-`, `data-`, etc.), you might be inclined to wrap the custom attributes with the same square brackets. ```angular-ts @Component({ standalone: true, template: ` <button [data-test-id]="testId">Primary CTA</button> `, }) export class AppBanner { testId = 'main-cta'; } ``` Unfortunately, this will not work because custom HTML attributes are not standard DOM properties. In order for this to work as intended, we need to prepend the custom HTML attribute with the `attr.` prefix. ```angular-ts @Component({ standalone: true, template: ` <button [attr.data-test-id]="testId">Primary CTA</button> `, }) export class AppBanner { testId = 'main-cta'; } ``` ## Next Step Now that you have dynamic data and templates in the application, it's time to learn how to enhance templates by conditionally hiding or showing certain elements, looping over elements, and more. <docs-pill-row> <docs-pill title="Conditionals and Loops" href="essentials/conditionals-and-loops" /> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 3414, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/essentials/rendering-dynamic-templates.md" }
angular/adev/src/content/introduction/essentials/conditionals-and-loops.md_0_3917
<docs-decorative-header title="Conditionals and Loops" imgSrc="adev/src/assets/images/directives.svg"> <!-- markdownlint-disable-line --> Conditionally show and/or repeat content based on dynamic data. </docs-decorative-header> One of the advantages of using a framework like Angular is that it provides built-in solutions for common problems that developers encounter. Examples of this include: displaying content based on a certain condition, rendering a list of items based on application data, etc. To solve this problem, Angular uses built-in control flow blocks, which tell the framework when and how your templates should be rendered. ## Conditional rendering One of the most common scenarios that developers encounter is the desire to show or hide content in templates based on a condition. A common example of this is whether or not to display certain controls on the screen based on the user's permission level. ### `@if` block Similar to JavaScript's `if` statement, Angular uses `@if` control flow blocks to conditionally hide and show part of a template and its contents. ```angular-ts // user-controls.component.ts @Component({ standalone: true, selector: 'user-controls', template: ` @if (isAdmin) { <button>Erase database</button> } `, }) export class UserControls { isAdmin = true; } ``` In this example, Angular only renders the `<button>` element if the `isAdmin` property is true. Otherwise, it does not appear on the page. ### `@else` block While the `@if` block can be helpful in many situations, it's common to also show fallback UI when the condition is not met. For example, in the `UserControls` component, rather than show a blank screen, it would be helpful to users to know that they're not able to see anything because they're not authenticated. When you need a fallback, similar to JavaScript's `else` clause, add an `@else` block to accomplish the same effect. ```angular-ts // user-controls.component.ts @Component({ standalone: true, selector: 'user-controls', template: ` @if (isAdmin) { <button>Erase database</button> } @else { <p>You are not authorized.</p> } `, }) export class UserControls { isAdmin = true; } ``` ## Rendering a list Another common scenario developers encounter is the need to render a list of items. ### `@for` block Similar to JavaScript’s `for...of` loops, Angular provides the `@for` block for rendering repeated elements. ```angular-html <!-- ingredient-list.component.html --> <ul> @for (ingredient of ingredientList; track ingredient.name) { <li>{{ ingredient.quantity }} - {{ ingredient.name }}</li> } </ul> ``` ```angular-ts // ingredient-list.component.ts @Component({ standalone: true, selector: 'ingredient-list', templateUrl: './ingredient-list.component.html', }) export class IngredientList { ingredientList = [ {name: 'noodles', quantity: 1}, {name: 'miso broth', quantity: 1}, {name: 'egg', quantity: 2}, ]; } ``` However, unlike a standard `for...of` loop, you might've noticed that there's an additional `track` keyword. #### `track` property When Angular renders a list of elements with `@for`, those items can later change or move. Angular needs to track each element through any reordering, usually by treating a property of the item as a unique identifier or key. This ensures any updates to the list are reflected correctly in the UI and tracked properly within Angular, especially in the case of stateful elements or animations. To accomplish this, we can provide a unique key to Angular with the `track` keyword. ## Next Step With the ability to determine when and how templates are rendered, it's time to learn how we handle an important aspect of most applications: handling user input. <docs-pill-row> <docs-pill title="Handling User Interaction" href="essentials/handling-user-interaction" /> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 3917, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/essentials/conditionals-and-loops.md" }
angular/adev/src/content/introduction/essentials/components.md_0_3900
<docs-decorative-header title="Components" imgSrc="adev/src/assets/images/components.svg"> <!-- markdownlint-disable-line --> The fundamental building block for creating applications in Angular. </docs-decorative-header> Components provide structure for organizing your project into easy-to-understand parts with clear responsibilities so that your code is maintainable and scalable. Here is an example of how a Todo application could be broken down into a tree of components. ```mermaid flowchart TD A[TodoApp]-->B A-->C B[TodoList]-->D C[TodoMetrics] D[TodoListItem] ``` In this guide, we'll take a look at how to create and use components in Angular. ## Defining a Component Every component has the following core properties: 1. A `@Component`[decorator](https://www.typescriptlang.org/docs/handbook/decorators.html) that contains some configuration 2. An HTML template that controls what renders into the DOM 3. A [CSS selector](https://developer.mozilla.org/docs/Learn/CSS/Building_blocks/Selectors) that defines how the component is used in HTML 4. A TypeScript class with behaviors such as managing state, handling user input, or fetching data from a server. Here is a simplified example of a TodoListItem component. ```angular-ts // todo-list-item.component.ts @Component({ selector: 'todo-list-item', template: ` <li>(TODO) Read Angular Essentials Guide</li> `, }) export class TodoListItem { /* Component behavior is defined in here */ } ``` Other common metadata that you'll also see in components include: - `standalone: true` — The recommended approach of streamlining the authoring experience of components - `styles` — A string or array of strings that contains any CSS styles you want applied to the component Knowing this, here is an updated version of our `TodoListItem` component. ```angular-ts // todo-list-item.component.ts @Component({ standalone: true, selector: 'todo-list-item', template: ` <li>(TODO) Read Angular Essentials Guide</li> `, styles: ` li { color: red; font-weight: 300; } `, }) export class TodoListItem { /* Component behavior is defined in here */ } ``` ### Separating HTML and CSS into separate files For teams that prefer managing their HTML and/or CSS in separate files, Angular provides two additional properties: `templateUrl` and `styleUrl`. Using the previous `TodoListItem` component, the alternative approach looks like: ```angular-ts // todo-list-item.component.ts @Component({ standalone: true, selector: 'todo-list-item', templateUrl: './todo-list-item.component.html', styleUrl: './todo-list-item.component.css', }) export class TodoListItem { /* Component behavior is defined in here */ } ``` ```angular-html <!-- todo-list-item.component.html --> <li>(TODO) Read Angular Essentials Guide</li> ``` ```css /* todo-list-item.component.css */ li { color: red; font-weight: 300; } ``` ## Using a Component One advantage of component architecture is that your application is modular. In other words, components can be used in other components. To use a component, you need to: 1. Import the component into the file 2. Add it to the component's `imports` array 3. Use the component's selector in the `template` Here's an example of a `TodoList` component importing the `TodoListItem` component from before: ```angular-ts // todo-list.component.ts import {TodoListItem} from './todo-list-item.component.ts'; @Component({ standalone: true, imports: [TodoListItem], template: ` <ul> <todo-list-item></todo-list-item> </ul> `, }) export class TodoList {} ``` ## Next Step Now that you know how components work in Angular, it's time to learn how we add and manage dynamic data in our application. <docs-pill-row> <docs-pill title="Managing Dynamic Data" href="essentials/managing-dynamic-data" /> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 3900, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/essentials/components.md" }
angular/adev/src/content/introduction/essentials/managing-dynamic-data.md_0_1980
<docs-decorative-header title="Managing Dynamic Data" imgSrc="adev/src/assets/images/signals.svg"> <!-- markdownlint-disable-line --> Define component state and behavior to manage dynamic data. </docs-decorative-header> Now that we have learned the basic structure for a component, let’s learn how you can define the component’s data (i.e., state) and behavior. ## What is state? Components let you neatly encapsulate responsibility for discrete parts of your application. For example, a `SignUpForm` component might need to keep track of whether the form is valid or not before allowing users to take a specific action. As a result, the various properties that a component needs to track is often referred to as "state." ## Defining state To define state, you use [class fields syntax](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/Public_class_fields) inside of your component. For example, using the `TodoListItem` component, create two properties that you want to track: 1. `taskTitle` — What the title of the task is 2. `isComplete` — Whether or not the task is complete ```angular-ts // todo-list-item.component.ts @Component({ ... }) export class TodoListItem { taskTitle = ''; isComplete = false; } ``` ## Updating state When you want to update state, this is typically accomplished by defining methods in the component class that can access the various class fields with the `this` keyword. ```angular-ts // todo-list-item.component.ts @Component({ ... }) export class TodoListItem { taskTitle = ''; isComplete = false; completeTask() { this.isComplete = true; } updateTitle(newTitle: string) { this.taskTitle = newTitle; } } ``` ## Next Step Now that you have learned how to declare and manage dynamic data, it's time to learn how to use that data inside of templates. <docs-pill-row> <docs-pill title="Rendering Dynamic Templates" href="essentials/rendering-dynamic-templates" /> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 1980, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/essentials/managing-dynamic-data.md" }
angular/adev/src/content/introduction/essentials/handling-user-interaction.md_0_1735
<docs-decorative-header title="Handling User Interaction" imgSrc="adev/src/assets/images/overview.svg"> <!-- markdownlint-disable-line --> Handle user interaction in your application. </docs-decorative-header> The ability to handle user interaction and then work with - it is one of the key aspects of building dynamic applications. In this guide, we'll take a look at simple user interaction - event handling. ## Event Handling You can add an event handler to an element by: 1. Adding an attribute with the events name inside of parentheses 2. Specify what JavaScript statement you want to run when it fires ```angular-html <button (click)="save()">Save</button> ``` For example, if we wanted to create a button that would run a `transformText` function when the `click` event is fired, it would look like the following: ```angular-ts // text-transformer.component.ts @Component({ standalone: true, selector: 'text-transformer', template: ` <p>{{ announcement }}</p> <button (click)="transformText()">Abracadabra!</button> `, }) export class TextTransformer { announcement = 'Hello again Angular!'; transformText() { this.announcement = this.announcement.toUpperCase(); } } ``` Other common examples of event listeners include: ```angular-html <input (keyup)="validateInput()" /> <input (keydown)="updateInput()" /> ``` ### $event If you need to access the [event](https://developer.mozilla.org/docs/Web/API/Event) object, Angular provides an implicit `$event` variable that you can pass to a function: ```angular-html <button (click)="createUser($event)">Submit</button> ``` ## Next Step <docs-pill-row> <docs-pill title="Sharing Logic" href="essentials/sharing-logic" /> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 1735, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/essentials/handling-user-interaction.md" }
angular/adev/src/content/introduction/essentials/next-steps.md_0_1073
<docs-decorative-header title="Next Steps" imgSrc="adev/src/assets/images/roadmap.svg"> <!-- markdownlint-disable-line --> </docs-decorative-header> Now that you have been introduced to core concepts of Angular - you're ready to put what you learned into practices with our interactive tutorials and learn more with our in-depth guides. ## Playground <docs-pill-row> <docs-pill title="Play with Angular!" href="playground" /> </docs-pill-row> ## Tutorials <docs-pill-row> <docs-pill title="Learn Angular's fundamentals" href="tutorials/learn-angular" /> <docs-pill title="Build your first Angular app" href="tutorials/first-app" /> </docs-pill-row> ## In-depth Guides Here are some in-depth guides you might be interested in reading: <docs-pill-row> <docs-pill title="Components In-depth Guide" href="guide/components/importing" /> <docs-pill title="Template In-depth Guide" href="guide/templates" /> <docs-pill title="Forms In-depth Guide" href="/guide/forms" /> </docs-pill-row> To see the rest of our in-depth guides, check out the main navigation.
{ "commit_id": "cb34e406ba", "end_byte": 1073, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/essentials/next-steps.md" }
angular/adev/src/content/introduction/essentials/BUILD.bazel_0_649
load("//adev/shared-docs:index.bzl", "generate_guides") generate_guides( name = "essentials", srcs = glob([ "*.md", ]), data = [ "//adev/src/assets/images:components.svg", "//adev/src/assets/images:dependency_injection.svg", "//adev/src/assets/images:directives.svg", "//adev/src/assets/images:overview.svg", "//adev/src/assets/images:roadmap.svg", "//adev/src/assets/images:signals.svg", "//adev/src/assets/images:templates.svg", "//adev/src/assets/images:what_is_angular.svg", ], mermaid_blocks = True, visibility = ["//adev:__subpackages__"], )
{ "commit_id": "cb34e406ba", "end_byte": 649, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/essentials/BUILD.bazel" }
angular/adev/src/content/introduction/essentials/sharing-logic.md_0_2225
<docs-decorative-header title="Sharing Code" imgSrc="adev/src/assets/images/dependency_injection.svg"> <!-- markdownlint-disable-line --> Dependency injection allows you to share code. </docs-decorative-header> When you need to share logic between components, Angular leverages the design pattern of [dependency injection](guide/di) that allows you to create a “service” which allows you to inject code into components while managing it from a single source of truth. ## What are services? Services are reusable pieces of code that can be injected Similar to defining a component, services are comprised of the following: - A **TypeScript decorator** that declares the class as an Angular service via `@Injectable` and allows you to define what part of the application can access the service via the `providedIn` property (which is typically `'root'`) to allow a service to be accessed anywhere within the application. - A **TypeScript class** that defines the desired code that will be accessible when the service is injected Here is an example of a `Calculator` service. ```angular-ts import {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root', }) export class CalculatorService { add(x: number, y: number) { return x + y; } } ``` ## How to use a service When you want to use a service in a component, you need to: 1. Import the service 2. Declare a class field where the service is injected. Assign the class field to the result of the call of the built-in function `inject` which creates the service Here’s what it might look like in the `Receipt` component: ```angular-ts import { Component, inject } from '@angular/core'; import { CalculatorService } from './calculator.service'; @Component({ selector: 'app-receipt', template: `<h1>The total is {{ totalCost }}</h1>`, }) export class Receipt { private calculatorService = inject(CalculatorService); totalCost = this.calculatorService.add(50, 25); } ``` In this example, the `CalculatorService` is being used by calling the Angular function `inject` and passing in the service to it. ## Next Step <docs-pill-row> <docs-pill title="Next Steps After Essentials" href="essentials/next-steps" /> </docs-pill-row>
{ "commit_id": "cb34e406ba", "end_byte": 2225, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/introduction/essentials/sharing-logic.md" }
angular/adev/src/content/api-examples/test-utils/index.ts_0_839
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* tslint:disable:no-console */ import {logging, WebDriver} from 'selenium-webdriver'; declare var browser: WebDriver; declare var expect: any; // TODO (juliemr): remove this method once this becomes a protractor plugin export async function verifyNoBrowserErrors() { const browserLog = await browser.manage().logs().get('browser'); const collectedErrors: any[] = []; browserLog.forEach((logEntry) => { const msg = logEntry.message; console.log('>> ' + msg, logEntry); if (logEntry.level.value >= logging.Level.INFO.value) { collectedErrors.push(msg); } }); expect(collectedErrors).toEqual([]); }
{ "commit_id": "cb34e406ba", "end_byte": 839, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/test-utils/index.ts" }
angular/adev/src/content/api-examples/upgrade/upgrade_example.bzl_0_2183
load("//tools:defaults.bzl", "esbuild", "http_server", "ng_module", "protractor_web_test_suite", "ts_library") """ Macro that can be used to create the Bazel targets for an "upgrade" example. Since the upgrade examples bootstrap their application manually, and we cannot serve all examples, we need to define the devserver for each example. This macro reduces code duplication for defining these targets. """ def create_upgrade_example_targets(name, srcs, e2e_srcs, entry_point, assets = []): ng_module( name = "%s_sources" % name, srcs = srcs, deps = [ "@npm//@types/angular", "@npm//@types/jasmine", "//packages/core", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/upgrade/static", "//packages/core/testing", "//packages/upgrade/static/testing", ], tsconfig = "//packages/examples/upgrade:tsconfig-build.json", ) ts_library( name = "%s_e2e_lib" % name, srcs = e2e_srcs, testonly = True, deps = [ "@npm//@types/jasminewd2", "@npm//protractor", "//packages/examples/test-utils", "//packages/private/testing", ], tsconfig = "//packages/examples:tsconfig-e2e.json", ) esbuild( name = "app_bundle", entry_point = entry_point, deps = [":%s_sources" % name], ) http_server( name = "devserver", additional_root_paths = ["angular/packages/examples/upgrade"], srcs = [ "//packages/examples/upgrade:index.html", "//packages/zone.js/bundles:zone.umd.js", "@npm//:node_modules/angular-1.8/angular.js", "@npm//:node_modules/reflect-metadata/Reflect.js", ] + assets, deps = [":app_bundle"], ) protractor_web_test_suite( name = "%s_protractor" % name, on_prepare = "//packages/examples/upgrade:start-server.js", server = ":devserver", deps = [ ":%s_e2e_lib" % name, "@npm//selenium-webdriver", ], )
{ "commit_id": "cb34e406ba", "end_byte": 2183, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/upgrade_example.bzl" }
angular/adev/src/content/api-examples/upgrade/index.html_0_632
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Angular Upgrade Examples</title> <base href="/" /> <!-- Prevent the browser from requesting any favicon. This could throw off the console output checks. --> <link rel="icon" href="data:," /> </head> <body> <example-app>Loading...</example-app> <script src="/angular/packages/zone.js/bundles/zone.umd.js"></script> <script src="/npm/node_modules/angular-1.8/angular.js"></script> <script src="/npm/node_modules/reflect-metadata/Reflect.js"></script> <script src="/app_bundle.js"></script> </body> </html>
{ "commit_id": "cb34e406ba", "end_byte": 632, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/index.html" }
angular/adev/src/content/api-examples/upgrade/start-server.js_0_552
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ const protractorUtils = require('@bazel/protractor/protractor-utils'); const protractor = require('protractor'); module.exports = async function (config) { const {port} = await protractorUtils.runServer(config.workspace, config.server, '--port', []); const serverUrl = `http://localhost:${port}`; protractor.browser.baseUrl = serverUrl; };
{ "commit_id": "cb34e406ba", "end_byte": 552, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/start-server.js" }
angular/adev/src/content/api-examples/upgrade/static/ts/full/styles.css_0_224
ng2-heroes { border: solid black 2px; display: block; padding: 5px; } ng1-hero { border: solid green 2px; margin-top: 5px; padding: 5px; display: block; } .title { background-color: blue; color: white; }
{ "commit_id": "cb34e406ba", "end_byte": 224, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/full/styles.css" }
angular/adev/src/content/api-examples/upgrade/static/ts/full/module.ts_0_6774
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docplaster import { Component, Directive, ElementRef, EventEmitter, Injectable, Injector, Input, NgModule, Output, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import { downgradeComponent, downgradeInjectable, UpgradeComponent, UpgradeModule, } from '@angular/upgrade/static'; declare var angular: ng.IAngularStatic; export interface Hero { name: string; description: string; } // #docregion ng1-text-formatter-service export class TextFormatter { titleCase(value: string) { return value.replace(/((^|\s)[a-z])/g, (_, c) => c.toUpperCase()); } } // #enddocregion // #docregion ng2-heroes // This Angular component will be "downgraded" to be used in AngularJS @Component({ selector: 'ng2-heroes', // This template uses the upgraded `ng1-hero` component // Note that because its element is compiled by Angular we must use camelCased attribute names template: ` <header><ng-content selector="h1"></ng-content></header> <ng-content selector=".extra"></ng-content> <div *ngFor="let hero of heroes"> <ng1-hero [hero]="hero" (onRemove)="removeHero.emit(hero)"> <strong>Super Hero</strong> </ng1-hero> </div> <button (click)="addHero.emit()">Add Hero</button> `, standalone: false, }) export class Ng2HeroesComponent { @Input() heroes!: Hero[]; @Output() addHero = new EventEmitter(); @Output() removeHero = new EventEmitter(); } // #enddocregion // #docregion ng2-heroes-service // This Angular service will be "downgraded" to be used in AngularJS @Injectable() export class HeroesService { heroes: Hero[] = [ {name: 'superman', description: 'The man of steel'}, {name: 'wonder woman', description: 'Princess of the Amazons'}, {name: 'thor', description: 'The hammer-wielding god'}, ]; // #docregion use-ng1-upgraded-service constructor(textFormatter: TextFormatter) { // Change all the hero names to title case, using the "upgraded" AngularJS service this.heroes.forEach((hero: Hero) => (hero.name = textFormatter.titleCase(hero.name))); } // #enddocregion addHero() { this.heroes = this.heroes.concat([ {name: 'Kamala Khan', description: 'Epic shape-shifting healer'}, ]); } removeHero(hero: Hero) { this.heroes = this.heroes.filter((item: Hero) => item !== hero); } } // #enddocregion // #docregion ng1-hero-wrapper // This Angular directive will act as an interface to the "upgraded" AngularJS component @Directive({ selector: 'ng1-hero', standalone: false, }) export class Ng1HeroComponentWrapper extends UpgradeComponent { // The names of the input and output properties here must match the names of the // `<` and `&` bindings in the AngularJS component that is being wrapped @Input() hero!: Hero; @Output() onRemove: EventEmitter<void> = new EventEmitter(); constructor(elementRef: ElementRef, injector: Injector) { // We must pass the name of the directive as used by AngularJS to the super super('ng1Hero', elementRef, injector); } } // #enddocregion // #docregion ng2-module // This NgModule represents the Angular pieces of the application @NgModule({ declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper], providers: [ HeroesService, // #docregion upgrade-ng1-service // Register an Angular provider whose value is the "upgraded" AngularJS service {provide: TextFormatter, useFactory: (i: any) => i.get('textFormatter'), deps: ['$injector']}, // #enddocregion ], // We must import `UpgradeModule` to get access to the AngularJS core services imports: [BrowserModule, UpgradeModule], }) // #docregion bootstrap-ng1 export class Ng2AppModule { // #enddocregion ng2-module constructor(private upgrade: UpgradeModule) {} ngDoBootstrap() { // We bootstrap the AngularJS app. this.upgrade.bootstrap(document.body, [ng1AppModule.name]); } // #docregion ng2-module } // #enddocregion bootstrap-ng1 // #enddocregion ng2-module // This Angular 1 module represents the AngularJS pieces of the application export const ng1AppModule: ng.IModule = angular.module('ng1AppModule', []); // #docregion ng1-hero // This AngularJS component will be "upgraded" to be used in Angular ng1AppModule.component('ng1Hero', { bindings: {hero: '<', onRemove: '&'}, transclude: true, template: `<div class="title" ng-transclude></div> <h2>{{ $ctrl.hero.name }}</h2> <p>{{ $ctrl.hero.description }}</p> <button ng-click="$ctrl.onRemove()">Remove</button>`, }); // #enddocregion // #docregion ng1-text-formatter-service // This AngularJS service will be "upgraded" to be used in Angular ng1AppModule.service('textFormatter', [TextFormatter]); // #enddocregion // #docregion downgrade-ng2-heroes-service // Register an AngularJS service, whose value is the "downgraded" Angular injectable. ng1AppModule.factory('heroesService', downgradeInjectable(HeroesService) as any); // #enddocregion // #docregion ng2-heroes-wrapper // This directive will act as the interface to the "downgraded" Angular component ng1AppModule.directive('ng2Heroes', downgradeComponent({component: Ng2HeroesComponent})); // #enddocregion // #docregion example-app // This is our top level application component ng1AppModule.component('exampleApp', { // We inject the "downgraded" HeroesService into this AngularJS component // (We don't need the `HeroesService` type for AngularJS DI - it just helps with TypeScript // compilation) controller: [ 'heroesService', function (heroesService: HeroesService) { this.heroesService = heroesService; }, ], // This template makes use of the downgraded `ng2-heroes` component // Note that because its element is compiled by AngularJS we must use kebab-case attributes // for inputs and outputs template: `<link rel="stylesheet" href="./styles.css"> <ng2-heroes [heroes]="$ctrl.heroesService.heroes" (add-hero)="$ctrl.heroesService.addHero()" (remove-hero)="$ctrl.heroesService.removeHero($event)"> <h1>Heroes</h1> <p class="extra">There are {{ $ctrl.heroesService.heroes.length }} heroes.</p> </ng2-heroes>`, }); // #enddocregion // #docregion bootstrap-ng2 // We bootstrap the Angular module as we would do in a normal Angular app. // (We are using the dynamic browser platform as this example has not been compiled AOT.) platformBrowserDynamic().bootstrapModule(Ng2AppModule); // #enddocregion
{ "commit_id": "cb34e406ba", "end_byte": 6774, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/full/module.ts" }
angular/adev/src/content/api-examples/upgrade/static/ts/full/module.spec.ts_0_1476
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion angular-setup import {TestBed} from '@angular/core/testing'; import { createAngularJSTestingModule, createAngularTestingModule, } from '@angular/upgrade/static/testing'; import {HeroesService, ng1AppModule, Ng2AppModule} from './module'; const {module, inject} = (window as any).angular.mock; // #enddocregion angular-setup describe('HeroesService (from Angular)', () => { // #docregion angular-setup beforeEach(() => { TestBed.configureTestingModule({ imports: [createAngularTestingModule([ng1AppModule.name]), Ng2AppModule], }); }); // #enddocregion angular-setup // #docregion angular-spec it('should have access to the HeroesService', () => { const heroesService = TestBed.inject(HeroesService); expect(heroesService).toBeDefined(); }); // #enddocregion angular-spec }); describe('HeroesService (from AngularJS)', () => { // #docregion angularjs-setup beforeEach(module(createAngularJSTestingModule([Ng2AppModule]))); beforeEach(module(ng1AppModule.name)); // #enddocregion angularjs-setup // #docregion angularjs-spec it('should have access to the HeroesService', inject((heroesService: HeroesService) => { expect(heroesService).toBeDefined(); })); // #enddocregion angularjs-spec });
{ "commit_id": "cb34e406ba", "end_byte": 1476, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/full/module.spec.ts" }
angular/adev/src/content/api-examples/upgrade/static/ts/full/e2e_test/static_full_spec.ts_0_1914
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../../../../../packages/examples/test-utils/index'; function loadPage() { browser.rootEl = 'example-app'; browser.get('/'); } describe('upgrade/static (full)', () => { beforeEach(loadPage); afterEach(verifyNoBrowserErrors); it('should render the `ng2-heroes` component', () => { expect(element(by.css('h1')).getText()).toEqual('Heroes'); expect(element.all(by.css('p')).get(0).getText()).toEqual('There are 3 heroes.'); }); it('should render 3 ng1-hero components', () => { const heroComponents = element.all(by.css('ng1-hero')); expect(heroComponents.count()).toEqual(3); }); it('should add a new hero when the "Add Hero" button is pressed', () => { const addHeroButton = element.all(by.css('button')).last(); expect(addHeroButton.getText()).toEqual('Add Hero'); addHeroButton.click(); const heroComponents = element.all(by.css('ng1-hero')); expect(heroComponents.last().element(by.css('h2')).getText()).toEqual('Kamala Khan'); }); it('should remove a hero when the "Remove" button is pressed', () => { let firstHero = element.all(by.css('ng1-hero')).get(0); expect(firstHero.element(by.css('h2')).getText()).toEqual('Superman'); const removeHeroButton = firstHero.element(by.css('button')); expect(removeHeroButton.getText()).toEqual('Remove'); removeHeroButton.click(); const heroComponents = element.all(by.css('ng1-hero')); expect(heroComponents.count()).toEqual(2); firstHero = element.all(by.css('ng1-hero')).get(0); expect(firstHero.element(by.css('h2')).getText()).toEqual('Wonder Woman'); }); });
{ "commit_id": "cb34e406ba", "end_byte": 1914, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/full/e2e_test/static_full_spec.ts" }
angular/adev/src/content/api-examples/upgrade/static/ts/lite/styles.css_0_224
ng2-heroes { border: solid black 2px; display: block; padding: 5px; } ng1-hero { border: solid green 2px; margin-top: 5px; padding: 5px; display: block; } .title { background-color: blue; color: white; }
{ "commit_id": "cb34e406ba", "end_byte": 224, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/lite/styles.css" }
angular/adev/src/content/api-examples/upgrade/static/ts/lite/module.ts_0_7635
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docplaster import { Component, Directive, ElementRef, EventEmitter, Inject, Injectable, Injector, Input, NgModule, Output, StaticProvider, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; // #docregion basic-how-to import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; // #enddocregion /* tslint:disable: no-duplicate-imports */ // #docregion basic-how-to import {downgradeComponent, downgradeModule, UpgradeComponent} from '@angular/upgrade/static'; // #enddocregion /* tslint:enable: no-duplicate-imports */ declare var angular: ng.IAngularStatic; interface Hero { name: string; description: string; } // This Angular service will use an "upgraded" AngularJS service. @Injectable() class HeroesService { heroes: Hero[] = [ {name: 'superman', description: 'The man of steel'}, {name: 'wonder woman', description: 'Princess of the Amazons'}, {name: 'thor', description: 'The hammer-wielding god'}, ]; constructor(@Inject('titleCase') titleCase: (v: string) => string) { // Change all the hero names to title case, using the "upgraded" AngularJS service. this.heroes.forEach((hero: Hero) => (hero.name = titleCase(hero.name))); } addHero() { const newHero: Hero = {name: 'Kamala Khan', description: 'Epic shape-shifting healer'}; this.heroes = this.heroes.concat([newHero]); return newHero; } removeHero(hero: Hero) { this.heroes = this.heroes.filter((item: Hero) => item !== hero); } } // This Angular component will be "downgraded" to be used in AngularJS. @Component({ selector: 'ng2-heroes', // This template uses the "upgraded" `ng1-hero` component // (Note that because its element is compiled by Angular we must use camelCased attribute names.) template: ` <div class="ng2-heroes"> <header><ng-content selector="h1"></ng-content></header> <ng-content selector=".extra"></ng-content> <div *ngFor="let hero of this.heroesService.heroes"> <ng1-hero [hero]="hero" (onRemove)="onRemoveHero(hero)"> <strong>Super Hero</strong> </ng1-hero> </div> <button (click)="onAddHero()">Add Hero</button> </div> `, standalone: false, }) class Ng2HeroesComponent { @Output() private addHero = new EventEmitter<Hero>(); @Output() private removeHero = new EventEmitter<Hero>(); constructor( @Inject('$rootScope') private $rootScope: ng.IRootScopeService, public heroesService: HeroesService, ) {} onAddHero() { const newHero = this.heroesService.addHero(); this.addHero.emit(newHero); // When a new instance of an "upgraded" component - such as `ng1Hero` - is created, we want to // run a `$digest` to initialize its bindings. Here, the component will be created by `ngFor` // asynchronously, thus we have to schedule the `$digest` to also happen asynchronously. this.$rootScope.$applyAsync(); } onRemoveHero(hero: Hero) { this.heroesService.removeHero(hero); this.removeHero.emit(hero); } } // This Angular directive will act as an interface to the "upgraded" AngularJS component. @Directive({ selector: 'ng1-hero', standalone: false, }) class Ng1HeroComponentWrapper extends UpgradeComponent { // The names of the input and output properties here must match the names of the // `<` and `&` bindings in the AngularJS component that is being wrapped. @Input() hero!: Hero; @Output() onRemove: EventEmitter<void> = new EventEmitter(); constructor(elementRef: ElementRef, injector: Injector) { // We must pass the name of the directive as used by AngularJS to the super. super('ng1Hero', elementRef, injector); } } // This Angular module represents the Angular pieces of the application. @NgModule({ imports: [BrowserModule], declarations: [Ng2HeroesComponent, Ng1HeroComponentWrapper], providers: [ HeroesService, // Register an Angular provider whose value is the "upgraded" AngularJS service. {provide: 'titleCase', useFactory: (i: any) => i.get('titleCase'), deps: ['$injector']}, ], // Note that there are no `bootstrap` components, since the "downgraded" component // will be instantiated by ngUpgrade. }) class MyLazyAngularModule { // Empty placeholder method to prevent the `Compiler` from complaining. ngDoBootstrap() {} } // #docregion basic-how-to // The function that will bootstrap the Angular module (when/if necessary). // (This would be omitted if we provided an `NgModuleFactory` directly.) const ng2BootstrapFn = (extraProviders: StaticProvider[]) => platformBrowserDynamic(extraProviders).bootstrapModule(MyLazyAngularModule); // #enddocregion // (We are using the dynamic browser platform, as this example has not been compiled AOT.) // #docregion basic-how-to // This AngularJS module represents the AngularJS pieces of the application. const myMainAngularJsModule = angular.module('myMainAngularJsModule', [ // We declare a dependency on the "downgraded" Angular module. downgradeModule(ng2BootstrapFn), // or // downgradeModule(MyLazyAngularModuleFactory) ]); // #enddocregion // This AngularJS component will be "upgraded" to be used in Angular. myMainAngularJsModule.component('ng1Hero', { bindings: {hero: '<', onRemove: '&'}, transclude: true, template: ` <div class="ng1-hero"> <div class="title" ng-transclude></div> <h2>{{ $ctrl.hero.name }}</h2> <p>{{ $ctrl.hero.description }}</p> <button ng-click="$ctrl.onRemove()">Remove</button> </div> `, }); // This AngularJS service will be "upgraded" to be used in Angular. myMainAngularJsModule.factory( 'titleCase', () => (value: string) => value.replace(/(^|\s)[a-z]/g, (m) => m.toUpperCase()), ); // This directive will act as the interface to the "downgraded" Angular component. myMainAngularJsModule.directive( 'ng2Heroes', downgradeComponent({ component: Ng2HeroesComponent, // Optionally, disable `$digest` propagation to avoid unnecessary change detection. // (Change detection is still run when the inputs of a "downgraded" component change.) propagateDigest: false, }), ); // This is our top level application component. myMainAngularJsModule.component('exampleApp', { // This template makes use of the "downgraded" `ng2-heroes` component, // but loads it lazily only when/if the user clicks the button. // (Note that because its element is compiled by AngularJS, // we must use kebab-case attributes for inputs and outputs.) template: ` <link rel="stylesheet" href="./styles.css"> <button ng-click="$ctrl.toggleHeroes()">{{ $ctrl.toggleBtnText() }}</button> <ng2-heroes ng-if="$ctrl.showHeroes" (add-hero)="$ctrl.setStatusMessage('Added hero ' + $event.name)" (remove-hero)="$ctrl.setStatusMessage('Removed hero ' + $event.name)"> <h1>Heroes</h1> <p class="extra">Status: {{ $ctrl.statusMessage }}</p> </ng2-heroes> `, controller: function () { this.showHeroes = false; this.statusMessage = 'Ready'; this.setStatusMessage = (msg: string) => (this.statusMessage = msg); this.toggleHeroes = () => (this.showHeroes = !this.showHeroes); this.toggleBtnText = () => `${this.showHeroes ? 'Hide' : 'Show'} heroes`; }, }); // We bootstrap the Angular module as we would do in a normal Angular app. angular.bootstrap(document.body, [myMainAngularJsModule.name]);
{ "commit_id": "cb34e406ba", "end_byte": 7635, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/lite/module.ts" }
angular/adev/src/content/api-examples/upgrade/static/ts/lite/BUILD.bazel_0_469
load("//packages/examples/upgrade:upgrade_example.bzl", "create_upgrade_example_targets") package(default_visibility = ["//visibility:public"]) create_upgrade_example_targets( name = "lite", srcs = glob( ["**/*.ts"], exclude = ["e2e_test/*"], ), assets = ["styles.css"], e2e_srcs = glob(["e2e_test/*.ts"]), entry_point = ":module.ts", ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "commit_id": "cb34e406ba", "end_byte": 469, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/lite/BUILD.bazel" }
angular/adev/src/content/api-examples/upgrade/static/ts/lite/e2e_test/static_lite_spec.ts_0_2793
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../../../../../packages/examples/test-utils/index'; import {addCustomMatchers} from './e2e_util'; function loadPage() { browser.rootEl = 'example-app'; browser.get('/'); } describe('upgrade/static (lite)', () => { let showHideBtn: ElementFinder; let ng2Heroes: ElementFinder; let ng2HeroesHeader: ElementFinder; let ng2HeroesExtra: ElementFinder; let ng2HeroesAddBtn: ElementFinder; let ng1Heroes: ElementArrayFinder; const expectHeroes = (isShown: boolean, ng1HeroCount = 3, statusMessage = 'Ready') => { // Verify the show/hide button text. expect(showHideBtn.getText()).toBe(isShown ? 'Hide heroes' : 'Show heroes'); // Verify the `<ng2-heroes>` component. expect(ng2Heroes.isPresent()).toBe(isShown); if (isShown) { expect(ng2HeroesHeader.getText()).toBe('Heroes'); expect(ng2HeroesExtra.getText()).toBe(`Status: ${statusMessage}`); } // Verify the `<ng1-hero>` components. expect(ng1Heroes.count()).toBe(isShown ? ng1HeroCount : 0); if (isShown) { ng1Heroes.each((ng1Hero) => expect(ng1Hero).toBeAHero()); } }; beforeEach(() => { showHideBtn = element(by.binding('toggleBtnText')); ng2Heroes = element(by.css('.ng2-heroes')); ng2HeroesHeader = ng2Heroes.element(by.css('h1')); ng2HeroesExtra = ng2Heroes.element(by.css('.extra')); ng2HeroesAddBtn = ng2Heroes.element(by.buttonText('Add Hero')); ng1Heroes = element.all(by.css('.ng1-hero')); }); beforeEach(addCustomMatchers); beforeEach(loadPage); afterEach(verifyNoBrowserErrors); it('should initially not render the heroes', () => expectHeroes(false)); it('should toggle the heroes when clicking the "show/hide" button', () => { showHideBtn.click(); expectHeroes(true); showHideBtn.click(); expectHeroes(false); }); it('should add a new hero when clicking the "add" button', () => { showHideBtn.click(); ng2HeroesAddBtn.click(); expectHeroes(true, 4, 'Added hero Kamala Khan'); expect(ng1Heroes.last()).toHaveName('Kamala Khan'); }); it('should remove a hero when clicking its "remove" button', () => { showHideBtn.click(); const firstHero = ng1Heroes.first(); expect(firstHero).toHaveName('Superman'); const removeBtn = firstHero.element(by.buttonText('Remove')); removeBtn.click(); expectHeroes(true, 2, 'Removed hero Superman'); expect(ng1Heroes.first()).not.toHaveName('Superman'); }); });
{ "commit_id": "cb34e406ba", "end_byte": 2793, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/lite/e2e_test/static_lite_spec.ts" }
angular/adev/src/content/api-examples/upgrade/static/ts/lite/e2e_test/e2e_util.ts_0_2263
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {by, ElementFinder} from 'protractor'; declare global { namespace jasmine { interface Matchers<T> { toBeAHero(): Promise<void>; toHaveName(exectedName: string): Promise<void>; } } } const isTitleCased = (text: string) => text.split(/\s+/).every((word) => word[0] === word[0].toUpperCase()); export function addCustomMatchers() { jasmine.addMatchers({ toBeAHero: () => ({ compare(actualNg1Hero: ElementFinder | undefined) { const getText = (selector: string) => actualNg1Hero!.element(by.css(selector)).getText(); const result = { message: 'Expected undefined to be an `ng1Hero` ElementFinder.', pass: !!actualNg1Hero && Promise.all(['.title', 'h2', 'p'].map(getText) as PromiseLike<string>[]).then( ([actualTitle, actualName, actualDescription]) => { const pass = actualTitle === 'Super Hero' && isTitleCased(actualName) && actualDescription.length > 0; const actualHero = `Hero(${actualTitle}, ${actualName}, ${actualDescription})`; result.message = `Expected ${actualHero}'${pass ? ' not' : ''} to be a real hero.`; return pass; }, ), }; return result; }, }), toHaveName: () => ({ compare(actualNg1Hero: ElementFinder | undefined, expectedName: string) { const result = { message: 'Expected undefined to be an `ng1Hero` ElementFinder.', pass: !!actualNg1Hero && actualNg1Hero .element(by.css('h2')) .getText() .then((actualName) => { const pass = actualName === expectedName; result.message = `Expected Hero(${actualName})${ pass ? ' not' : '' } to have name '${expectedName}'.`; return pass; }), }; return result; }, }), } as any); }
{ "commit_id": "cb34e406ba", "end_byte": 2263, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/lite/e2e_test/e2e_util.ts" }
angular/adev/src/content/api-examples/upgrade/static/ts/lite-multi/module.ts_0_3724
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docplaster import { Component, Directive, ElementRef, getPlatform, Injectable, Injector, NgModule, StaticProvider, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import { downgradeComponent, downgradeInjectable, downgradeModule, UpgradeComponent, } from '@angular/upgrade/static'; declare var angular: ng.IAngularStatic; // An Angular module that declares an Angular service and a component, // which in turn uses an upgraded AngularJS component. @Component({ selector: 'ng2A', template: 'Component A | <ng1A></ng1A>', standalone: false, }) export class Ng2AComponent {} @Directive({ selector: 'ng1A', standalone: false, }) export class Ng1AComponentFacade extends UpgradeComponent { constructor(elementRef: ElementRef, injector: Injector) { super('ng1A', elementRef, injector); } } @Injectable() export class Ng2AService { getValue() { return 'ng2'; } } @NgModule({ imports: [BrowserModule], providers: [Ng2AService], declarations: [Ng1AComponentFacade, Ng2AComponent], }) export class Ng2AModule { ngDoBootstrap() {} } // Another Angular module that declares an Angular component. @Component({ selector: 'ng2B', template: 'Component B', standalone: false, }) export class Ng2BComponent {} @NgModule({ imports: [BrowserModule], declarations: [Ng2BComponent], }) export class Ng2BModule { ngDoBootstrap() {} } // The downgraded Angular modules. const downgradedNg2AModule = downgradeModule((extraProviders: StaticProvider[]) => (getPlatform() || platformBrowserDynamic(extraProviders)).bootstrapModule(Ng2AModule), ); const downgradedNg2BModule = downgradeModule((extraProviders: StaticProvider[]) => (getPlatform() || platformBrowserDynamic(extraProviders)).bootstrapModule(Ng2BModule), ); // The AngularJS app including downgraded modules, components and injectables. const appModule = angular .module('exampleAppModule', [downgradedNg2AModule, downgradedNg2BModule]) .component('exampleApp', { template: ` <nav> <button ng-click="$ctrl.page = page" ng-repeat="page in ['A', 'B']"> Page {{ page }} </button> </nav> <hr /> <main ng-switch="$ctrl.page"> <ng2-a ng-switch-when="A"></ng2-a> <ng2-b ng-switch-when="B"></ng2-b> </main> `, controller: class ExampleAppController { page = 'A'; }, }) .component('ng1A', { template: 'ng1({{ $ctrl.value }})', controller: [ 'ng2AService', class Ng1AController { value = this.ng2AService.getValue(); constructor(private ng2AService: Ng2AService) {} }, ], }) .directive( 'ng2A', downgradeComponent({ component: Ng2AComponent, // Since there is more than one downgraded Angular module, // specify which module this component belongs to. downgradedModule: downgradedNg2AModule, propagateDigest: false, }), ) .directive( 'ng2B', downgradeComponent({ component: Ng2BComponent, // Since there is more than one downgraded Angular module, // specify which module this component belongs to. downgradedModule: downgradedNg2BModule, propagateDigest: false, }), ) .factory('ng2AService', downgradeInjectable(Ng2AService, downgradedNg2AModule)); // Bootstrap the AngularJS app. angular.bootstrap(document.body, [appModule.name]);
{ "commit_id": "cb34e406ba", "end_byte": 3724, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/lite-multi/module.ts" }
angular/adev/src/content/api-examples/upgrade/static/ts/lite-multi/e2e_test/static_lite_multi_spec.ts_0_875
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../../../../../packages/examples/test-utils/index'; describe('upgrade/static (lite with multiple downgraded modules)', () => { const navButtons = element.all(by.css('nav button')); const mainContent = element(by.css('main')); beforeEach(() => browser.get('/')); afterEach(verifyNoBrowserErrors); it('should correctly bootstrap multiple downgraded modules', () => { navButtons.get(1).click(); expect(mainContent.getText()).toBe('Component B'); navButtons.get(0).click(); expect(mainContent.getText()).toBe('Component A | ng1(ng2)'); }); });
{ "commit_id": "cb34e406ba", "end_byte": 875, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/lite-multi/e2e_test/static_lite_multi_spec.ts" }
angular/adev/src/content/api-examples/upgrade/static/ts/lite-multi-shared/module.ts_0_4809
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Compiler, Component, getPlatform, Injectable, Injector, NgModule, StaticProvider, } from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {downgradeComponent, downgradeModule} from '@angular/upgrade/static'; declare var angular: ng.IAngularStatic; // An Angular service provided in root. Each instance of the service will get a new ID. @Injectable({providedIn: 'root'}) export class Ng2Service { static nextId = 1; id = Ng2Service.nextId++; } // An Angular module that will act as "root" for all downgraded modules, so that injectables // provided in root will be available to all. @NgModule({ imports: [BrowserModule], }) export class Ng2RootModule { ngDoBootstrap() {} } // An Angular module that declares an Angular component, // which in turn uses an Angular service from the root module. @Component({ selector: 'ng2A', template: 'Component A (Service ID: {{ service.id }})', standalone: false, }) export class Ng2AComponent { constructor(public service: Ng2Service) {} } @NgModule({ declarations: [Ng2AComponent], }) export class Ng2AModule { ngDoBootstrap() {} } // Another Angular module that declares an Angular component, which uses the same service. @Component({ selector: 'ng2B', template: 'Component B (Service ID: {{ service.id }})', standalone: false, }) export class Ng2BComponent { constructor(public service: Ng2Service) {} } @NgModule({ declarations: [Ng2BComponent], }) export class Ng2BModule { ngDoBootstrap() {} } // A third Angular module that declares an Angular component, which uses the same service. @Component({ selector: 'ng2C', template: 'Component C (Service ID: {{ service.id }})', standalone: false, }) export class Ng2CComponent { constructor(public service: Ng2Service) {} } @NgModule({ imports: [BrowserModule], declarations: [Ng2CComponent], }) export class Ng2CModule { ngDoBootstrap() {} } // The downgraded Angular modules. Modules A and B share a common root module. Module C does not. // #docregion shared-root-module let rootInjectorPromise: Promise<Injector> | null = null; const getRootInjector = (extraProviders: StaticProvider[]) => { if (!rootInjectorPromise) { rootInjectorPromise = platformBrowserDynamic(extraProviders) .bootstrapModule(Ng2RootModule) .then((moduleRef) => moduleRef.injector); } return rootInjectorPromise; }; const downgradedNg2AModule = downgradeModule(async (extraProviders: StaticProvider[]) => { const rootInjector = await getRootInjector(extraProviders); const moduleAFactory = await rootInjector.get(Compiler).compileModuleAsync(Ng2AModule); return moduleAFactory.create(rootInjector); }); const downgradedNg2BModule = downgradeModule(async (extraProviders: StaticProvider[]) => { const rootInjector = await getRootInjector(extraProviders); const moduleBFactory = await rootInjector.get(Compiler).compileModuleAsync(Ng2BModule); return moduleBFactory.create(rootInjector); }); // #enddocregion shared-root-module const downgradedNg2CModule = downgradeModule((extraProviders: StaticProvider[]) => (getPlatform() || platformBrowserDynamic(extraProviders)).bootstrapModule(Ng2CModule), ); // The AngularJS app including downgraded modules and components. // #docregion shared-root-module const appModule = angular .module('exampleAppModule', [downgradedNg2AModule, downgradedNg2BModule, downgradedNg2CModule]) // #enddocregion shared-root-module .component('exampleApp', {template: '<ng2-a></ng2-a> | <ng2-b></ng2-b> | <ng2-c></ng2-c>'}) .directive( 'ng2A', downgradeComponent({ component: Ng2AComponent, // Since there is more than one downgraded Angular module, // specify which module this component belongs to. downgradedModule: downgradedNg2AModule, propagateDigest: false, }), ) .directive( 'ng2B', downgradeComponent({ component: Ng2BComponent, // Since there is more than one downgraded Angular module, // specify which module this component belongs to. downgradedModule: downgradedNg2BModule, propagateDigest: false, }), ) .directive( 'ng2C', downgradeComponent({ component: Ng2CComponent, // Since there is more than one downgraded Angular module, // specify which module this component belongs to. downgradedModule: downgradedNg2CModule, propagateDigest: false, }), ); // Bootstrap the AngularJS app. angular.bootstrap(document.body, [appModule.name]);
{ "commit_id": "cb34e406ba", "end_byte": 4809, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/lite-multi-shared/module.ts" }
angular/adev/src/content/api-examples/upgrade/static/ts/lite-multi-shared/BUILD.bazel_0_460
load("//packages/examples/upgrade:upgrade_example.bzl", "create_upgrade_example_targets") package(default_visibility = ["//visibility:public"]) create_upgrade_example_targets( name = "lite-multi-shared", srcs = glob( ["**/*.ts"], exclude = ["**/*_spec.ts"], ), e2e_srcs = glob(["e2e_test/*_spec.ts"]), entry_point = ":module.ts", ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "commit_id": "cb34e406ba", "end_byte": 460, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/lite-multi-shared/BUILD.bazel" }
angular/adev/src/content/api-examples/upgrade/static/ts/lite-multi-shared/e2e_test/static_lite_multi_shared_spec.ts_0_1042
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../../../../../packages/examples/test-utils/index'; describe('upgrade/static (lite with multiple downgraded modules and shared root module)', () => { const compA = element(by.css('ng2-a')); const compB = element(by.css('ng2-b')); const compC = element(by.css('ng2-c')); beforeEach(() => browser.get('/')); afterEach(verifyNoBrowserErrors); it('should share the same injectable instance across downgraded modules A and B', () => { expect(compA.getText()).toBe('Component A (Service ID: 2)'); expect(compB.getText()).toBe('Component B (Service ID: 2)'); }); it('should use a different injectable instance on downgraded module C', () => { expect(compC.getText()).toBe('Component C (Service ID: 1)'); }); });
{ "commit_id": "cb34e406ba", "end_byte": 1042, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/upgrade/static/ts/lite-multi-shared/e2e_test/static_lite_multi_shared_spec.ts" }
angular/adev/src/content/api-examples/forms/main.ts_0_427
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import 'zone.js/lib/browser/rollup-main'; import {platformBrowserDynamic} from '@angular/platform-browser-dynamic'; import {TestsAppModule} from './test_module'; platformBrowserDynamic().bootstrapModule(TestsAppModule);
{ "commit_id": "cb34e406ba", "end_byte": 427, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/main.ts" }
angular/adev/src/content/api-examples/forms/start-server.js_0_552
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ const protractorUtils = require('@bazel/protractor/protractor-utils'); const protractor = require('protractor'); module.exports = async function (config) { const {port} = await protractorUtils.runServer(config.workspace, config.server, '--port', []); const serverUrl = `http://localhost:${port}`; protractor.browser.baseUrl = serverUrl; };
{ "commit_id": "cb34e406ba", "end_byte": 552, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/start-server.js" }
angular/adev/src/content/api-examples/forms/test_module.ts_0_2969
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Component, NgModule} from '@angular/core'; import {RouterModule} from '@angular/router'; import * as formBuilderExample from './ts/formBuilder/module'; import * as nestedFormArrayExample from './ts/nestedFormArray/module'; import * as nestedFormGroupExample from './ts/nestedFormGroup/module'; import * as ngModelGroupExample from './ts/ngModelGroup/module'; import * as radioButtonsExample from './ts/radioButtons/module'; import * as reactiveRadioButtonsExample from './ts/reactiveRadioButtons/module'; import * as reactiveSelectControlExample from './ts/reactiveSelectControl/module'; import * as selectControlExample from './ts/selectControl/module'; import * as simpleFormExample from './ts/simpleForm/module'; import * as simpleFormControlExample from './ts/simpleFormControl/module'; import * as simpleFormGroupExample from './ts/simpleFormGroup/module'; import * as simpleNgModelExample from './ts/simpleNgModel/module'; @Component({ selector: 'example-app', template: '<router-outlet></router-outlet>', standalone: false, }) export class TestsAppComponent {} @NgModule({ imports: [ formBuilderExample.AppModule, nestedFormArrayExample.AppModule, nestedFormGroupExample.AppModule, ngModelGroupExample.AppModule, radioButtonsExample.AppModule, reactiveRadioButtonsExample.AppModule, reactiveSelectControlExample.AppModule, selectControlExample.AppModule, simpleFormExample.AppModule, simpleFormControlExample.AppModule, simpleFormGroupExample.AppModule, simpleNgModelExample.AppModule, // Router configuration so that the individual e2e tests can load their // app components. RouterModule.forRoot([ {path: 'formBuilder', component: formBuilderExample.AppComponent}, {path: 'nestedFormArray', component: nestedFormArrayExample.AppComponent}, {path: 'nestedFormGroup', component: nestedFormGroupExample.AppComponent}, {path: 'ngModelGroup', component: ngModelGroupExample.AppComponent}, {path: 'radioButtons', component: radioButtonsExample.AppComponent}, {path: 'reactiveRadioButtons', component: reactiveRadioButtonsExample.AppComponent}, {path: 'reactiveSelectControl', component: reactiveSelectControlExample.AppComponent}, {path: 'selectControl', component: selectControlExample.AppComponent}, {path: 'simpleForm', component: simpleFormExample.AppComponent}, {path: 'simpleFormControl', component: simpleFormControlExample.AppComponent}, {path: 'simpleFormGroup', component: simpleFormGroupExample.AppComponent}, {path: 'simpleNgModel', component: simpleNgModelExample.AppComponent}, ]), ], declarations: [TestsAppComponent], bootstrap: [TestsAppComponent], }) export class TestsAppModule {}
{ "commit_id": "cb34e406ba", "end_byte": 2969, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/test_module.ts" }
angular/adev/src/content/api-examples/forms/BUILD.bazel_0_1445
load("//tools:defaults.bzl", "esbuild", "http_server", "ng_module", "protractor_web_test_suite", "ts_library") package(default_visibility = ["//visibility:public"]) ng_module( name = "forms_examples", srcs = glob( ["**/*.ts"], exclude = ["**/*_spec.ts"], ), deps = [ "//packages/core", "//packages/forms", "//packages/platform-browser", "//packages/platform-browser-dynamic", "//packages/router", "//packages/zone.js/lib", "@npm//rxjs", ], ) ts_library( name = "forms_e2e_tests_lib", testonly = True, srcs = glob(["**/e2e_test/*_spec.ts"]), tsconfig = "//packages/examples:tsconfig-e2e.json", deps = [ "//packages/examples/test-utils", "//packages/private/testing", "@npm//@types/jasminewd2", "@npm//protractor", ], ) esbuild( name = "app_bundle", entry_point = ":main.ts", deps = [":forms_examples"], ) http_server( name = "devserver", srcs = ["//packages/examples:index.html"], additional_root_paths = ["angular/packages/examples"], deps = [":app_bundle"], ) protractor_web_test_suite( name = "protractor_tests", on_prepare = ":start-server.js", server = ":devserver", deps = [ ":forms_e2e_tests_lib", "@npm//selenium-webdriver", ], ) filegroup( name = "files_for_docgen", srcs = glob([ "**/*.ts", ]), )
{ "commit_id": "cb34e406ba", "end_byte": 1445, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/BUILD.bazel" }
angular/adev/src/content/api-examples/forms/ts/ngModelGroup/module.ts_0_600
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {NgModelGroupComp} from './ng_model_group_example'; @NgModule({ imports: [BrowserModule, FormsModule], declarations: [NgModelGroupComp], bootstrap: [NgModelGroupComp], }) export class AppModule {} export {NgModelGroupComp as AppComponent};
{ "commit_id": "cb34e406ba", "end_byte": 600, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/ngModelGroup/module.ts" }
angular/adev/src/content/api-examples/forms/ts/ngModelGroup/ng_model_group_example.ts_0_1273
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* tslint:disable:no-console */ // #docregion Component import {Component} from '@angular/core'; import {NgForm} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <form #f="ngForm" (ngSubmit)="onSubmit(f)"> <p *ngIf="nameCtrl.invalid">Name is invalid.</p> <div ngModelGroup="name" #nameCtrl="ngModelGroup"> <input name="first" [ngModel]="name.first" minlength="2" /> <input name="middle" [ngModel]="name.middle" maxlength="2" /> <input name="last" [ngModel]="name.last" required /> </div> <input name="email" ngModel /> <button>Submit</button> </form> <button (click)="setValue()">Set value</button> `, standalone: false, }) export class NgModelGroupComp { name = {first: 'Nancy', middle: 'J', last: 'Drew'}; onSubmit(f: NgForm) { console.log(f.value); // {name: {first: 'Nancy', middle: 'J', last: 'Drew'}, email: ''} console.log(f.valid); // true } setValue() { this.name = {first: 'Bess', middle: 'S', last: 'Marvin'}; } } // #enddocregion
{ "commit_id": "cb34e406ba", "end_byte": 1273, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/ngModelGroup/ng_model_group_example.ts" }
angular/adev/src/content/api-examples/forms/ts/ngModelGroup/e2e_test/ng_model_group_spec.ts_0_1455
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementArrayFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index'; describe('ngModelGroup example', () => { afterEach(verifyNoBrowserErrors); let inputs: ElementArrayFinder; let buttons: ElementArrayFinder; beforeEach(() => { browser.get('/ngModelGroup'); inputs = element.all(by.css('input')); buttons = element.all(by.css('button')); }); it('should populate the UI with initial values', () => { expect(inputs.get(0).getAttribute('value')).toEqual('Nancy'); expect(inputs.get(1).getAttribute('value')).toEqual('J'); expect(inputs.get(2).getAttribute('value')).toEqual('Drew'); }); it('should show the error when name is invalid', () => { inputs.get(0).click(); inputs.get(0).clear(); inputs.get(0).sendKeys('a'); expect(element(by.css('p')).getText()).toEqual('Name is invalid.'); }); it('should set the value when changing the domain model', () => { buttons.get(1).click(); expect(inputs.get(0).getAttribute('value')).toEqual('Bess'); expect(inputs.get(1).getAttribute('value')).toEqual('S'); expect(inputs.get(2).getAttribute('value')).toEqual('Marvin'); }); });
{ "commit_id": "cb34e406ba", "end_byte": 1455, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/ngModelGroup/e2e_test/ng_model_group_spec.ts" }
angular/adev/src/content/api-examples/forms/ts/simpleFormControl/simple_form_control_example.ts_0_778
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // #docregion Component import {Component} from '@angular/core'; import {FormControl, Validators} from '@angular/forms'; @Component({ selector: 'example-app', template: ` <input [formControl]="control" /> <p>Value: {{ control.value }}</p> <p>Validation status: {{ control.status }}</p> <button (click)="setValue()">Set value</button> `, standalone: false, }) export class SimpleFormControl { control: FormControl = new FormControl('value', Validators.minLength(2)); setValue() { this.control.setValue('new value'); } } // #enddocregion
{ "commit_id": "cb34e406ba", "end_byte": 778, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleFormControl/simple_form_control_example.ts" }
angular/adev/src/content/api-examples/forms/ts/simpleFormControl/module.ts_0_625
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {ReactiveFormsModule} from '@angular/forms'; import {BrowserModule} from '@angular/platform-browser'; import {SimpleFormControl} from './simple_form_control_example'; @NgModule({ imports: [BrowserModule, ReactiveFormsModule], declarations: [SimpleFormControl], bootstrap: [SimpleFormControl], }) export class AppModule {} export {SimpleFormControl as AppComponent};
{ "commit_id": "cb34e406ba", "end_byte": 625, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleFormControl/module.ts" }
angular/adev/src/content/api-examples/forms/ts/simpleFormControl/e2e_test/simple_form_control_spec.ts_0_1614
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {browser, by, element, ElementFinder} from 'protractor'; import {verifyNoBrowserErrors} from '../../../../../../../../packages/examples/test-utils/index'; describe('simpleFormControl example', () => { afterEach(verifyNoBrowserErrors); describe('index view', () => { let input: ElementFinder; let valueP: ElementFinder; let statusP: ElementFinder; beforeEach(() => { browser.get('/simpleFormControl'); input = element(by.css('input')); valueP = element(by.css('p:first-of-type')); statusP = element(by.css('p:last-of-type')); }); it('should populate the form control value in the DOM', () => { expect(input.getAttribute('value')).toEqual('value'); expect(valueP.getText()).toEqual('Value: value'); }); it('should update the value as user types', () => { input.click(); input.sendKeys('s!'); expect(valueP.getText()).toEqual('Value: values!'); }); it('should show the correct validity state', () => { expect(statusP.getText()).toEqual('Validation status: VALID'); input.click(); input.clear(); input.sendKeys('a'); expect(statusP.getText()).toEqual('Validation status: INVALID'); }); it('should set the value programmatically', () => { element(by.css('button')).click(); expect(input.getAttribute('value')).toEqual('new value'); }); }); });
{ "commit_id": "cb34e406ba", "end_byte": 1614, "start_byte": 0, "url": "https://github.com/angular/angular/blob/main/adev/src/content/api-examples/forms/ts/simpleFormControl/e2e_test/simple_form_control_spec.ts" }