id
stringlengths
6
6
text
stringlengths
20
17.2k
title
stringclasses
1 value
003814
import {bootstrapApplication} from '@angular/platform-browser'; import {provideAnimations} from '@angular/platform-browser/animations'; import {provideRouter} from '@angular/router'; import {AppComponent} from './app/app.component'; bootstrapApplication(AppComponent, { providers: [ provideAnimations(), provideRouter([ { path: '', loadComponent: () => import('./app/open-close.component').then((m) => m.OpenCloseComponent), }, ]), ], }).catch((err) => console.error(err));
004063
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Example</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <app-root></app-root> </body> </html>
004099
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {isPlatformBrowser} from '@angular/common'; import {InjectionToken, PLATFORM_ID, inject} from '@angular/core'; export const LOCAL_STORAGE = new InjectionToken<Storage | null>('LOCAL_STORAGE', { providedIn: 'root', factory: () => getStorage(inject(PLATFORM_ID)), }); const getStorage = (platformId: Object): Storage | null => { // Prerendering: localStorage is undefined for prerender build return isPlatformBrowser(platformId) ? new LocalStorage() : null; }; /** * LocalStorage is wrapper class for localStorage, operations can fail due to various reasons, * such as browser restrictions or storage limits being exceeded. A wrapper is providing error handling. */ class LocalStorage implements Storage { get length(): number { try { return localStorage.length; } catch { return 0; } } clear(): void { try { localStorage.clear(); } catch {} } getItem(key: string): string | null { try { return localStorage.getItem(key); } catch { return null; } } key(index: number): string | null { try { return localStorage.key(index); } catch { return null; } } removeItem(key: string): void { try { localStorage.removeItem(key); } catch {} } setItem(key: string, value: string): void { try { localStorage.setItem(key, value); } catch {} } }
004131
// TODO: Continue organizing and refactoring this file @use '@angular/material' as mat; // Using disable-next-line to avoid stylelint errors - these imports are necessary // TODO: Is there another way to prevent these linting errors? // stylelint-disable-next-line @angular/no-unused-import @use '_colors'; // stylelint-disable-next-line @angular/no-unused-import @use '_z-index'; // Global @use 'resets'; @use 'typography'; @use 'scroll-track'; @use 'button'; @use 'kbd'; @use 'api-item-label'; @use 'faceted-list'; @use 'media-queries' as mq; // Docs @use 'docs/alert'; @use 'docs/callout'; @use 'docs/card'; @use 'docs/code'; @use 'docs/decorative-header'; @use 'docs/icon'; @use 'docs/pill'; @use 'docs/steps'; @use 'docs/table'; @use 'docs/video'; @use 'docs/mermaid'; // Global @include resets.resets(); @include typography.typography(); @include scroll-track.scroll-track(); @include button.button(); @include kbd.kbd(); @include api-item-label.api-item-label(); @include faceted-list.faceted-list(); @include mq.for-phone-only(); @include mq.for-tablet-portrait-up(); @include mq.for-tablet-landscape-up(); @include mq.for-desktop-up(); @include mq.for-big-desktop-up(); @include mq.for-tablet-landscape-down(); // temporary just to show different options of code component UI. $primary: mat.m2-define-palette(mat.$m2-indigo-palette); $accent: mat.m2-define-palette(mat.$m2-pink-palette, A200, A100, A400); $theme: mat.m2-define-light-theme( ( color: ( primary: $primary, accent: $accent, ), typography: mat.m2-define-typography-config(), ) ); // Include material core styles. @include mat.core(); @include mat.tabs-theme($theme); @include mat.button-toggle-theme($theme); @include mat.tooltip-theme($theme); // Include custom docs styles @include alert.docs-alert(); @include callout.docs-callout(); @include card.docs-card(); @include code.docs-code-block(); @include code.docs-code-editor(); @include decorative-header.docs-decorative-header(); @include icon.docs-icon(); @include pill.docs-pill(); @include steps.docs-steps(); @include code.docs-syntax-highlighting(); @include table.docs-table(); @include video.docs-video(); // Include custom angular.dev styles // Disable view transitions when reduced motion is requested. @media (prefers-reduced-motion) { ::view-transition-group(*), ::view-transition-old(*), ::view-transition-new(*) { animation: none !important; } } .docs-dark-mode .shiki { color: var(--shiki-dark); background-color: var(--shiki-dark-bg); span { color: var(--shiki-dark); background-color: var(--shiki-dark-bg); /* Optional, if you also want font styles */ font-style: var(--shiki-dark-font-style); font-weight: var(--shiki-dark-font-weight); } .shiki-ln-line-highlighted, button:hover { span { background-color: inherit; } } } .shiki { padding-block: 1rem; &.cli { padding-inline-start: 1rem; } a { color: inherit; &:hover { text-decoration: underline; } } } .docs-light-mode .shiki { color: var(--shiki-light); background-color: var(--shiki-light-bg); span { color: var(--shiki-light); background-color: var(--shiki-light-bg); /* Optional, if you also want font styles */ font-style: var(--shiki-light-font-style); font-weight: var(--shiki-light-font-weight); text-decoration: var(--shiki-light-text-decoration); } .shiki-ln-line-highlighted, button:hover { span { background-color: inherit; } } }
004134
@mixin external-link-with-icon() { &::after { display: inline-block; content: '\e89e'; // codepoint for "open_in_new" font-family: 'Material Symbols Outlined'; margin-left: 0.2rem; vertical-align: middle; } }
004197
import {ChangeDetectionStrategy, Component, inject, input, OnInit, signal} from '@angular/core'; import {ExternalLink} from '../../directives'; import {LOCAL_STORAGE} from '../../providers'; import {IconComponent} from '../icon/icon.component'; export const STORAGE_KEY_PREFIX = 'docs-was-closed-top-banner-'; @Component({ selector: 'docs-top-level-banner', standalone: true, imports: [ExternalLink, IconComponent], templateUrl: './top-level-banner.component.html', styleUrl: './top-level-banner.component.scss', changeDetection: ChangeDetectionStrategy.OnPush, }) export class TopLevelBannerComponent implements OnInit { private readonly localStorage = inject(LOCAL_STORAGE); /** * Unique identifier for the banner. This ID is required to ensure that * the state of the banner (e.g., whether it has been closed) is tracked * separately for different events or instances. Without a unique ID, * closing one banner could inadvertently hide other banners for different events. */ id = input.required<string>(); // Optional URL link that the banner should navigate to when clicked. link = input<string>(); // Text content to be displayed in the banner. text = input.required<string>(); // Optional expiry date. Setting the default expiry as a future date so we // don't have to deal with undefined signal values. expiry = input(new Date('3000-01-01'), {transform: parseDate}); // Whether the user has closed the banner or the survey has expired. hasClosed = signal<boolean>(false); ngOnInit(): void { const expired = Date.now() > this.expiry().getTime(); // Needs to be in a try/catch, because some browsers will // throw when using `localStorage` in private mode. try { this.hasClosed.set( this.localStorage?.getItem(this.getBannerStorageKey()) === 'true' || expired, ); } catch { this.hasClosed.set(false); } } close(): void { this.localStorage?.setItem(this.getBannerStorageKey(), 'true'); this.hasClosed.set(true); } private getBannerStorageKey(): string { return `${STORAGE_KEY_PREFIX}${this.id()}`; } } const parseDate = (inputDate: string | Date): Date => { if (inputDate instanceof Date) { return inputDate; } const outputDate = new Date(inputDate); if (isNaN(outputDate.getTime())) { throw new Error(`Invalid date string: ${inputDate}`); } return outputDate; };
004266
/*! * @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 {mergeApplicationConfig, ApplicationConfig} from '@angular/core'; import {provideServerRendering} from '@angular/platform-server'; import {provideServerRoutesConfig, RenderMode} from '@angular/ssr'; import {appConfig} from './app.config'; const serverConfig: ApplicationConfig = { providers: [ provideServerRendering(), provideServerRoutesConfig([{path: '**', renderMode: RenderMode.Prerender}]), ], }; export const config = mergeApplicationConfig(appConfig, serverConfig);
004270
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {DOCUMENT, isPlatformBrowser} from '@angular/common'; import { ChangeDetectionStrategy, Component, inject, OnInit, PLATFORM_ID, signal, WritableSignal, } from '@angular/core'; import {NavigationEnd, NavigationSkipped, Router, RouterLink, RouterOutlet} from '@angular/router'; import {filter, map, skip} from 'rxjs/operators'; import { CookiePopup, getActivatedRouteSnapshotFromRouter, IS_SEARCH_DIALOG_OPEN, SearchDialog, TopLevelBannerComponent, } from '@angular/docs'; import {Footer} from './core/layout/footer/footer.component'; import {Navigation} from './core/layout/navigation/navigation.component'; import {SecondaryNavigation} from './core/layout/secondary-navigation/secondary-navigation.component'; import {ProgressBarComponent} from './core/layout/progress-bar/progress-bar.component'; import {ESCAPE, SEARCH_TRIGGER_KEY} from './core/constants/keys'; import {HeaderService} from './core/services/header.service'; @Component({ selector: 'adev-root', changeDetection: ChangeDetectionStrategy.OnPush, standalone: true, imports: [ CookiePopup, Navigation, Footer, SecondaryNavigation, RouterOutlet, SearchDialog, ProgressBarComponent, TopLevelBannerComponent, ], templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], host: { '(window:keydown)': 'setSearchDialogVisibilityOnKeyPress($event)', }, }) export class AppComponent implements OnInit { private readonly document = inject(DOCUMENT); private readonly router = inject(Router); private readonly headerService = inject(HeaderService); currentUrl = signal(''); displayFooter = signal(false); displaySecondaryNav = signal(false); displaySearchDialog: WritableSignal<boolean> = inject(IS_SEARCH_DIALOG_OPEN); isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); ngOnInit(): void { this.closeSearchDialogOnNavigationSkipped(); this.router.events .pipe( filter((e): e is NavigationEnd => e instanceof NavigationEnd), map((event) => event.urlAfterRedirects), ) .subscribe((url) => { this.currentUrl.set(url); this.setComponentsVisibility(); this.displaySearchDialog.set(false); this.updateCanonicalLink(url); }); } focusFirstHeading(): void { if (!this.isBrowser) { return; } const h1 = this.document.querySelector<HTMLHeadingElement>('h1'); h1?.focus(); } private updateCanonicalLink(absoluteUrl: string) { this.headerService.setCanonical(absoluteUrl); } private setComponentsVisibility(): void { const activatedRoute = getActivatedRouteSnapshotFromRouter(this.router as any); this.displaySecondaryNav.set(activatedRoute.data['displaySecondaryNav']); this.displayFooter.set(!activatedRoute.data['hideFooter']); } private setSearchDialogVisibilityOnKeyPress(event: KeyboardEvent): void { if (event.key === SEARCH_TRIGGER_KEY && (event.metaKey || event.ctrlKey)) { event.preventDefault(); this.displaySearchDialog.update((display) => !display); } if (event.key === ESCAPE && this.displaySearchDialog()) { event.preventDefault(); this.displaySearchDialog.set(false); } } private closeSearchDialogOnNavigationSkipped(): void { this.router.events.pipe(filter((event) => event instanceof NavigationSkipped)).subscribe(() => { this.displaySearchDialog.set(false); }); } }
004277
/*! * @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 { ChangeDetectionStrategy, Component, DestroyRef, OnInit, PLATFORM_ID, computed, inject, signal, } from '@angular/core'; import {takeUntilDestroyed, toObservable} from '@angular/core/rxjs-interop'; import { ClickOutside, NavigationItem, NavigationList, NavigationState, WINDOW, findNavigationItem, getBaseUrlAfterRedirects, getNavigationItemsTree, markExternalLinks, shouldReduceMotion, } from '@angular/docs'; import {distinctUntilChanged, filter, map, skip, startWith} from 'rxjs/operators'; import {SUB_NAVIGATION_DATA} from '../../../sub-navigation-data'; import {PagePrefix} from '../../enums/pages'; import {ActivatedRouteSnapshot, NavigationEnd, Router, RouterStateSnapshot} from '@angular/router'; import {isPlatformBrowser} from '@angular/common'; import {trigger, transition, style, animate} from '@angular/animations'; import {PRIMARY_NAV_ID, SECONDARY_NAV_ID} from '../../constants/element-ids'; export const ANIMATION_DURATION = 500; @Component({ selector: 'adev-secondary-navigation', standalone: true, imports: [NavigationList, ClickOutside], templateUrl: './secondary-navigation.component.html', styleUrls: ['./secondary-navigation.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, animations: [ trigger('leaveAnimation', [ transition(':leave', [ style({transform: 'translateX(0%)'}), animate( `${ANIMATION_DURATION}ms ${ANIMATION_DURATION}ms ease-out`, style({transform: 'translateX(100%)'}), ), ]), ]), ], }) export class SecondaryNavigation implements OnInit { private readonly destroyRef = inject(DestroyRef); private readonly navigationState = inject(NavigationState); private readonly platformId = inject(PLATFORM_ID); private readonly router = inject(Router); private readonly window = inject(WINDOW); readonly isSecondaryNavVisible = this.navigationState.isMobileNavVisible; readonly primaryActiveRouteItem = this.navigationState.primaryActiveRouteItem; readonly maxVisibleLevelsOnSecondaryNav = computed(() => this.primaryActiveRouteItem() === PagePrefix.REFERENCE ? 1 : 2, ); readonly navigationItemsSlides = this.navigationState.expandedItems; navigationItems: NavigationItem[] | undefined; translateX = computed(() => { const level = this.navigationState.expandedItems()?.length ?? 0; return `translateX(${-level * 100}%)`; }); transition = signal('0ms'); readonly PRIMARY_NAV_ID = PRIMARY_NAV_ID; readonly SECONDARY_NAV_ID = SECONDARY_NAV_ID; private readonly routeMap: Record<string, NavigationItem[]> = { [PagePrefix.REFERENCE]: getNavigationItemsTree(SUB_NAVIGATION_DATA.reference, (tree) => markExternalLinks(tree, this.window.origin), ), [PagePrefix.DOCS]: getNavigationItemsTree(SUB_NAVIGATION_DATA.docs, (tree) => markExternalLinks(tree, this.window.origin), ), }; private readonly primaryActiveRouteChanged$ = toObservable(this.primaryActiveRouteItem).pipe( distinctUntilChanged(), takeUntilDestroyed(this.destroyRef), ); private readonly urlAfterRedirects$ = this.router.events.pipe( filter((event) => event instanceof NavigationEnd), map((event) => (event as NavigationEnd).urlAfterRedirects), filter((url): url is string => url !== undefined), startWith(this.getInitialPath(this.router.routerState.snapshot)), takeUntilDestroyed(this.destroyRef), ); ngOnInit(): void { this.navigationState.cleanExpandedState(); this.listenToPrimaryRouteChange(); this.setActiveRouteOnNavigationEnd(); if (isPlatformBrowser(this.platformId)) { this.initSlideAnimation(); } } close(): void { this.navigationState.setMobileNavigationListVisibility(false); } private setActiveRouteOnNavigationEnd(): void { this.urlAfterRedirects$.subscribe((url) => { const activeNavigationItem = this.getActiveNavigationItem(url); if ( activeNavigationItem?.level && activeNavigationItem.level <= this.maxVisibleLevelsOnSecondaryNav() ) { this.navigationState.cleanExpandedState(); } else if (activeNavigationItem) { /** * For the `Docs`, we don't expand the "level === 1" items because they are already displayed in the main navigation list. * Example: * In-depth Guides (level == 0) * Components (level == 1) -> Selectors, Styling, etc (level == 2) * Template Syntax (level == 1) -> Text interpolation, etc (level == 2) * * For the `Tutorials`, we display the navigation in the dropdown and it has flat structure (all items are displayed as items with level === 0). * * For the `Reference` we would like to give possibility to expand the "level === 1" items cause they are not visible in the first slide of navigation list. * Example: * API Reference (level == 0) -> Overview, Animations, common, etc (level == 1) -> API Package exports (level == 2) */ const shouldExpandItem = (node: NavigationItem): boolean => !!node.level && (this.primaryActiveRouteItem() === PagePrefix.REFERENCE ? node.level > 0 : node.level > 1); // Skip expand when active item is API Reference homepage - `/api`. // It protect us from displaying second level of the navigation when user clicks on `Reference`, // Because in this situation we want to display the first level, which contains, in addition to the API Reference, also the CLI Reference, Error Encyclopedia etc. const skipExpandPredicateFn = (node: NavigationItem): boolean => node.path === PagePrefix.API; this.navigationState.expandItemHierarchy( activeNavigationItem, shouldExpandItem, skipExpandPredicateFn, ); } }); } private getActiveNavigationItem(url: string): NavigationItem | null { // set visible navigation items if not present this.setVisibleNavigationItems(); const activeNavigationItem = findNavigationItem( this.navigationItems!, (item) => !!item.path && getBaseUrlAfterRedirects(item.path, this.router) === getBaseUrlAfterRedirects(url, this.router), ); this.navigationState.setActiveNavigationItem(activeNavigationItem); return activeNavigationItem; } private initSlideAnimation(): void { if (shouldReduceMotion()) { return; } setTimeout(() => { this.transition.set(`${ANIMATION_DURATION}ms`); }, ANIMATION_DURATION); } private setVisibleNavigationItems(): void { const routeMap = this.routeMap[this.primaryActiveRouteItem()!]; this.navigationItems = routeMap ? getNavigationItemsTree(routeMap, (item) => { item.isExpanded = this.primaryActiveRouteItem() === PagePrefix.DOCS && item.level === 1; }) : []; } private listenToPrimaryRouteChange(): void { // Fix: flicker of sub-navigation on init this.primaryActiveRouteChanged$.pipe(skip(1)).subscribe(() => { this.navigationState.cleanExpandedState(); }); } private getInitialPath(routerState: RouterStateSnapshot): string { let route: ActivatedRouteSnapshot = routerState.root; while (route.firstChild) { route = route.firstChild; } return route.routeConfig?.path ?? ''; } }
004282
/*! * @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 { ChangeDetectionStrategy, Component, inject, OnInit, PLATFORM_ID, ViewChild, } from '@angular/core'; import {isPlatformBrowser} from '@angular/common'; import {NgProgressbar} from 'ngx-progressbar'; import { NavigationCancel, NavigationEnd, NavigationError, NavigationSkipped, NavigationStart, Router, } from '@angular/router'; import {filter, map, switchMap, take} from 'rxjs/operators'; /** Time to wait after navigation starts before showing the progress bar. This delay allows a small amount of time to skip showing the progress bar when a navigation is effectively immediate. 30ms is approximately the amount of time we can wait before a delay is perceptible.*/ export const PROGRESS_BAR_DELAY = 30; @Component({ selector: 'adev-progress-bar', standalone: true, imports: [NgProgressbar], template: ` <ng-progress aria-label="Page load progress" /> `, changeDetection: ChangeDetectionStrategy.OnPush, }) export class ProgressBarComponent implements OnInit { private readonly router = inject(Router); @ViewChild(NgProgressbar, {static: true}) progressBar!: NgProgressbar; isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); ngOnInit() { this.setupPageNavigationDimming(); } /** * Dims the main router-outlet content when navigating to a new page. */ private setupPageNavigationDimming() { if (!this.isBrowser) { return; } this.router.events .pipe( filter((e) => e instanceof NavigationStart), map(() => { // Only apply set the property if the navigation is not "immediate" return setTimeout(() => { this.progressBar.start(); }, PROGRESS_BAR_DELAY); }), switchMap((timeoutId) => { return this.router.events.pipe( filter((e) => { return ( e instanceof NavigationEnd || e instanceof NavigationCancel || e instanceof NavigationSkipped || e instanceof NavigationError ); }), take(1), map(() => timeoutId), ); }), ) .subscribe((timeoutId) => { // When the navigation finishes, prevent the navigating class from being applied in the timeout. clearTimeout(timeoutId); this.progressBar.complete(); }); } }
004283
/*! * @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 {CdkMenu, CdkMenuItem, CdkMenuTrigger} from '@angular/cdk/menu'; import {DOCUMENT, Location, isPlatformBrowser} from '@angular/common'; import { ChangeDetectionStrategy, Component, DestroyRef, OnInit, PLATFORM_ID, inject, } from '@angular/core'; import {takeUntilDestroyed, toObservable} from '@angular/core/rxjs-interop'; import { ClickOutside, NavigationState, WINDOW, IconComponent, getBaseUrlAfterRedirects, isApple, IS_SEARCH_DIALOG_OPEN, } from '@angular/docs'; import {NavigationEnd, Router, RouterLink} from '@angular/router'; import {filter, map, startWith} from 'rxjs/operators'; import {DOCS_ROUTES, REFERENCE_ROUTES, TUTORIALS_ROUTES} from '../../../routes'; import {GITHUB, MEDIUM, X, YOUTUBE, DISCORD} from '../../constants/links'; import {PagePrefix} from '../../enums/pages'; import {Theme, ThemeManager} from '../../services/theme-manager.service'; import {VersionManager} from '../../services/version-manager.service'; import {PRIMARY_NAV_ID, SECONDARY_NAV_ID} from '../../constants/element-ids'; import {ConnectionPositionPair} from '@angular/cdk/overlay'; import {COMMAND, CONTROL, SEARCH_TRIGGER_KEY} from '../../constants/keys'; type MenuType = 'social' | 'theme-picker' | 'version-picker'; @Component({ selector: 'div.adev-nav', standalone: true, imports: [RouterLink, ClickOutside, CdkMenu, CdkMenuItem, CdkMenuTrigger, IconComponent], templateUrl: './navigation.component.html', styleUrls: ['./navigation.component.scss', './mini-menu.scss', './nav-item.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class Navigation implements OnInit { private readonly destroyRef = inject(DestroyRef); private readonly document = inject(DOCUMENT); private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); private readonly navigationState = inject(NavigationState); private readonly router = inject(Router); private readonly location = inject(Location); private readonly themeManager = inject(ThemeManager); private readonly isSearchDialogOpen = inject(IS_SEARCH_DIALOG_OPEN); private readonly window = inject(WINDOW); private readonly versionManager = inject(VersionManager); readonly DOCS_ROUTE = PagePrefix.DOCS; readonly HOME_ROUTE = PagePrefix.HOME; readonly PLAYGROUND_ROUTE = PagePrefix.PLAYGROUND; readonly REFERENCE_ROUTE = PagePrefix.REFERENCE; readonly TUTORIALS_ROUTE = PagePrefix.TUTORIALS; readonly GITHUB = GITHUB; readonly X = X; readonly MEDIUM = MEDIUM; readonly YOUTUBE = YOUTUBE; readonly DISCORD = DISCORD; readonly PRIMARY_NAV_ID = PRIMARY_NAV_ID; readonly SECONDARY_NAV_ID = SECONDARY_NAV_ID; // We can't use the ActivatedRouter queryParams as we're outside the router outlet readonly isUwu = 'location' in globalThis ? location.search.includes('uwu') : false; miniMenuPositions = [ new ConnectionPositionPair( {originX: 'end', originY: 'center'}, {overlayX: 'start', overlayY: 'center'}, ), new ConnectionPositionPair( {originX: 'end', originY: 'top'}, {overlayX: 'start', overlayY: 'top'}, ), ]; readonly APPLE_SEARCH_LABEL = `⌘`; readonly DEFAULT_SEARCH_LABEL = `ctrl`; activeRouteItem = this.navigationState.primaryActiveRouteItem; theme = this.themeManager.theme; openedMenu: MenuType | null = null; currentDocsVersion = this.versionManager.currentDocsVersion; currentDocsVersionMode = this.versionManager.currentDocsVersion()?.version; // Set the values of the search label and title only on the client, because the label is user-agent specific. searchLabel = this.isBrowser ? isApple ? this.APPLE_SEARCH_LABEL : this.DEFAULT_SEARCH_LABEL : ''; searchTitle = this.isBrowser ? isApple ? `${COMMAND} ${SEARCH_TRIGGER_KEY.toUpperCase()}` : `${CONTROL} ${SEARCH_TRIGGER_KEY.toUpperCase()}` : ''; versions = this.versionManager.versions; isMobileNavigationOpened = this.navigationState.isMobileNavVisible; isMobileNavigationOpened$ = toObservable(this.isMobileNavigationOpened); primaryRouteChanged$ = toObservable(this.activeRouteItem); ngOnInit(): void { this.listenToRouteChange(); this.preventToScrollContentWhenSecondaryNavIsOpened(); this.closeMobileNavOnPrimaryRouteChange(); } setTheme(theme: Theme): void { this.themeManager.setTheme(theme); } openVersionMenu($event: MouseEvent): void { // It's required to avoid redirection to `home` $event.stopImmediatePropagation(); $event.preventDefault(); this.openMenu('version-picker'); } openMenu(menuType: MenuType): void { this.openedMenu = menuType; } closeMenu(): void { this.openedMenu = null; } openMobileNav($event: MouseEvent): void { $event.stopPropagation(); this.navigationState.setMobileNavigationListVisibility(true); } closeMobileNav(): void { this.navigationState.setMobileNavigationListVisibility(false); } toggleSearchDialog(event: MouseEvent): void { event.stopPropagation(); this.isSearchDialogOpen.update((isOpen) => !isOpen); } private closeMobileNavOnPrimaryRouteChange(): void { this.primaryRouteChanged$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(() => { this.closeMobileNav(); }); } private listenToRouteChange(): void { this.router.events .pipe( filter((event) => event instanceof NavigationEnd), map((event) => (event as NavigationEnd).urlAfterRedirects), ) .pipe( takeUntilDestroyed(this.destroyRef), //using location because router.url will only return "/" here startWith(this.location.path()), ) .subscribe((url) => { this.setActivePrimaryRoute(getBaseUrlAfterRedirects(url, this.router)); }); } // Set active route item, based on urlAfterRedirects. // First check if url starts with the main prefixes (docs, reference, tutorials). // (*) Docs navigation tree contains items which will navigate to /tutorials. // In that case after click on such link we should mark as active item, and display tutorials navigation tree. // If it's not starting with prefix then check if specific path exist in the array of defined routes // (*) Reference navigation tree contains items which are not start with prefix like /migrations or /errors. private setActivePrimaryRoute(urlAfterRedirects: string): void { if (urlAfterRedirects === '') { this.activeRouteItem.set(PagePrefix.HOME); } else if (urlAfterRedirects.startsWith(PagePrefix.DOCS)) { this.activeRouteItem.set(PagePrefix.DOCS); } else if ( urlAfterRedirects.startsWith(PagePrefix.REFERENCE) || urlAfterRedirects.startsWith(PagePrefix.API) || urlAfterRedirects.startsWith(PagePrefix.UPDATE) ) { this.activeRouteItem.set(PagePrefix.REFERENCE); } else if (urlAfterRedirects === PagePrefix.PLAYGROUND) { this.activeRouteItem.set(PagePrefix.PLAYGROUND); } else if (urlAfterRedirects.startsWith(PagePrefix.TUTORIALS)) { this.activeRouteItem.set(PagePrefix.TUTORIALS); } else if (DOCS_ROUTES.some((route) => route.path === urlAfterRedirects)) { this.activeRouteItem.set(PagePrefix.DOCS); } else if (REFERENCE_ROUTES.some((route) => route.path === urlAfterRedirects)) { this.activeRouteItem.set(PagePrefix.REFERENCE); } else if (TUTORIALS_ROUTES.some((route) => route.path === urlAfterRedirects)) { this.activeRouteItem.set(PagePrefix.TUTORIALS); } else { // Reset if no active route item could be found this.activeRouteItem.set(null); } } private preventToScrollContentWhenSecondaryNavIsOpened(): void { this.isMobileNavigationOpened$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe((opened) => { if (opened) { this.document.body.style.overflowY = 'hidden'; } else { this.document.body.style.removeProperty('overflow-y'); } }); } }
004285
/*! * @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 {ComponentFixture, TestBed} from '@angular/core/testing'; import {Navigation} from './navigation.component'; import {RouterTestingModule} from '@angular/router/testing'; import {By} from '@angular/platform-browser'; import {PagePrefix} from '../../enums/pages'; import {Theme, ThemeManager} from '../../services/theme-manager.service'; import {Version, signal} from '@angular/core'; import {of} from 'rxjs'; import {VersionManager} from '../../services/version-manager.service'; import {Search, WINDOW} from '@angular/docs'; describe('Navigation', () => { let component: Navigation; let fixture: ComponentFixture<Navigation>; const fakeThemeManager = { theme: signal<Theme>('dark'), setTheme: (theme: Theme) => {}, themeChanged$: of(), }; const fakeVersionManager = { currentDocsVersion: signal('v17'), versions: signal<Version[]>([]), }; const fakeWindow = {}; const fakeSearch = {}; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [Navigation, RouterTestingModule], providers: [ { provide: WINDOW, useValue: fakeWindow, }, { provide: Search, useValue: fakeSearch, }, ], }).compileComponents(); TestBed.overrideProvider(ThemeManager, {useValue: fakeThemeManager}); TestBed.overrideProvider(VersionManager, {useValue: fakeVersionManager}); fixture = TestBed.createComponent(Navigation); component = fixture.componentInstance; fixture.detectChanges(); }); it('should append active class to DOCS_ROUTE when DOCS_ROUTE is active', () => { component.activeRouteItem.set(PagePrefix.DOCS); fixture.detectChanges(); const docsLink = fixture.debugElement.query(By.css('a[href="/docs"]')).parent?.nativeElement; expect(docsLink).toHaveClass('adev-nav-item--active'); }); it('should not have active class when activeRouteItem is null', () => { component.activeRouteItem.set(null); fixture.detectChanges(); const docsLink = fixture.debugElement.query(By.css('a[href="/docs"]')).nativeElement; const referenceLink = fixture.debugElement.query(By.css('a[href="/reference"]')).nativeElement; expect(docsLink).not.toHaveClass('adev-nav-item--active'); expect(referenceLink).not.toHaveClass('adev-nav-item--active'); }); it('should call themeManager.setTheme(dark) when user tries to set dark theme', () => { const openThemePickerButton = fixture.debugElement.query( By.css('button[aria-label^="Open theme picker"]'), ).nativeElement; const setThemeSpy = spyOn(fakeThemeManager, 'setTheme'); openThemePickerButton.click(); fixture.detectChanges(); const setDarkModeButton = fixture.debugElement.query( By.css('button[aria-label="Set dark theme"]'), ).nativeElement; setDarkModeButton.click(); expect(setThemeSpy).toHaveBeenCalledOnceWith('dark'); }); });
004300
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {DOCUMENT, isPlatformBrowser} from '@angular/common'; import {Injectable, PLATFORM_ID, inject, signal} from '@angular/core'; import {LOCAL_STORAGE} from '@angular/docs'; import {Subject} from 'rxjs'; // Keep these constants in sync with the code in index.html export const THEME_PREFERENCE_LOCAL_STORAGE_KEY = 'themePreference'; export const DARK_MODE_CLASS_NAME = 'docs-dark-mode'; export const LIGHT_MODE_CLASS_NAME = 'docs-light-mode'; export const PREFERS_COLOR_SCHEME_DARK = '(prefers-color-scheme: dark)'; export type Theme = 'dark' | 'light' | 'auto'; @Injectable({ providedIn: 'root', }) export class ThemeManager { private readonly document = inject(DOCUMENT); private readonly localStorage = inject(LOCAL_STORAGE); private readonly platformId = inject(PLATFORM_ID); readonly theme = signal<Theme | null>(this.getThemeFromLocalStorageValue()); // Zoneless - it's required to notify that theme was changed. It could be removed when signal-based components will be available. readonly themeChanged$ = new Subject<void>(); constructor() { if (!isPlatformBrowser(this.platformId)) { return; } this.loadThemePreference(); this.watchPreferredColorScheme(); } setTheme(theme: Theme): void { this.theme.set(theme); this.setThemeInLocalStorage(); this.setThemeBodyClasses(theme === 'auto' ? preferredScheme() : theme); } // 1. Read theme preferences stored in localStorage // 2. In case when there are no stored user preferences, then read them from device preferences. private loadThemePreference(): void { const savedUserPreference = this.getThemeFromLocalStorageValue(); const useTheme = savedUserPreference ?? 'auto'; this.theme.set(useTheme); this.setThemeBodyClasses(useTheme === 'auto' ? preferredScheme() : useTheme); } // Set theme classes on the body element private setThemeBodyClasses(theme: 'dark' | 'light'): void { const documentClassList = this.document.documentElement.classList; if (theme === 'dark') { documentClassList.add(DARK_MODE_CLASS_NAME); documentClassList.remove(LIGHT_MODE_CLASS_NAME); } else { documentClassList.add(LIGHT_MODE_CLASS_NAME); documentClassList.remove(DARK_MODE_CLASS_NAME); } this.themeChanged$.next(); } private getThemeFromLocalStorageValue(): Theme | null { const theme = this.localStorage?.getItem(THEME_PREFERENCE_LOCAL_STORAGE_KEY) as Theme | null; return theme ?? null; } private setThemeInLocalStorage(): void { if (this.theme()) { this.localStorage?.setItem(THEME_PREFERENCE_LOCAL_STORAGE_KEY, this.theme()!); } } private watchPreferredColorScheme() { window.matchMedia(PREFERS_COLOR_SCHEME_DARK).addEventListener('change', (event) => { const preferredScheme = event.matches ? 'dark' : 'light'; this.setThemeBodyClasses(preferredScheme); }); } } function preferredScheme(): 'dark' | 'light' { return window.matchMedia(PREFERS_COLOR_SCHEME_DARK).matches ? 'dark' : 'light'; }
004319
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {DOCUMENT, isPlatformBrowser} from '@angular/common'; import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Injector, OnDestroy, OnInit, PLATFORM_ID, ViewChild, inject, } from '@angular/core'; import {WINDOW, shouldReduceMotion, isIos} from '@angular/docs'; import {ActivatedRoute, RouterLink} from '@angular/router'; import {injectAsync} from '../../core/services/inject-async'; import {CodeEditorComponent} from './components/home-editor.component'; import {HEADER_CLASS_NAME} from './home-animation-constants'; import type {HomeAnimation} from './services/home-animation.service'; export const TUTORIALS_HOMEPAGE_DIRECTORY = 'homepage'; @Component({ standalone: true, selector: 'adev-home', imports: [RouterLink, CodeEditorComponent], templateUrl: './home.component.html', styleUrls: ['./home.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export default class Home implements OnInit, AfterViewInit, OnDestroy { @ViewChild('home') home!: ElementRef<HTMLDivElement>; private readonly document = inject(DOCUMENT); private readonly injector = inject(Injector); private readonly platformId = inject(PLATFORM_ID); private readonly window = inject(WINDOW); private readonly activatedRoute = inject(ActivatedRoute); protected readonly tutorialFiles = TUTORIALS_HOMEPAGE_DIRECTORY; protected readonly isUwu = 'uwu' in this.activatedRoute.snapshot.queryParams; private element!: HTMLDivElement; private homeAnimation?: HomeAnimation; private intersectionObserver: IntersectionObserver | undefined; ctaLink = 'tutorials/learn-angular'; ctaIosLink = 'overview'; ngOnInit(): void { if (isIos) { this.ctaLink = this.ctaIosLink; } } ngAfterViewInit() { this.element = this.home.nativeElement; if (isPlatformBrowser(this.platformId)) { // Always scroll to top on home page (even for navigating back) this.window.scrollTo({top: 0, left: 0, behavior: 'instant'}); // Create a single intersection observer used for disabling the animation // at the end of the page, and to load the embedded editor. this.initIntersectionObserver(); if (this.isWebGLAvailable() && !shouldReduceMotion() && !this.isUwu) { this.loadHomeAnimation(); } } } ngOnDestroy(): void { if (isPlatformBrowser(this.platformId)) { // Stop observing and disconnect this.intersectionObserver?.disconnect(); if (this.homeAnimation) { this.homeAnimation.destroy(); } } } private initIntersectionObserver(): void { const header = this.document.querySelector('.adev-top'); const footer = this.document.querySelector('footer'); this.intersectionObserver = new IntersectionObserver((entries) => { const headerEntry = entries.find((entry) => entry.target === header); const footerEntry = entries.find((entry) => entry.target === footer); // CTA and arrow animation this.headerTop(headerEntry); // Disable animation at end of page if (this.homeAnimation) { this.homeAnimation.disableEnd(footerEntry); } }); // Start observing this.intersectionObserver.observe(header!); this.intersectionObserver.observe(footer!); } private headerTop(headerEntry: IntersectionObserverEntry | undefined): void { if (!headerEntry) { return; } if (headerEntry.isIntersecting) { this.element.classList.add(HEADER_CLASS_NAME); } else { this.element.classList.remove(HEADER_CLASS_NAME); } } private async loadHomeAnimation() { this.homeAnimation = await injectAsync(this.injector, () => import('./services/home-animation.service').then((c) => c.HomeAnimation), ); await this.homeAnimation.init(this.element); } private isWebGLAvailable() { try { return !!document .createElement('canvas') .getContext('webgl', {failIfMajorPerformanceCaveat: true}); } catch (e) { return false; } } }
004329
/*! * @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 {ComponentFixture, TestBed} from '@angular/core/testing'; // import Home from './home.component'; // import {HomeAnimation} from './services/home-animation.service'; // TODO: refactor for lazy-loading when both conditions are met // 1. WebGL is available with isWebGLAvailable() // 2. When a user's device settings are not set to reduced motion with !shouldReduceMotion() /* describe('Home', () => { let component: Home; let fixture: ComponentFixture<Home>; let fakeHomeAnimation = { init: () => Promise.resolve(), destroy: () => {}, }; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [Home], }).compileComponents(); TestBed.overrideProvider(HomeAnimation, {useValue: fakeHomeAnimation}); fixture = TestBed.createComponent(Home); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should call homeAnimation.destroy() on ngOnDestroy', () => { const destroySpy = spyOn(fakeHomeAnimation, 'destroy'); component.ngOnDestroy(); expect(destroySpy).toHaveBeenCalled(); }); }); */
004366
/*! * @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 {DOCS_VIEWER_SELECTOR, DocViewer, WINDOW} from '@angular/docs'; import {Component, Input, signal} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {RouterTestingModule} from '@angular/router/testing'; import {of} from 'rxjs'; import { EMBEDDED_EDITOR_SELECTOR, EmbeddedEditor, EmbeddedTutorialManager, NodeRuntimeSandbox, } from '../../editor'; import {mockAsyncProvider} from '../../core/services/inject-async'; import Tutorial from './tutorial.component'; import {TutorialConfig, TutorialType} from '@angular/docs'; @Component({ selector: EMBEDDED_EDITOR_SELECTOR, template: '<div>FakeEmbeddedEditor</div>', standalone: true, }) class FakeEmbeddedEditor {} @Component({ selector: DOCS_VIEWER_SELECTOR, template: '<div>FakeDocsViewer</div>', standalone: true, }) class FakeDocViewer { @Input('documentFilePath') documentFilePath: string | undefined; } // TODO: export this class, it's a helpful mock we could you on other tests. class FakeNodeRuntimeSandbox { loadingStep = signal(0); previewUrl$ = of(); writeFile(path: string, content: string) { return Promise.resolve(); } init() { return Promise.resolve(); } } describe('Tutorial', () => { let component: Tutorial; let fixture: ComponentFixture<Tutorial>; const fakeWindow = { addEventListener: () => {}, removeEventListener: () => {}, }; const fakeEmbeddedTutorialManager: Partial<EmbeddedTutorialManager> = { tutorialFiles: signal({'app.component.ts': 'original'}), answerFiles: signal({'app.component.ts': 'answer'}), type: signal(TutorialType.EDITOR), revealAnswer: () => {}, resetRevealAnswer: () => {}, tutorialChanged$: of(false), openFiles: signal<NonNullable<TutorialConfig['openFiles']>>(['app.component.ts']), }; function setupRevealAnswerValues() { component['shouldRenderRevealAnswer'].set(true); component['canRevealAnswer'] = signal(true); component['embeddedTutorialManager'].answerFiles.set({'app.component.ts': 'answer'}); } function setupDisabledRevealAnswerValues() { component['shouldRenderRevealAnswer'].set(true); component['canRevealAnswer'] = signal(false); component['embeddedTutorialManager'].answerFiles.set({'app.component.ts': 'answer'}); } function setupNoRevealAnswerValues() { component['shouldRenderRevealAnswer'].set(false); component['canRevealAnswer'] = signal(true); component['embeddedTutorialManager'].answerFiles.set({}); } function setupResetRevealAnswerValues() { setupRevealAnswerValues(); component['answerRevealed'].set(true); } beforeEach(async () => { TestBed.configureTestingModule({ imports: [Tutorial, RouterTestingModule, EmbeddedEditor, DocViewer, NoopAnimationsModule], providers: [ { provide: WINDOW, useValue: fakeWindow, }, { provide: EmbeddedTutorialManager, useValue: fakeEmbeddedTutorialManager, }, mockAsyncProvider(NodeRuntimeSandbox, FakeNodeRuntimeSandbox), ], }); TestBed.overrideComponent(Tutorial, { remove: { imports: [DocViewer], }, add: { imports: [FakeDocViewer], }, }); await TestBed.compileComponents(); fixture = TestBed.createComponent(Tutorial); component = fixture.componentInstance; // Replace EmbeddedEditor with FakeEmbeddedEditor spyOn(component as any, 'loadEmbeddedEditorComponent').and.resolveTo(FakeEmbeddedEditor); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); // TODO: Add tests in a future PR // it('should render the embedded editor based on the tutorial config', () => {}); // it('should not render the embedded editor based on the tutorial config', () => {}); // it('should load the tutorial', () => {}); it('should reset the reveal answer', async () => { setupResetRevealAnswerValues(); fixture.detectChanges(); if (!component.revealAnswerButton) throw new Error('revealAnswerButton is undefined'); const revealAnswerSpy = spyOn(component['embeddedTutorialManager'], 'revealAnswer'); const resetRevealAnswerSpy = spyOn(component['embeddedTutorialManager'], 'resetRevealAnswer'); component.revealAnswerButton.nativeElement.click(); expect(revealAnswerSpy).not.toHaveBeenCalled(); expect(resetRevealAnswerSpy).toHaveBeenCalled(); }); it('should reveal the answer on button click', async () => { setupRevealAnswerValues(); fixture.detectChanges(); if (!component.revealAnswerButton) throw new Error('revealAnswerButton is undefined'); const embeddedTutorialManagerRevealAnswerSpy = spyOn( component['embeddedTutorialManager'], 'revealAnswer', ); component.revealAnswerButton.nativeElement.click(); expect(embeddedTutorialManagerRevealAnswerSpy).toHaveBeenCalled(); await fixture.whenStable(); fixture.detectChanges(); expect(component.revealAnswerButton.nativeElement.textContent?.trim()).toBe('Reset'); }); it('should not reveal the answer when button is disabled', async () => { setupDisabledRevealAnswerValues(); fixture.detectChanges(); if (!component.revealAnswerButton) throw new Error('revealAnswerButton is undefined'); spyOn(component, 'canRevealAnswer').and.returnValue(false); const handleRevealAnswerSpy = spyOn(component, 'handleRevealAnswer'); component.revealAnswerButton.nativeElement.click(); expect(component.revealAnswerButton.nativeElement.getAttribute('disabled')).toBeDefined(); expect(handleRevealAnswerSpy).not.toHaveBeenCalled(); }); it('should not render the reveal answer button when there are no answers', () => { setupNoRevealAnswerValues(); fixture.detectChanges(); expect(component.revealAnswerButton).toBe(undefined); }); });
004380
possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'debug', action: 'With Angular 9 Ivy is now the default rendering engine, for any compatibility problems that might arise, read the [Ivy compatibility guide](https://v9.angular.io/guide/ivy-compatibility).', }, { possibleIn: 900, necessaryAsOf: 900, level: ApplicationComplexity.Advanced, step: 'express-universal-server', action: 'If you use Angular Universal with `@nguniversal/express-engine` or `@nguniversal/hapi-engine`, several backup files will be created. One of them for `server.ts`. If this file defers from the default one, you may need to copy some changes from the `server.ts.bak` to `server.ts` manually.', }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, step: 'ivy i18n', action: "Angular 9 introduced a global `$localize()` function that needs to be loaded if you depend on Angular's internationalization (i18n). Run `ng add @angular/localize` to add the necessary packages and code modifications. Consult the [$localize Global Import Migration guide](https://v9.angular.io/guide/migration-localize) to learn more about the changes.", }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'entryComponents', action: 'In your application projects, you can remove `entryComponents` NgModules and any uses of `ANALYZE_FOR_ENTRY_COMPONENTS`. They are no longer required with the Ivy compiler and runtime. You may need to keep these if building a library that will be consumed by a View Engine application.', }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'testbed-get', action: 'If you use `TestBed.get`, you should instead use `TestBed.inject`. This new method has the same behavior, but is type safe.', }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: '$localize', action: "If you use [Angular's i18n support](http://angular.io/guide/i18n), you will need to begin using `@angular/localize`. Learn more about the [$localize Global Import Migration](https://v9.angular.io/guide/migration-localize).", }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, step: 'v10 NodeJS 12', action: 'Make sure you are using <a href="https://nodejs.org/dist/latest-v12.x/" target="_blank">Node 12 or later</a>.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, step: 'ng update v10', action: 'Run `npx @angular/cli@10 update @angular/core@10 @angular/cli@10` which should bring you to version 10 of Angular.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `npx @angular/cli@10 update @angular/material@10`.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Basic, step: 'browserlist', action: 'New projects use the filename `.browserslistrc` instead of `browserslist`. `ng update` will migrate you automatically.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'v10-versions', action: 'Angular now requires `tslint` v6, `tslib` v2, and [TypeScript 3.9](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-9.html). `ng update` will migrate you automatically.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'styleext', action: 'Stop using `styleext` or `spec` in your Angular schematics. `ng update` will migrate you automatically.', }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'classes-without-decorators', action: 'In version 10, classes that use Angular features and do not have an Angular decorator are no longer supported. [Read more](https://v10.angular.io/guide/migration-undecorated-classes). `ng update` will migrate you automatically.', }, { possibleIn: 900, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'injectable-definitions', action: 'As of Angular 9, enforcement of @Injectable decorators for DI is stricter and incomplete provider definitions behave differently. [Read more](https://v9.angular.io/guide/migration-injectable). `ng update` will migrate you automatically.', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'closure-jsdoc-comments', action: "Angular's NPM packages no longer contain jsdoc comments, which are necessary for use with closure compiler (extremely uncommon). This support was experimental and only worked in some use cases. There will be an alternative recommended path announced shortly.", }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'forms-number-input', action: 'If you use Angular forms, inputs of type `number` no longer listen to [change events](https://developer.mozilla.org/docs/Web/API/HTMLElement/change_event) (this events are not necessarily fired for each alteration the value), instead listen for an [input events](https://developer.mozilla.org/docs/Web/API/HTMLElement/input_event). ', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'forms-length-input', action: "For Angular forms validation, the `minLength` and `maxLength` validators now verify that the form control's value has a numeric length property, and only validate for length if that's the case.", }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'esm5-bundles', action: "The [Angular Package Format](https://g.co/ng/apf) has been updated to remove `esm5` and `fesm5` formats. These are no longer distributed in our npm packages. If you don't use the CLI, you may need to downlevel Angular code to ES5 yourself.", }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Medium, step: 'console-errors', action: "Warnings about unknown elements are now logged as errors. This won't break your app, but it may trip up tools that expect nothing to be logged via `console.error`.", }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'router-resolver-empty', action: 'Any resolver which returns `EMPTY` will cancel navigation. If you want to allow navigation to continue, you will need to update the resolvers to emit some value, (i.e. `defaultIfEmpty(...)`, `of(...)`, etc).', }, { possibleIn: 1000, necessaryAsOf: 1000, level: ApplicationComplexity.Advanced, step: 'sw-vary-headers', action: 'If you use the Angular service worker and rely on resources with [Vary](https://developer.mozilla.org/docs/Web/HTTP/Headers/Vary) headers, these headers are now ignored to avoid unpredictable behavior across browsers. To avoid this, [configure](https://angular.io/guide/service-worker-config) your service worker to avoid caching these resources.', },
004386
possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 iframe', action: "Existing `<iframe>` instances might have security-sensitive attributes applied to them as an attribute or property binding. These security-sensitive attributes can occur in a template or in a directive's host bindings. Such occurrences require an update to ensure compliance with the new and stricter rules about `<iframe>` bindings. For more information, see [the error page](https://v15.angular.io/errors/NG0910).", }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 Injector.get', action: 'Update instances of `Injector.get()` that use an `InjectFlags` parameter to use an `InjectOptions` parameter. The `InjectFlags` parameter of `Injector.get()` is deprecated in v15. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-02" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 TestBed.inject', action: 'Update instances of `TestBed.inject()` that use an `InjectFlags` parameter to use an `InjectOptions` parameter. The `InjectFlags` parameter of `TestBed.inject()` is deprecated in v15. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-01" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 ngModule in providedIn', action: 'Using `providedIn: ngModule` for an `@Injectable` and `InjectionToken` is deprecated in v15. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-04" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 providedIn any', action: 'Using `providedIn: \'any\'` for an `@Injectable` or `InjectionToken` is deprecated in v15. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-05" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Medium, step: 'v15 RouterLinkWithHref', action: 'Update instances of the `RouterLinkWithHref`directive to use the `RouterLink` directive. The `RouterLinkWithHref` directive is deprecated in v15. <a href="https://v15.angular.io/guide/update-to-version-15#v15-dp-06" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, material: true, step: 'v15 mat refactor', action: 'In Angular Material v15, many of the components have been refactored to be based on the official Material Design Components for Web (MDC). This change affected the DOM and CSS classes of many components. <a href="https://rc.material.angular.io/guide/mdc-migration" alt="Link to more information about this change">Read further</a>', }, { possibleIn: 1500, necessaryAsOf: 1500, level: ApplicationComplexity.Basic, step: 'v15 visual review', action: 'After you update your application to v15, visually review your application and its interactions to ensure everything is working as it should.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 node support', action: 'Make sure that you are using a supported version of node.js before you upgrade your application. Angular v16 supports node.js versions: v16 and v18.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 ts support', action: 'Make sure that you are using a supported version of TypeScript before you upgrade your application. Angular v16 supports TypeScript version 4.9.3 or later.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 ng update', action: "In the application's project directory, run `ng update @angular/core@16 @angular/cli@16` to update your application to Angular v16.", }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `ng update @angular/material@16`.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 zone.js support', action: 'Make sure that you are using a supported version of Zone.js before you upgrade your application. Angular v16 supports Zone.js version 0.13.x or later.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 RouterEvent', action: "The Event union no longer contains `RouterEvent`, which means that if you're using the Event type you may have to change the type definition from `(e: Event)` to `(e: Event|RouterEvent)`", }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 routerEvent prop type', action: 'In addition to `NavigationEnd` the `routerEvent` property now also accepts type `NavigationSkipped`', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 RendererType2', action: 'Pass only flat arrays to `RendererType2.styles` because it no longer accepts nested arrays', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 BrowserPlatformLocation', action: 'You may have to update tests that use `BrowserPlatformLocation` because `MockPlatformLocation` is now provided by default in tests. [Read further](https://github.com/angular/angular/blob/main/CHANGELOG.md#common-9).', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 ngcc', action: 'Due to the removal of the Angular Compatibility Compiler (ngcc) in v16, projects on v16 and later no longer support View Engine libraries.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 createUrlTree', action: 'After bug fixes in `Router.createUrlTree` you may have to readjust tests which mock `ActiveRoute`. [Read further](https://github.com/angular/angular/blob/main/CHANGELOG.md#1600-next1-2023-03-01)', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 ApplicationConfig imports', action: 'Change imports of `ApplicationConfig` to be from `@angular/core`.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 renderModule', action: 'Revise your code to use `renderModule` instead of `renderModuleFactory` because it has been deleted.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 XhrFactory', action: 'Revise your code to use `XhrFactory` from `@angular/common` instead of `XhrFactory` export from `@angular/common/http`.', },
004387
possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 withServerTransition', action: "If you're running multiple Angular apps on the same page and you're using `BrowserModule.withServerTransition({ appId: 'serverApp' })` make sure you set the `APP_ID` instead since `withServerTransition` is now deprecated. [Read further](https://github.com/angular/angular/blob/main/CHANGELOG.md#platform-browser-4)", }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 EnvironmentInjector', action: 'Change `EnvironmentInjector.runInContext` to `runInInjectionContext` and pass the environment injector as the first parameter.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 ViewContainerRef.createComponent', action: 'Update your code to use `ViewContainerRef.createComponent` without the factory resolver. `ComponentFactoryResolver` has been removed from Router APIs.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 APP_ID', action: 'If you bootstrap multiple apps on the same page, make sure you set unique `APP_IDs`.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 server renderApplication', action: 'Update your code to revise `renderApplication` method as it no longer accepts a root component as first argument, but instead a callback that should bootstrap your app. [Read further](https://github.com/angular/angular/blob/main/CHANGELOG.md#platform-server-3)', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 PlatformConfig.baseUrl', action: 'Update your code to remove any reference to `PlatformConfig.baseUrl` and `PlatformConfig.useAbsoluteUrl` platform-server config options as it has been deprecated.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 moduleid', action: 'Update your code to remove any reference to `@Directive`/`@Component` `moduleId` property as it does not have any effect and will be removed in v17.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 transfer state imports', action: "Update imports from `import {makeStateKey, StateKey, TransferState} from '@angular/platform-browser'` to `import {makeStateKey, StateKey, TransferState} from '@angular/core'`", }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 ComponentRef', action: "If you rely on `ComponentRef.setInput` to set the component input even if it's the same based on `Object.is` equality check, make sure you copy its value.", }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 ANALYZE_FOR_ENTRY_COMPONENTS', action: 'Update your code to remove any reference to `ANALYZE_FOR_ENTRY_COMPONENTS` injection token as it has been deleted.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 entry components', action: '`entryComponents` is no longer available and any reference to it can be removed from the `@NgModule` and `@Component` public APIs.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 ngTemplateOutletContext', action: 'ngTemplateOutletContext has stricter type checking which requires you to declare all the properties in the corresponding object. [Read further](https://github.com/angular/angular/blob/main/CHANGELOG.md#common-1).', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 APF', action: 'Angular packages no longer include FESM2015 and the distributed ECMScript has been updated from 2020 to 2022.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Advanced, step: 'v16 EventManager', action: 'The deprecated `EventManager` method `addGlobalEventListener` has been removed as it is not used by Ivy.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 BrowserTransferStateModule', action: '`BrowserTransferStateModule` is no longer available and any reference to it can be removed from your applications.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Medium, step: 'v16 ReflectiveInjector', action: 'Update your code to use `Injector.create` rather than `ReflectiveInjector` since `ReflectiveInjector` is removed.', }, { possibleIn: 1600, necessaryAsOf: 1600, level: ApplicationComplexity.Basic, step: 'v16 QueryList', action: '`QueryList.filter` now supports type guard functions. Since the type will be narrowed, you may have to update your application code that relies on the old behavior.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 node support', action: 'Make sure that you are using a supported version of node.js before you upgrade your application. Angular v17 supports node.js versions: v18.13.0 and newer', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 ts support', action: 'Make sure that you are using a supported version of TypeScript before you upgrade your application. Angular v17 supports TypeScript version 5.2 or later.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 zone.js support', action: 'Make sure that you are using a supported version of Zone.js before you upgrade your application. Angular v17 supports Zone.js version 0.14.x or later.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 ng update', action: "In the application's project directory, run `ng update @angular/core@17 @angular/cli@17` to update your application to Angular v17.", }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `ng update @angular/material@17`.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Medium, step: 'v17 style removal', action: 'Angular now automatically removes styles of destroyed components, which may impact your existing apps in cases you rely on leaked styles. To change this update the value of the `REMOVE_STYLES_ON_COMPONENT_DESTROY` provider to `false`.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 router removals', action: "Make sure you configure `setupTestingRouter`, `canceledNavigationResolution`, `paramsInheritanceStrategy`, `titleStrategy`, `urlUpdateStrategy`, `urlHandlingStrategy`, and `malformedUriErrorHandler` in `provideRouter` or `RouterModule.forRoot` since these properties are now not part of the `Router`'s public API", },
004388
possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Advanced, step: 'v17 ngDoCheck dynamic components', action: 'For dynamically instantiated components we now execute `ngDoCheck` during change detection if the component is marked as dirty. You may need to update your tests or logic within `ngDoCheck` for dynamically instantiated components.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Medium, step: 'v17 malformedUriErrorHandler', action: "Handle URL parsing errors in the `UrlSerializer.parse` instead of `malformedUriErrorHandler` because it's now part of the public API surface.", }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Medium, step: 'v17 zone deep imports', action: 'Change Zone.js deep imports like `zone.js/bundles/zone-testing.js` and `zone.js/dist/zone` to `zone.js` and `zone.js/testing`.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Advanced, step: 'v17 absolute redirects', action: 'You may need to adjust your router configuration to prevent infinite redirects after absolute redirects. In v17 we no longer prevent additional redirects after absolute redirects.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Medium, step: 'v17 AnimationDriver', action: 'Change references to `AnimationDriver.NOOP` to use `NoopAnimationDriver` because `AnimationDriver.NOOP` is now deprecated.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 switch strictness', action: "You may need to adjust the equality check for `NgSwitch` because now it defaults to stricter check with `===` instead of `==`. Angular will log a warning message for the usages where you'd need to provide an adjustment.", }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Advanced, step: 'v17 mutate in signals', action: 'Use `update` instead of `mutate` in Angular Signals. For example `items.mutate(itemsArray => itemsArray.push(newItem));` will now be `items.update(itemsArray => [itemsArray, …newItem]);`', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Medium, step: 'v17 withNoDomReuse', action: 'To disable hydration use `ngSkipHydration` or remove the `provideClientHydration` call from the provider list since `withNoDomReuse` is no longer part of the public API.', }, { possibleIn: 1700, necessaryAsOf: 1700, level: ApplicationComplexity.Basic, step: 'v17 paramsInheritanceStrategy', action: 'If you want the child routes of `loadComponent` routes to inherit data from their parent specify the `paramsInheritanceStrategy` to `always`, which in v17 is now set to `emptyOnly`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Basic, step: 'v18 node support', action: 'Make sure that you are using a supported version of node.js before you upgrade your application. Angular v18 supports node.js versions: v18.19.0 and newer', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Basic, step: 'v18 ng update', action: "In the application's project directory, run `ng update @angular/core@18 @angular/cli@18` to update your application to Angular v18.", }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Basic, material: true, step: 'update @angular/material', action: 'Run `ng update @angular/material@18`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Basic, step: '18.0.0 Upgrade TypeScript', action: 'Update TypeScript to versions 5.4 or newer.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: async has been removed, use `waitForAsync` instead', action: 'Replace `async` from `@angular/core` with `waitForAsync`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: Deprecated matchesElement method removed from AnimationDriver', action: "Remove calls to `matchesElement` because it's now not part of `AnimationDriver`.", }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0. Use `@angular/core` StateKey and TransferState', action: 'Import `StateKey` and `TransferState` from `@angular/core` instead of `@angular/platform-browser`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0. Opt-in of caching for HTTP requests with auth headers', action: 'Use `includeRequestsWithAuthHeaders: true` in `withHttpTransferCache` to opt-in of caching for HTTP requests that require authorization.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0.REMOVE_OBSOLETE_IS_WORKER', action: 'Update the application to remove `isPlatformWorkerUi` and `isPlatformWorkerApp` since they were part of platform WebWorker which is now not part of Angular.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0.FORCE_ZONE_CHANGE_DETECTION', action: 'Tests may run additional rounds of change detection to fully reflect test state in the DOM. As a last resort, revert to the old behavior by adding `provideZoneChangeDetection({ignoreChangesOutsideZone: true})` to the TestBed providers.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0: Remove two-way binding expressions in writable bindings', action: 'Remove expressions that write to properties in templates that use `[(ngModel)]`', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: Use zones to track pending requests', action: 'Remove calls to `Testability` methods `increasePendingRequestCount`, `decreasePendingRequestCount`, and `getPendingRequestCount`. This information is tracked by ZoneJS.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Medium, step: '18.0.0: Move shared providers to the routed component', action: 'Move any environment providers that should be available to routed components from the component that defines the `RouterOutlet` to the providers of `bootstrapApplication` or the `Route` config.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0 Use RedirectCommand or new NavigationBehaviorOptions', action: 'When a guard returns a `UrlTree` as a redirect, the redirecting navigation will now use `replaceUrl` if the initial navigation was also using the `replaceUrl` option. If you prefer the previous behavior, configure the redirect using the new `NavigationBehaviorOptions` by returning a `RedirectCommand` with the desired options instead of `UrlTree`.', }, { possibleIn: 1800, necessaryAsOf: 1800, level: ApplicationComplexity.Advanced, step: '18.0.0: Remove deprecated resource cache providers', action: "Remove dependencies of `RESOURCE_CACHE_PROVIDER` since it's no longer part of the Angular runtime.", },
004424
/*! * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {DOCUMENT, isPlatformBrowser} from '@angular/common'; import { DestroyRef, EnvironmentInjector, Injectable, OnDestroy, PLATFORM_ID, afterNextRender, inject, signal, } from '@angular/core'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {fromEvent} from 'rxjs'; import {auditTime} from 'rxjs/operators'; import { API_REFERENCE_DETAILS_PAGE_MEMBERS_CLASS_NAME, API_REFERENCE_MEMBER_CARD_CLASS_NAME, API_TAB_ACTIVE_CODE_LINE, MEMBER_ID_ATTRIBUTE, } from '../constants/api-reference-prerender.constants'; import {WINDOW} from '@angular/docs'; import {Router} from '@angular/router'; import {AppScroller} from '../../../app-scroller'; export const SCROLL_EVENT_DELAY = 20; export const SCROLL_THRESHOLD = 20; @Injectable() export class ReferenceScrollHandler implements OnDestroy { private readonly destroyRef = inject(DestroyRef); private readonly document = inject(DOCUMENT); private readonly injector = inject(EnvironmentInjector); private readonly window = inject(WINDOW); private readonly router = inject(Router); private readonly appScroller = inject(AppScroller); private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID)); private readonly cardOffsetTop = new Map<string, number>(); private resizeObserver: ResizeObserver | null = null; membersMarginTopInPx = signal<number>(0); ngOnDestroy(): void { this.resizeObserver?.disconnect(); } setupListeners(tocSelector: string): void { if (!this.isBrowser) { return; } this.setupCodeToCListeners(tocSelector); this.setupMemberCardListeners(); this.setScrollEventHandlers(); this.listenToResizeCardContainer(); this.setupFragmentChangeListener(); } private setupFragmentChangeListener() { this.router.routerState.root.fragment .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((fragment) => { // If there is no fragment or the scroll event has a position (traversing through history), // allow the scroller to handler scrolling instead of going to the fragment if (!fragment || this.appScroller.lastScrollEvent?.position) { this.appScroller.scroll(); return; } const card = this.document.getElementById(fragment) as HTMLDivElement | null; this.scrollToCard(card); }); } updateMembersMarginTop(selectorOfTheElementToAlign: string): void { if (!this.isBrowser) { return; } const elementToAlign = this.document.querySelector<HTMLElement>(selectorOfTheElementToAlign); if (elementToAlign) { this.updateMarginTopWhenTabBodyIsResized(elementToAlign); } } private setupCodeToCListeners(tocSelector: string): void { const tocContainer = this.document.querySelector<HTMLDivElement>(tocSelector); if (!tocContainer) { return; } fromEvent(tocContainer, 'click') .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((event) => { if (event.target instanceof HTMLAnchorElement) { event.stopPropagation(); return; } // Get the card member ID from the attributes const target = event.target instanceof HTMLButtonElement ? event.target : this.findButtonElement(event.target as HTMLElement); const memberId = this.getMemberId(target); if (memberId) { this.router.navigate([], {fragment: memberId, replaceUrl: true}); } }); } private setupMemberCardListeners(): void { this.getAllMemberCards().forEach((card) => { this.cardOffsetTop.set(card.id, card.offsetTop); const header = card.querySelector('header'); if (!header) { return; } fromEvent(header, 'click') .pipe(takeUntilDestroyed(this.destroyRef)) .subscribe((event) => { const target = event.target as HTMLElement; if (target instanceof HTMLAnchorElement) { return; } this.router.navigate([], {fragment: card.id, replaceUrl: true}); }); }); } private setScrollEventHandlers(): void { const scroll$ = fromEvent(this.document, 'scroll').pipe( auditTime(SCROLL_EVENT_DELAY), takeUntilDestroyed(this.destroyRef), ); scroll$.subscribe(() => this.setActiveCodeLine()); } private listenToResizeCardContainer(): void { const membersCardContainer = this.document.querySelector( API_REFERENCE_DETAILS_PAGE_MEMBERS_CLASS_NAME, ); if (membersCardContainer) { afterNextRender( () => { const resizeObserver = new ResizeObserver(() => { this.updateCardsOffsetTop(); this.setActiveCodeLine(); }); resizeObserver.observe(membersCardContainer); this.destroyRef.onDestroy(() => resizeObserver.disconnect()); }, {injector: this.injector}, ); } } private setActiveCodeLine(): void { const activeCard = Array.from(this.cardOffsetTop) .filter(([_, offsetTop]) => { return offsetTop < this.window.scrollY + this.membersMarginTopInPx() + SCROLL_THRESHOLD; }) .pop(); if (!activeCard) { return; } const activeLines = this.document.querySelectorAll<HTMLButtonElement>( `button.${API_TAB_ACTIVE_CODE_LINE}`, ); const activeLine = activeLines.length > 0 ? activeLines.item(0) : null; const previousActiveMemberId = this.getMemberId(activeLine); const currentActiveMemberId = activeCard[0]; if (previousActiveMemberId && previousActiveMemberId !== currentActiveMemberId) { for (const line of Array.from(activeLines)) { line.classList.remove(API_TAB_ACTIVE_CODE_LINE); } } else { const lines = this.document.querySelectorAll<HTMLButtonElement>( `button[${MEMBER_ID_ATTRIBUTE}="${currentActiveMemberId}"]`, ); for (const line of Array.from(lines)) { line.classList.add(API_TAB_ACTIVE_CODE_LINE); } this.document.getElementById(`${currentActiveMemberId}`)?.focus({preventScroll: true}); } } private scrollToCard(card: HTMLDivElement | null): void { if (!card) { return; } if (card !== <HTMLElement>document.activeElement) { (<HTMLElement>document.activeElement).blur(); } this.window.scrollTo({ top: card!.offsetTop - this.membersMarginTopInPx(), behavior: 'smooth', }); } private updateCardsOffsetTop(): void { this.getAllMemberCards().forEach((card) => { this.cardOffsetTop.set(card.id, card.offsetTop); }); } private getAllMemberCards(): NodeListOf<HTMLDivElement> { return this.document.querySelectorAll<HTMLDivElement>( `${API_REFERENCE_MEMBER_CARD_CLASS_NAME}`, ); } private getMemberId(lineButton: HTMLButtonElement | null): string | undefined { if (!lineButton) { return undefined; } return lineButton.attributes.getNamedItem(MEMBER_ID_ATTRIBUTE)?.value; } private updateMarginTopWhenTabBodyIsResized(tabBody: HTMLElement): void { this.resizeObserver?.disconnect(); this.resizeObserver = new ResizeObserver((_) => { const offsetTop = tabBody.getBoundingClientRect().top; if (offsetTop) { this.membersMarginTopInPx.set(offsetTop); } }); this.resizeObserver.observe(tabBody); } private findButtonElement(element: HTMLElement) { let parent = element.parentElement; while (parent) { if (parent instanceof HTMLButtonElement) { return parent; } parent = parent.parentElement; } return null; } }
004515
# Deferrable Views ## Overview Deferrable views can be used in component template to defer the loading of select dependencies within that template. Those dependencies include components, directives, and pipes, and any associated CSS. To use this feature, you can declaratively wrap a section of your template in a `@defer` block which specifies the loading conditions. Deferrable views support a series of [triggers](guide/defer#triggers), [prefetching](guide/defer#prefetching), and several sub blocks used for [placeholder](guide/defer#placeholder), [loading](guide/defer#loading), and [error](guide/defer#error) state management. You can also create custom conditions with [`when`](guide/defer#when) and [`prefetch when`](guide/defer#prefetching). ```angular-html @defer { <large-component /> } ``` ## Why use Deferrable Views? Deferrable views, also known as `@defer` blocks, are a powerful tool that can be used to reduce the initial bundle size of your application or defer heavy components that may not ever be loaded until a later time. This should result in a faster initial load and an improvement in your Core Web Vitals (CWV) results. Deferring some of your components until later should specifically improve Largest Contentful Paint (LCP) and Time to First Byte (TTFB). Note: It is highly recommended that any defer loaded component that might result in layout shift once the dependencies have loaded be below the fold or otherwise not yet visible to the user. ## Which dependencies are defer-loadable? In order for dependencies within a `@defer` block to be deferred, they need to meet two conditions: 1. They must be standalone. Non-standalone dependencies cannot be deferred and will still be eagerly loaded, even inside of `@defer` blocks. 2. They must not be directly referenced from the same file, outside of `@defer` blocks; this includes ViewChild queries. Transitive dependencies of the components, directives, and pipes used in the defer block can be standalone or NgModule based and will still be deferred. ## Blocks `@defer` blocks have several sub blocks to allow you to gracefully handle different stages in the deferred loading process. ### `@defer` The content of the main `@defer` block is the section of content that is lazily loaded. It will not be rendered initially, and all of the content will appear once the specified [trigger](guide/defer#triggers) or `when` condition is met and the dependencies have been fetched. By default, a `@defer` block is triggered when the browser state becomes [idle](guide/defer#on-idle). ### `@placeholder` By default, defer blocks do not render any content before they are triggered. The `@placeholder` is an optional block that declares content to show before the defer block is triggered. This placeholder content is replaced with the main content once the loading is complete. You can use any content in the placeholder section including plain HTML, components, directives, and pipes; however keep in mind the dependencies of the placeholder block are eagerly loaded. Note: For the best user experience, you should always specify a `@placeholder` block. The `@placeholder` block accepts an optional parameter to specify the `minimum` amount of time that this placeholder should be shown. This `minimum` parameter is specified in time increments of milliseconds (ms) or seconds (s). This parameter exists to prevent fast flickering of placeholder content in the case that the deferred dependencies are fetched quickly. The `minimum` timer for the `@placeholder` block begins after the initial render of this `@placeholder` block completes. ```angular-html @defer { <large-component /> } @placeholder (minimum 500ms) { <p>Placeholder content</p> } ``` Note: Certain triggers may require the presence of either a `@placeholder` or a [template reference variable](guide/templates/variables#template-reference-variables) to function. See the [Triggers](guide/defer#triggers) section for more details. ### `@loading` The `@loading` block is an optional block that allows you to declare content that will be shown during the loading of any deferred dependencies. Its dependences are eagerly loaded (similar to `@placeholder`). For example, you could show a loading spinner. Once loading has been triggered, the `@loading` block replaces the `@placeholder` block. The `@loading` block accepts two optional parameters to specify the `minimum` amount of time that this placeholder should be shown and amount of time to wait `after` loading begins before showing the loading template. `minimum` and `after` parameters are specified in time increments of milliseconds (ms) or seconds (s). Just like `@placeholder`, these parameters exist to prevent fast flickering of content in the case that the deferred dependencies are fetched quickly. Both the `minimum` and `after` timers for the `@loading` block begins immediately after the loading has been triggered. ```angular-html @defer { <large-component /> } @loading (after 100ms; minimum 1s) { <img alt="loading..." src="loading.gif" /> } ``` ### `@error` The `@error` block allows you to declare content that will be shown if deferred loading fails. Similar to `@placeholder` and `@loading`, the dependencies of the `@error` block are eagerly loaded. The `@error` block is optional. ```angular-html @defer { <calendar-cmp /> } @error { <p>Failed to load the calendar</p> } ```
004516
## Triggers When a `@defer` block is triggered, it replaces placeholder content with lazily loaded content. There are two options for configuring when this swap is triggered: `on` and `when`. <a id="on"></a> `on` specifies a trigger condition using a trigger from the list of available triggers below. An example would be on interaction or on viewport. Multiple event triggers can be defined at once. For example: `on interaction; on timer(5s)` means that the defer block will be triggered if the user interacts with the placeholder, or after 5 seconds. Note: Multiple `on` triggers are always OR conditions. Similarly, `on` mixed with `when` conditions are also OR conditions. ```angular-html @defer (on viewport; on timer(5s)) { <calendar-cmp /> } @placeholder { <img src="placeholder.png" /> } ``` <a id="when"></a> `when` specifies a condition as an expression that returns a boolean. When this expression becomes truthy, the placeholder is swapped with the lazily loaded content (which may be an asynchronous operation if the dependencies need to be fetched). Note: if the `when` condition switches back to `false`, the defer block is not reverted back to the placeholder. The swap is a one-time operation. If the content within the block should be conditionally rendered, an `if` condition can be used within the block itself. ```angular-html @defer (when cond) { <calendar-cmp /> } ``` You could also use both `when` and `on` together in one statement, and the swap will be triggered if either condition is met. ```angular-html @defer (on viewport; when cond) { <calendar-cmp /> } @placeholder { <img src="placeholder.png" /> } ``` ### on idle `idle` will trigger the deferred loading once the browser has reached an idle state (detected using the `requestIdleCallback` API under the hood). This is the default behavior with a defer block. ### on viewport `viewport` would trigger the deferred block when the specified content enters the viewport using the [`IntersectionObserver` API](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API). This could be the placeholder content or an element reference. By default, the placeholder will act as the element watched for entering viewport as long as it is a single root element node. ```angular-html @defer (on viewport) { <calendar-cmp /> } @placeholder { <div>Calendar placeholder</div> } ``` Alternatively, you can specify a [template reference variable](guide/templates/variables#template-reference-variables) in the same template as the `@defer` block as the element that is watched to enter the viewport. This variable is passed in as a parameter on the viewport trigger. ```angular-html <div #greeting>Hello!</div> @defer (on viewport(greeting)) { <greetings-cmp /> } ``` ### on interaction `interaction` will trigger the deferred block when the user interacts with the specified element through `click` or `keydown` events. By default, the placeholder will act as the interaction element as long as it is a single root element node. ```angular-html @defer (on interaction) { <calendar-cmp /> } @placeholder { <div>Calendar placeholder</div> } ``` Alternatively, you can specify a [template reference variable](guide/templates/variables#template-reference-variables) as the element that triggers interaction. This variable is passed in as a parameter on the interaction trigger. ```angular-html <button type="button" #greeting>Hello!</button> @defer (on interaction(greeting)) { <calendar-cmp /> } @placeholder { <div>Calendar placeholder</div> } ``` ### on hover `hover` triggers deferred loading when the mouse has hovered over the trigger area. Events used for this are `mouseenter` and `focusin`. By default, the placeholder will act as the hover element as long as it is a single root element node. ```angular-html @defer (on hover) { <calendar-cmp /> } @placeholder { <div>Calendar placeholder</div> } ``` Alternatively, you can specify a [template reference variable](guide/templates/variables#template-reference-variables) as the hover element. This variable is passed in as a parameter on the hover trigger. ```angular-html <div #greeting>Hello!</div> @defer (on hover(greeting)) { <calendar-cmp /> } @placeholder { <div>Calendar placeholder</div> } ``` ### on immediate `immediate` triggers the deferred load immediately, meaning once the client has finished rendering, the defer chunk would then start fetching right away. ```angular-html @defer (on immediate) { <calendar-cmp /> } @placeholder { <div>Calendar placeholder</div> } ``` ### on timer `timer(x)` would trigger after a specified duration. The duration is required and can be specified in `ms` or `s`. ```angular-html @defer (on timer(500ms)) { <calendar-cmp /> } ``` ## Prefetching `@defer` allows to specify conditions when prefetching of the dependencies should be triggered. You can use a special `prefetch` keyword. `prefetch` syntax works similarly to the main defer conditions, and accepts `when` and/or `on` to declare the trigger. In this case, `when` and `on` associated with defer controls when to render, and `prefetch when` and `prefetch on` controls when to fetch the resources. This enables more advanced behaviors, such as letting you start to prefetch resources before a user has actually seen or interacted with a defer block, but might interact with it soon, making the resources available faster. In the example below, the prefetching starts when a browser becomes idle and the contents of the block is rendered on interaction. ```angular-html @defer (on interaction; prefetch on idle) { <calendar-cmp /> } @placeholder { <img src="placeholder.png" /> } ``` ## Testing Angular provides TestBed APIs to simplify the process of testing `@defer` blocks and triggering different states during testing. By default, `@defer` blocks in tests will play through like a defer block would behave in a real application. If you want to manually step through states, you can switch the defer block behavior to `Manual` in the TestBed configuration. ```typescript it('should render a defer block in different states', async () => { // configures the defer block behavior to start in "paused" state for manual control. TestBed.configureTestingModule({deferBlockBehavior: DeferBlockBehavior.Manual}); @Component({ // ... template: ` @defer { <large-component /> } @placeholder { Placeholder } @loading { Loading... } ` }) class ComponentA {} // Create component fixture. const componentFixture = TestBed.createComponent(ComponentA); // Retrieve the list of all defer block fixtures and get the first block. const deferBlockFixture = (await componentFixture.getDeferBlocks())[0]; // Renders placeholder state by default. expect(componentFixture.nativeElement.innerHTML).toContain('Placeholder'); // Render loading state and verify rendered output. await deferBlockFixture.render(DeferBlockState.Loading); expect(componentFixture.nativeElement.innerHTML).toContain('Loading'); // Render final state and verify the output. await deferBlockFixture.render(DeferBlockState.Complete); expect(componentFixture.nativeElement.innerHTML).toContain('large works!'); }); ``` ## Behavior with Server-side rendering (SSR) and Static site generation (SSG) When rendering an application on the server (either using SSR or SSG), defer blocks always render their `@placeholder` (or nothing if a placeholder is not specified). Triggers are ignored on the server. ## Behavior with `NgModule` `@defer` blocks can be used in both standalone and NgModule-based components, directives and pipes. You can use standalone and NgModule-based dependencies inside of a `@defer` block, however **only standalone components, directives, and pipes can be deferred**. The NgModule-based dependencies would be included into the eagerly loaded bundle. ## Nested `@defer` blocks and avoiding cascading loads There are cases where nesting multiple `@defer` blocks may cause cascading requests. An example of this would be when a `@defer` block with an immediate trigger has a nested `@defer` block with another immediate trigger. When you have nested `@defer` blocks, make sure that an inner one has a different set of conditions, so that they don't trigger at the same time, causing cascading requests. ## Avoiding Layout Shifts It is a recommended best practice to not defer components that will be visible in the user's viewport on initial load. This will negatively affect Core Web Vitals by causing an increase in cumulative layout shift (CLS). If you choose to defer components in this area, it's best to avoid `immediate`, `timer`, `viewport`, and custom `when` conditions that would cause the content to be loaded during the initial render of the page.
004517
# Hydration ## What is hydration Hydration is the process that restores the server-side rendered application on the client. This includes things like reusing the server rendered DOM structures, persisting the application state, transferring application data that was retrieved already by the server, and other processes. ## Why is hydration important? Hydration improves application performance by avoiding extra work to re-create DOM nodes. Instead, Angular tries to match existing DOM elements to the applications structure at runtime and reuses DOM nodes when possible. This results in a performance improvement that can be measured using [Core Web Vitals (CWV)](https://web.dev/learn-core-web-vitals/) statistics, such as reducing the First Input Delay ([FID](https://web.dev/fid/)) and Largest Contentful Paint ([LCP](https://web.dev/lcp/)), as well as Cumulative Layout Shift ([CLS](https://web.dev/cls/)). Improving these numbers also affects things like SEO performance. Without hydration enabled, server-side rendered Angular applications will destroy and re-render the application's DOM, which may result in a visible UI flicker. This re-rendering can negatively impact [Core Web Vitals](https://web.dev/learn-core-web-vitals/) like [LCP](https://web.dev/lcp/) and cause a layout shift. Enabling hydration allows the existing DOM to be re-used and prevents a flicker. ## How do you enable hydration in Angular Hydration can be enabled for server-side rendered (SSR) applications only. Follow the [Angular SSR Guide](guide/ssr) to enable server-side rendering first. ### Using Angular CLI If you've used Angular CLI to enable SSR (either by enabling it during application creation or later via `ng add @angular/ssr`), the code that enables hydration should already be included into your application. ### Manual setup If you have a custom setup and didn't use Angular CLI to enable SSR, you can enable hydration manually by visiting your main application component or module and importing `provideClientHydration` from `@angular/platform-browser`. You'll then add that provider to your app's bootstrapping providers list. ```typescript import { bootstrapApplication, provideClientHydration, } from '@angular/platform-browser'; ... bootstrapApplication(AppComponent, { providers: [provideClientHydration()] }); ``` Alternatively if you are using NgModules, you would add `provideClientHydration` to your root app module's provider list. ```typescript import {provideClientHydration} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; @NgModule({ declarations: [AppComponent], exports: [AppComponent], bootstrap: [AppComponent], providers: [provideClientHydration()], }) export class AppModule {} ``` IMPORTANT: Make sure that the `provideClientHydration()` call is also included into a set of providers that is used to bootstrap an application on the **server**. In applications with the default project structure (generated by the `ng new` command), adding a call to the root `AppModule` should be sufficient, since this module is imported by the server module. If you use a custom setup, add the `provideClientHydration()` call to the providers list in the server bootstrap configuration. ### Verify that hydration is enabled After you've configured hydration and have started up your server, load your application in the browser. HELPFUL: You will likely need to fix instances of Direct DOM Manipulation before hydration will fully work either by switching to Angular constructs or by using `ngSkipHydration`. See [Constraints](#constraints), [Direct DOM Manipulation](#direct-dom-manipulation), and [How to skip hydration for particular components](#how-to-skip-hydration-for-particular-components) for more details. While running an application in dev mode, you can confirm hydration is enabled by opening the Developer Tools in your browser and viewing the console. You should see a message that includes hydration-related stats, such as the number of components and nodes hydrated. Angular calculates the stats based on all components rendered on a page, including those that come from third-party libraries. You can also use [Angular DevTools browser extension](tools/devtools) to see hydration status of components on a page. Angular DevTools also allows to enable an overlay to indicate which parts of the page were hydrated. If there is a hydration mismatch error - DevTools would also highlight a component that caused the error. ## Capturing and replaying events When an application is rendered on the server, it is visible in a browser as soon as produced HTML loads. Users may assume that they can interact with the page, but event listeners are not attached until hydration completes. Starting from v18, you can enable the Event Replay feature that allows to capture all events that happen before hydration and replay those events once hydration has completed. You can enable it using the `withEventReplay()` function, for example: ```typescript import {provideClientHydration, withEventReplay} from '@angular/platform-browser'; bootstrapApplication(App, { providers: [ provideClientHydration(withEventReplay()) ] }); ``` ## Constraints Hydration imposes a few constraints on your application that are not present without hydration enabled. Your application must have the same generated DOM structure on both the server and the client. The process of hydration expects the DOM tree to have the same structure in both places. This also includes whitespaces and comment nodes that Angular produces during the rendering on the server. Those whitespaces and nodes must be present in the HTML generated by the server-side rendering process. IMPORTANT: The HTML produced by the server side rendering operation **must not** be altered between the server and the client. If there is a mismatch between server and client DOM tree structures, the hydration process will encounter problems attempting to match up what was expected to what is actually present in the DOM. Components that do direct DOM manipulation using native DOM APIs are the most common culprit. ### Direct DOM Manipulation If you have components that manipulate the DOM using native DOM APIs or use `innerHTML` or `outerHTML`, the hydration process will encounter errors. Specific cases where DOM manipulation is a problem are situations like accessing the `document`, querying for specific elements, and injecting additional nodes using `appendChild`. Detaching DOM nodes and moving them to other locations will also result in errors. This is because Angular is unaware of these DOM changes and cannot resolve them during the hydration process. Angular will expect a certain structure, but it will encounter a different structure when attempting to hydrate. This mismatch will result in hydration failure and throw a DOM mismatch error ([see below](#errors)). It is best to refactor your component to avoid this sort of DOM manipulation. Try to use Angular APIs to do this work, if you can. If you cannot refactor this behavior, use the `ngSkipHydration` attribute ([described below](#how-to-skip-hydration-for-particular-components)) until you can refactor into a hydration friendly solution. ### Valid HTML structure There are a few cases where if you have a component template that does not have valid HTML structure, this could result in a DOM mismatch error during hydration. As an example, here are some of the most common cases of this issue. * `<table>` without a `<tbody>` * `<div>` inside a `<p>` * `<a>` inside an `<h1>` * `<a>` inside another `<a>` If you are uncertain about whether your HTML is valid, you can use a [syntax validator](https://validator.w3.org/) to check it. ### Preserve Whitespaces Configuration When using the hydration feature, we recommend using the default setting of `false` for `preserveWhitespaces`. If this setting is not in your tsconfig, the value will be `false` and no changes are required. If you choose to enable preserving whitespaces by adding `preserveWhitespaces: true` to your tsconfig, it is possible you may encounter issues with hydration. This is not yet a fully supported configuration. HELPFUL: Make sure that this setting is set **consistently** in `tsconfig.server.json` for your server and `tsconfig.app.json` for your browser builds. A mismatched value will cause hydration to break. If you choose to set this setting in your tsconfig, we recommend to set it only in `tsconfig.app.json` which by default the `tsconfig.server.json` will inherit it from. ### Custom or Noop Zone.js are not yet supported Hydration relies on a signal from Zone.js when it becomes stable inside an application, so that Angular can start the serialization process on the server or post-hydration cleanup on the client to remove DOM nodes that remained unclaimed. Providing a custom or a "noop" Zone.js implementation may lead to a different timing of the "stable" event, thus triggering the serialization or the cleanup too early or too late. This is not yet a fully supported configuration and you may need to adjust the timing of the `onStable` event in the custom Zone.js implementation.
004519
# Prerendering (SSG) Prerendering, commonly referred to as Static Site Generation (SSG), represents the method by which pages are rendered to static HTML files during the build process. Prerendering maintains the same performance benefits of [server-side rendering (SSR)](guide/ssr#why-use-server-side-rendering) but achieves a reduced Time to First Byte (TTFB), ultimately enhancing user experience. The key distinction lies in its approach that pages are served as static content, and there is no request-based rendering. When the data necessary for server-side rendering remains consistent across all users, the strategy of prerendering emerges as a valuable alternative. Rather than dynamically rendering pages for each user request, prerendering takes a proactive approach by rendering them in advance. ## How to prerender a page To prerender a static page, add SSR capabilities to your application with the following Angular CLI command: <docs-code language="shell"> ng add @angular/ssr </docs-code> <div class="alert is-helpful"> To create an application with prerendering capabilities from the beginning use the [`ng new --ssr`](tools/cli/setup-local) command. </div> Once SSR is added, you can generate the static pages by running the build command: <docs-code language="shell"> ng build </docs-code> ### Build options for prerender The application builder `prerender` option can be either a Boolean or an Object for more fine-tuned configuration. When the option is `false`, no prerendering is done. When it is `true`, all options use the default value. When it is an Object, each option can be individually configured. | Options | Details | Default Value | | :--------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------ | | `discoverRoutes` | Whether the builder should process the Angular Router configuration to find all unparameterized routes and prerender them. | `true` | | `routesFile` | The path to a file that contains a list of all routes to prerender, separated by newlines. This option is useful if you want to prerender routes with parameterized URLs. | | <docs-code language="json"> { "projects": { "my-app": { "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "prerender": { "discoverRoutes": false } } } } } } } </docs-code> ### Prerendering parameterized routes You can prerender parameterized routes using the `routesFile` option. An example of a parameterized route is `product/:id`, where `id` is dynamically provided. To specify these routes, they should be listed in a text file, with each route on a separate line. For an app with a large number of parameterized routes, consider generating this file using a script before running `ng build`. <docs-code header="routes.txt" language="text"> /products/1 /products/555 </docs-code> With routes specified in the `routes.txt` file, use the `routesFile` option to configure the builder to prerender the product routes. <docs-code language="json"> { "projects": { "my-app": { "architect": { "build": { "builder": "@angular-devkit/build-angular:application", "options": { "prerender": { "routesFile": "routes.txt" } } } } } } } </docs-code> This configures `ng build` to prerender `/products/1` and `/products/555` at build time.
004520
# Getting started with NgOptimizedImage The `NgOptimizedImage` directive makes it easy to adopt performance best practices for loading images. The directive ensures that the loading of the [Largest Contentful Paint (LCP)](http://web.dev/lcp) image is prioritized by: * Automatically setting the `fetchpriority` attribute on the `<img>` tag * Lazy loading other images by default * Automatically generating a preconnect link tag in the document head * Automatically generating a `srcset` attribute * Generating a [preload hint](https://developer.mozilla.org/docs/Web/HTML/Link_types/preload) if app is using SSR In addition to optimizing the loading of the LCP image, `NgOptimizedImage` enforces a number of image best practices, such as: * Using [image CDN URLs to apply image optimizations](https://web.dev/image-cdns/#how-image-cdns-use-urls-to-indicate-optimization-options) * Preventing layout shift by requiring `width` and `height` * Warning if `width` or `height` have been set incorrectly * Warning if the image will be visually distorted when rendered If you're using a background image in CSS, [start here](#how-to-migrate-your-background-image). **Note: Although the `NgOptimizedImage` directive was made a stable feature in Angular version 15, it has been backported and is available as a stable feature in versions 13.4.0 and 14.3.0 as well.** ## Getting Started <docs-workflow> <docs-step title="Import `NgOptimizedImage` directive"> Import `NgOptimizedImage` directive from `@angular/common`: <docs-code language="typescript"> import { NgOptimizedImage } from '@angular/common' </docs-code> and include it into the `imports` array of a standalone component or an NgModule: <docs-code language="typescript"> imports: [ NgOptimizedImage, // ... ], </docs-code> </docs-step> <docs-step title="(Optional) Set up a Loader"> An image loader is not **required** in order to use NgOptimizedImage, but using one with an image CDN enables powerful performance features, including automatic `srcset`s for your images. A brief guide for setting up a loader can be found in the [Configuring an Image Loader](#configuring-an-image-loader-for-ngoptimizedimage) section at the end of this page. </docs-step> <docs-step title="Enable the directive"> To activate the `NgOptimizedImage` directive, replace your image's `src` attribute with `ngSrc`. <docs-code language="angular-html"> <img ngSrc="cat.jpg"> </docs-code> If you're using a [built-in third-party loader](#built-in-loaders), make sure to omit the base URL path from `src`, as that will be prepended automatically by the loader. </docs-step> <docs-step title="Mark images as `priority`"> Always mark the [LCP image](https://web.dev/lcp/#what-elements-are-considered) on your page as `priority` to prioritize its loading. <docs-code language="angular-html"> <img ngSrc="cat.jpg" width="400" height="200" priority> </docs-code> Marking an image as `priority` applies the following optimizations: * Sets `fetchpriority=high` (read more about priority hints [here](https://web.dev/priority-hints)) * Sets `loading=eager` (read more about native lazy loading [here](https://web.dev/browser-level-image-lazy-loading)) * Automatically generates a [preload link element](https://developer.mozilla.org/docs/Web/HTML/Link_types/preload) if [rendering on the server](guide/ssr). Angular displays a warning during development if the LCP element is an image that does not have the `priority` attribute. A page’s LCP element can vary based on a number of factors - such as the dimensions of a user's screen, so a page may have multiple images that should be marked `priority`. See [CSS for Web Vitals](https://web.dev/css-web-vitals/#images-and-largest-contentful-paint-lcp) for more details. </docs-step> <docs-step title="Include Width and Height"> In order to prevent [image-related layout shifts](https://web.dev/css-web-vitals/#images-and-layout-shifts), NgOptimizedImage requires that you specify a height and width for your image, as follows: <docs-code language="angular-html"> <img ngSrc="cat.jpg" width="400" height="200"> </docs-code> For **responsive images** (images which you've styled to grow and shrink relative to the viewport), the `width` and `height` attributes should be the intrinsic size of the image file. For responsive images it's also important to [set a value for `sizes`.](#responsive-images) For **fixed size images**, the `width` and `height` attributes should reflect the desired rendered size of the image. The aspect ratio of these attributes should always match the intrinsic aspect ratio of the image. Note: If you don't know the size of your images, consider using "fill mode" to inherit the size of the parent container, as described below. </docs-step> </docs-workflow> ## Using `fill` mode In cases where you want to have an image fill a containing element, you can use the `fill` attribute. This is often useful when you want to achieve a "background image" behavior. It can also be helpful when you don't know the exact width and height of your image, but you do have a parent container with a known size that you'd like to fit your image into (see "object-fit" below). When you add the `fill` attribute to your image, you do not need and should not include a `width` and `height`, as in this example: <docs-code language="angular-html"> <img ngSrc="cat.jpg" fill> </docs-code> You can use the [object-fit](https://developer.mozilla.org/docs/Web/CSS/object-fit) CSS property to change how the image will fill its container. If you style your image with `object-fit: "contain"`, the image will maintain its aspect ratio and be "letterboxed" to fit the element. If you set `object-fit: "cover"`, the element will retain its aspect ratio, fully fill the element, and some content may be "cropped" off. See visual examples of the above at the [MDN object-fit documentation.](https://developer.mozilla.org/docs/Web/CSS/object-fit) You can also style your image with the [object-position property](https://developer.mozilla.org/docs/Web/CSS/object-position) to adjust its position within its containing element. IMPORTANT: For the "fill" image to render properly, its parent element **must** be styled with `position: "relative"`, `position: "fixed"`, or `position: "absolute"`. ## How to migrate your background image Here's a simple step-by-step process for migrating from `background-image` to `NgOptimizedImage`. For these steps, we'll refer to the element that has an image background as the "containing element": 1) Remove the `background-image` style from the containing element. 2) Ensure that the containing element has `position: "relative"`, `position: "fixed"`, or `position: "absolute"`. 3) Create a new image element as a child of the containing element, using `ngSrc` to enable the `NgOptimizedImage` directive. 4) Give that element the `fill` attribute. Do not include a `height` and `width`. 5) If you believe this image might be your [LCP element](https://web.dev/lcp/), add the `priority` attribute to the image element. You can adjust how the background image fills the container as described in the [Using fill mode](#using-fill-mode) section. ## U
004524
# Server-side rendering Server-side rendering (SSR) is a process that involves rendering pages on the server, resulting in initial HTML content which contains initial page state. Once the HTML content is delivered to a browser, Angular initializes the application and utilizes the data contained within the HTML. ## Why use SSR? The main advantages of SSR as compared to client-side rendering (CSR) are: - **Improved performance**: SSR can improve the performance of web applications by delivering fully rendered HTML to the client, which the browser can parse and display even before it downloads the application JavaScript. This can be especially beneficial for users on low-bandwidth connections or mobile devices. - **Improved Core Web Vitals**: SSR results in performance improvements that can be measured using [Core Web Vitals (CWV)](https://web.dev/learn-core-web-vitals/) statistics, such as reduced First Contentful Paint ([FCP](https://developer.chrome.com/en/docs/lighthouse/performance/first-contentful-paint/)) and Largest Contentful Paint ([LCP](https://web.dev/lcp/)), as well as Cumulative Layout Shift ([CLS](https://web.dev/cls/)). - **Better SEO**: SSR can improve the search engine optimization (SEO) of web applications by making it easier for search engines to crawl and index the content of the application. ## Enable server-side rendering To create a **new** project with SSR, run: <docs-code language="shell"> ng new --ssr </docs-code> To add SSR to an **existing** project, use the Angular CLI `ng add` command. <docs-code language="shell"> ng add @angular/ssr </docs-code> These commands create and update application code to enable SSR and adds extra files to the project structure. <docs-code language="text"> my-app |-- server.ts # application server └── src |-- app | └── app.config.server.ts # server application configuration └── main.server.ts # main server application bootstrapping </docs-code> To verify that the application is server-side rendered, run it locally with `ng serve`. The initial HTML request should contain application content. ## Configure server-side rendering Note: In Angular v17 and later, `server.ts` is no longer used by `ng serve`. The dev server will use `main.server.ts` directly to perfom server side rendering. The `server.ts` file configures a Node.js Express server and Angular server-side rendering. `CommonEngine` is used to render an Angular application. <docs-code path="adev/src/content/examples/ssr/server.ts" visibleLines="[31,45]"></docs-code> The `render` method of `CommonEngine` accepts an object with the following properties: | Properties | Details | Default Value | | ------------------- | ---------------------------------------------------------------------------------------- | ------------- | | `bootstrap` | A method which returns an `NgModule` or a promise which resolves to an `ApplicationRef`. | | | `providers` | An array of platform level providers for the current request. | | | `url` | The url of the page to render. | | | `inlineCriticalCss` | Whether to reduce render blocking requests by inlining critical CSS. | `true` | | `publicPath` | Base path for browser files and assets. | | | `document` | The initial DOM to use for bootstrapping the server application. | | | `documentFilePath` | File path of the initial DOM to use to bootstrap the server application. | | Angular CLI will scaffold an initial server implementation focused on server-side rendering your Angular application. This server can be extended to support other features such as API routes, redirects, static assets, and more. See [Express documentation](https://expressjs.com/) for more details. ## Hydration Hydration is the process that restores the server side rendered application on the client. This includes things like reusing the server rendered DOM structures, persisting the application state, transferring application data that was retrieved already by the server, and other processes. Hydration is enabled by default when you use SSR. You can find more info in [the hydration guide](guide/hydration). ## Caching data when using HttpClient [`HttpClient`](api/common/http/HttpClient) cached outgoing network requests when running on the server. This information is serialized and transferred to the browser as part of the initial HTML sent from the server. In the browser, `HttpClient` checks whether it has data in the cache and if so, reuses it instead of making a new HTTP request during initial application rendering. `HttpClient` stops using the cache once an application becomes [stable](api/core/ApplicationRef#isStable) while running in a browser. By default, `HttpClient` caches all `HEAD` and `GET` requests which don't contain `Authorization` or `Proxy-Authorization` headers. You can override those settings by using [`withHttpTransferCacheOptions`](api/platform-browser/withHttpTransferCacheOptions) when providing hydration. <docs-code language="typescript"> bootstrapApplication(AppComponent, { providers: [ provideClientHydration(withHttpTransferCacheOptions({ includePostRequests: true })) ] }); </docs-code> ## Authoring server-compatible components Some common browser APIs and capabilities might not be available on the server. Applications cannot make use of browser-specific global objects like `window`, `document`, `navigator`, or `location` as well as certain properties of `HTMLElement`. In general, code which relies on browser-specific symbols should only be executed in the browser, not on the server. This can be enforced through the [`afterRender`](api/core/afterRender) and [`afterNextRender`](api/core/afterNextRender) lifecycle hooks. These are only executed on the browser and skipped on the server. <docs-code language="typescript"> import { Component, ViewChild, afterNextRender } from '@angular/core'; @Component({ selector: 'my-cmp', template: `<span #content>{{ ... }}</span>`, }) export class MyComponent { @ViewChild('content') contentRef: ElementRef; constructor() { afterNextRender(() => { // Safe to check `scrollHeight` because this will only run in the browser, not the server. console.log('content height: ' + this.contentRef.nativeElement.scrollHeight); }); } } </docs-code> ## Using Angular Service Worker If you are using Angular on the server in combination with the Angular service worker, the behavior deviates from the normal server-side rendering behavior. The initial server request will be rendered on the server as expected. However, after that initial request, subsequent requests are handled by the service worker and always client-side rendered.
004532
# Angular without ZoneJS (Zoneless) ## Why use Zoneless? The main advantages to removing ZoneJS as a dependency are: - **Improved performance**: ZoneJS uses DOM events and async tasks as indicators of when application state _might_ have updated and subsequently triggers application synchronization to run change detection on the application's views. ZoneJS does not have any insight into whether application state actually changed and so this synchronization is triggered more frequently than necessary. - **Improved Core Web Vitals**: ZoneJS brings a fair amount of overhead, both in payload size and in startup time cost. - **Improved debugging experience**: ZoneJS makes debugging code more difficult. Stack traces are harder to understand with ZoneJS. It's also difficult to understand when code breaks as a result of being outside the Angular Zone. - **Better ecosystem compatibility**: ZoneJS works by patching browser APIs but does not automatically have patches for every new browser API. Some APIs simply cannot be patched effectively, such as `async`/`await`, and have to be downleveled to work with ZoneJS. Sometimes libraries in the ecosystem are also incompatible with the way ZoneJS patches the native APIs. Removing ZoneJS as a dependency ensures better long-term compatibility by removing a source of complexity, monkey patching, and ongoing maintenance. ## Enabling Zoneless in an application The API for enabling Zoneless is currently experimental. Neither the shape, nor the underlying behavior is stable and can change in patch versions. There are known feature gaps, including the lack of an ergonomic API which prevents the application from serializing too early with Server Side Rendering. ```typescript // standalone bootstrap bootstrapApplication(MyApp, {providers: [ provideExperimentalZonelessChangeDetection(), ]}); // NgModule bootstrap platformBrowser().bootstrapModule(AppModule); @NgModule({ providers: [provideExperimentalZonelessChangeDetection()] }) export class AppModule {} ``` ## Removing ZoneJS Zoneless applications should remove ZoneJS entirely from the build to reduce bundle size. ZoneJS is typically loaded via the `polyfills` option in `angular.json`, both in the `build` and `test` targets. Remove `zone.js` and `zone.js/testing` from both to remove it from the build. Projects which use an explicit `polyfills.ts` file should remove `import 'zone.js';` and `import 'zone.js/testing';` from the file. After removing ZoneJS from the build, there is no longer a need for a `zone.js` dependency either and the package can be removed entirely: ```shell npm uninstall zone.js ``` ## Requirements for Zoneless compatibility Angular relies on notifications from core APIs in order to determine when to run change detection and on which views. These notifications include: - `ChangeDetectorRef.markForCheck` (called automatically by `AsyncPipe`) - `ComponentRef.setInput` - Updating a signal that's read in a template - Bound host or template listeners callbacks - Attaching a view that was marked dirty by one of the above ### `OnPush`-compatible components One way to ensure that a component is using the correct notification mechanisms from above is to use [ChangeDetectionStrategy.OnPush](/best-practices/skipping-subtrees#using-onpush). The `OnPush` change detection strategy is not required, but it is a recommended step towards zoneless compatibility for application components. It is not always possible for library components to use `ChangeDetectionStrategy.OnPush`. When a library component is a host for user-components which might use `ChangeDetectionStrategy.Default`, it cannot use `OnPush` because that would prevent the child component from being refreshed if it is not `OnPush` compatible and relies on ZoneJS to trigger change detection. Components can use the `Default` strategy as long as they notify Angular when change detection needs to run (calling `markForCheck`, using signals, `AsyncPipe`, etc.). ### Remove `NgZone.onMicrotaskEmpty`, `NgZone.onUnstable`, `NgZone.isStable`, or `NgZone.onStable` Applications and libraries need to remove uses of `NgZone.onMicrotaskEmpty`, `NgZone.onUnstable` and `NgZone.onStable`. These observables will never emit when an Application enables zoneless change detection. Similarly, `NgZone.isStable` will always be `true` and should not be used as a condition for code execution. The `NgZone.onMicrotaskEmpty` and `NgZone.onStable` observables are most often used to wait for Angular to complete change detection before performing a task. Instead, these can be replaced by `afterNextRender` if they need to wait for a single change detection or `afterRender` if there is some condition that might span several change detection rounds. In other cases, these observables were used because they happened to be familiar and have similar timing to what was needed. More straightforward or direct DOM APIs can be used instead, such as `MutationObserver` when code needs to wait for certain DOM state (rather than waiting for it indirectly through Angular's render hooks). <docs-callout title="NgZone.run and NgZone.runOutsideAngular are compatible with Zoneless"> `NgZone.run` and `NgZone.runOutsideAngular` do not need to be removed in order for code to be compatible with Zoneless applications. In fact, removing these calls can lead to performance regressions for libraries that are used in applications that still rely on ZoneJS. </docs-callout> ### `PendingTasks` for Server Side Rendering (SSR) If you are using SSR with Angular, you may know that it relies on ZoneJS to help determine when the application is "stable" and can be serialized. If there are asynchronous tasks that should prevent serialization, an application not using ZoneJS will need to make Angular aware of these with the `PendingTasks` service. Serialization will wait for the first moment that all pending tasks have been removed. ```typescript const taskService = inject(PendingTasks); const taskCleanup = taskService.add(); await doSomeWorkThatNeedsToBeRendered(); taskCleanup(); ``` The framework uses this service internally as well to prevent serialization until asynchronous tasks are complete. These include, but are not limited to, an ongoing Router navigation and an incomplete `HttpClient` request. ## Testing and Debugging ### Using Zoneless in `TestBed` The zoneless provider function can also be used with `TestBed` to help ensure the components under test are compatible with a Zoneless Angular application. ```typescript TestBed.configureTestingModule({ providers: [provideExperimentalZonelessChangeDetection()] }); const fixture = TestBed.createComponent(MyComponent); await fixture.whenStable(); ``` To ensure tests have the most similar behavior to production code, avoid using `fixture.detectChanges()` when possible. This forces change detection to run when Angular might otherwise have not scheduled change detection. Tests should ensure these notifications are happening and allow Angular to handle when to synchronize state rather than manually forcing it to happen in the test. ### Debug-mode check to ensure updates are detected Angular also provides an additional tool to help verify that an application is making updates to state in a zoneless-compatible way. `provideExperimentalCheckNoChangesForDebug` can be used to periodically check to ensure that no bindings have been updated without a notification. Angular will throw `ExpressionChangedAfterItHasBeenCheckedError` if there is an updated binding that would not have refreshed by the zoneless change detection.
004534
<docs-decorative-header title="Built-in directives" imgSrc="adev/src/assets/images/directives.svg"> <!-- markdownlint-disable-line --> Directives are classes that add additional behavior to elements in your Angular applications. </docs-decorative-header> Use Angular's built-in directives to manage forms, lists, styles, and what users see. The different types of Angular directives are as follows: | Directive Types | Details | | :------------------------------------------------------- | :-------------------------------------------------------------------------------- | | [Components](guide/components) | Used with a template. This type of directive is the most common directive type. | | [Attribute directives](#built-in-attribute-directives) | Change the appearance or behavior of an element, component, or another directive. | | [Structural directives](#built-in-structural-directives) | Change the DOM layout by adding and removing DOM elements. | This guide covers built-in [attribute directives](#built-in-attribute-directives) and [structural directives](#built-in-structural-directives). ## Built-in attribute directives Attribute directives listen to and modify the behavior of other HTML elements, attributes, properties, and components. The most common attribute directives are as follows: | Common directives | Details | | :------------------------------------------------------------ | :------------------------------------------------- | | [`NgClass`](#adding-and-removing-classes-with-ngclass) | Adds and removes a set of CSS classes. | | [`NgStyle`](#setting-inline-styles-with-ngstyle) | Adds and removes a set of HTML styles. | | [`NgModel`](#displaying-and-updating-properties-with-ngmodel) | Adds two-way data binding to an HTML form element. | HELPFUL: Built-in directives use only public APIs. They do not have special access to any private APIs that other directives can't access. ## Adding and removing classes with `NgClass` Add or remove multiple CSS classes simultaneously with `ngClass`. HELPFUL: To add or remove a _single_ class, use [class binding](guide/templates/class-binding) rather than `NgClass`. ### Import `NgClass` in the component To use `NgClass`, add it to the component's `imports` list. <docs-code header="src/app/app.component.ts (NgClass import)" path="adev/src/content/examples/built-in-directives/src/app/app.component.ts" visibleRegion="import-ng-class"/> ### Using `NgClass` with an expression On the element you'd like to style, add `[ngClass]` and set it equal to an expression. In this case, `isSpecial` is a boolean set to `true` in `app.component.ts`. Because `isSpecial` is true, `ngClass` applies the class of `special` to the `<div>`. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="special-div"/> ### Using `NgClass` with a method 1. To use `NgClass` with a method, add the method to the component class. In the following example, `setCurrentClasses()` sets the property `currentClasses` with an object that adds or removes three classes based on the `true` or `false` state of three other component properties. Each key of the object is a CSS class name. If a key is `true`, `ngClass` adds the class. If a key is `false`, `ngClass` removes the class. <docs-code header="src/app/app.component.ts" path="adev/src/content/examples/built-in-directives/src/app/app.component.ts" visibleRegion="setClasses"/> 1. In the template, add the `ngClass` property binding to `currentClasses` to set the element's classes: <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgClass-1"/> For this use case, Angular applies the classes on initialization and in case of changes caused by reassigning the `currentClasses` object. The full example calls `setCurrentClasses()` initially with `ngOnInit()` when the user clicks on the `Refresh currentClasses` button. These steps are not necessary to implement `ngClass`. ## Setting inline styles with `NgStyle` ### Import `NgStyle` in the component To use `NgStyle`, add it to the component's `imports` list. <docs-code header="src/app/app.component.ts (NgStyle import)" path="adev/src/content/examples/built-in-directives/src/app/app.component.ts" visibleRegion="import-ng-style"/> Use `NgStyle` to set multiple inline styles simultaneously, based on the state of the component. 1. To use `NgStyle`, add a method to the component class. In the following example, `setCurrentStyles()` sets the property `currentStyles` with an object that defines three styles, based on the state of three other component properties. <docs-code header="src/app/app.component.ts" path="adev/src/content/examples/built-in-directives/src/app/app.component.ts" visibleRegion="setStyles"/> 1. To set the element's styles, add an `ngStyle` property binding to `currentStyles`. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgStyle-2"/> For this use case, Angular applies the styles upon initialization and in case of changes. To do this, the full example calls `setCurrentStyles()` initially with `ngOnInit()` and when the dependent properties change through a button click. However, these steps are not necessary to implement `ngStyle` on its own. ## Displaying and updating properties with `ngModel` Use the `NgModel` directive to display a data property and update that property when the user makes changes. 1. Import `FormsModule` and add it to the AppComponent's `imports` list. <docs-code header="src/app/app.component.ts (FormsModule import)" path="adev/src/content/examples/built-in-directives/src/app/app.component.ts" visibleRegion="import-forms-module" /> 1. Add an `[(ngModel)]` binding on an HTML `<form>` element and set it equal to the property, here `name`. <docs-code header="src/app/app.component.html (NgModel example)" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgModel-1"/> This `[(ngModel)]` syntax can only set a data-bound property. To customize your configuration, write the expanded form, which separates the property and event binding. Use [property binding](guide/templates/property-binding) to set the property and [event binding](guide/templates/event-listeners) to respond to changes. The following example changes the `<input>` value to uppercase: <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="uppercase"/> Here are all variations in action, including the uppercase version: <img alt="NgModel variations" src="assets/images/guide/built-in-directives/ng-model-anim.gif"> ### `NgModel` and value accessors The `NgModel` directive works for an element supported by a [ControlValueAccessor](api/forms/ControlValueAccessor). Angular provides _value accessors_ for all of the basic HTML form elements. For more information, see [Forms](guide/forms). To apply `[(ngModel)]` to a non-form built-in element or a third-party custom component, you have to write a value accessor. For more information, see the API documentation on [DefaultValueAccessor](api/forms/DefaultValueAccessor). HELPFUL: When you write an Angular component, you don't need a value accessor or `NgModel` if you name the value and event properties according to Angular's [two-way binding syntax](guide/templates/two-way-binding#how-two-way-binding-works). ## Built-in structural directives Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, and manipulating the host elements to which they are attached. This section introduces the most common built-in structural directives: | Common built-in structural directives | Details | | :------------------------------------------------- | :--------------------------------------------------------------- | | [`NgIf`](#adding-or-removing-an-element-with-ngif) | Conditionally creates or disposes of subviews from the template. | | [`NgFor`](#listing-items-with-ngfor) | Repeat a node for each item in a list. | | [`NgSwitch`](#switching-cases-with-ngswitch) | A set of directives that switch among alternative views. | For more information, see [Structural Directives](guide/directives/structural-directives).
004535
## Adding or removing an element with `NgIf` Add or remove an element by applying an `NgIf` directive to a host element. When `NgIf` is `false`, Angular removes an element and its descendants from the DOM. Angular then disposes of their components, which frees up memory and resources. ### Import `NgIf` in the component To use `NgIf`, add it to the component's `imports` list. <docs-code header="src/app/app.component.ts (NgIf import)" path="adev/src/content/examples/built-in-directives/src/app/app.component.ts" visibleRegion="import-ng-if"/> ### Using `NgIf` To add or remove an element, bind `*ngIf` to a condition expression such as `isActive` in the following example. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgIf-1"/> When the `isActive` expression returns a truthy value, `NgIf` adds the `ItemDetailComponent` to the DOM. When the expression is falsy, `NgIf` removes the `ItemDetailComponent` from the DOM and disposes of the component and all of its subcomponents. For more information on `NgIf` and `NgIfElse`, see the [NgIf API documentation](api/common/NgIf). ### Guarding against `null` By default, `NgIf` prevents display of an element bound to a null value. To use `NgIf` to guard a `<div>`, add `*ngIf="yourProperty"` to the `<div>`. In the following example, the `currentCustomer` name appears because there is a `currentCustomer`. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgIf-2"/> However, if the property is `null`, Angular does not display the `<div>`. In this example, Angular does not display the `nullCustomer` because it is `null`. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgIf-2b"/> ## Listing items with `NgFor` Use the `NgFor` directive to present a list of items. ### Import `NgFor` in the component To use `NgFor`, add it to the component's `imports` list. <docs-code header="src/app/app.component.ts (NgFor import)" path="adev/src/content/examples/built-in-directives/src/app/app.component.ts" visibleRegion="import-ng-for"/> ### Using `NgFor` To use `NgFor`, you have to: 1. Define a block of HTML that determines how Angular renders a single item. 1. To list your items, assign the shorthand `let item of items` to `*ngFor`. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgFor-1"/> The string `"let item of items"` instructs Angular to do the following: - Store each item in the `items` array in the local `item` looping variable - Make each item available to the templated HTML for each iteration - Translate `"let item of items"` into an `<ng-template>` around the host element - Repeat the `<ng-template>` for each `item` in the list For more information see the [Structural directive shorthand](guide/directives/structural-directives#structural-directive-shorthand) section of [Structural directives](guide/directives/structural-directives). ### Repeating a component view To repeat a component element, apply `*ngFor` to the selector. In the following example, the selector is `<app-item-detail>`. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgFor-2"/> Reference a template input variable, such as `item`, in the following locations: - Within the `ngFor` host element - Within the host element descendants to access the item's properties The following example references `item` first in an interpolation and then passes in a binding to the `item` property of the `<app-item-detail>` component. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgFor-1-2"/> For more information about template input variables, see [Structural directive shorthand](guide/directives/structural-directives#structural-directive-shorthand). ### Getting the `index` of `*ngFor` Get the `index` of `*ngFor` in a template input variable and use it in the template. In the `*ngFor`, add a semicolon and `let i=index` to the shorthand. The following example gets the `index` in a variable named `i` and displays it with the item name. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgFor-3"/> The index property of the `NgFor` directive context returns the zero-based index of the item in each iteration. Angular translates this instruction into an `<ng-template>` around the host element, then uses this template repeatedly to create a new set of elements and bindings for each `item` in the list. For more information about shorthand, see the [Structural Directives](guide/directives/structural-directives#structural-directive-shorthand) guide. ## Repeating elements when a condition is true To repeat a block of HTML when a particular condition is true, put the `*ngIf` on a container element that wraps an `*ngFor` element. For more information see [one structural directive per element](guide/directives/structural-directives#one-structural-directive-per-element). ### Tracking items with `*ngFor` `trackBy` Reduce the number of calls your application makes to the server by tracking changes to an item list. With the `*ngFor` `trackBy` property, Angular can change and re-render only those items that have changed, rather than reloading the entire list of items. 1. Add a method to the component that returns the value `NgFor` should track. In this example, the value to track is the item's `id`. If the browser has already rendered `id`, Angular keeps track of it and doesn't re-query the server for the same `id`. <docs-code header="src/app/app.component.ts" path="adev/src/content/examples/built-in-directives/src/app/app.component.ts" visibleRegion="trackByItems"/> 1. In the shorthand expression, set `trackBy` to the `trackByItems()` method. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="trackBy"/> **Change ids** creates new items with new `item.id`s. In the following illustration of the `trackBy` effect, **Reset items** creates new items with the same `item.id`s. - With no `trackBy`, both buttons trigger complete DOM element replacement. - With `trackBy`, only changing the `id` triggers element replacement. <img alt="Animation of trackBy" src="assets/images/guide/built-in-directives/ngfor-trackby.gif"> ## Hosting a directive without a DOM element The Angular `<ng-container>` is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM. Use `<ng-container>` when there's no single element to host the directive. Here's a conditional paragraph using `<ng-container>`. <docs-code header="src/app/app.component.html (ngif-ngcontainer)" path="adev/src/content/examples/structural-directives/src/app/app.component.html" visibleRegion="ngif-ngcontainer"/> <img alt="ngcontainer paragraph with proper style" src="assets/images/guide/structural-directives/good-paragraph.png"> 1. Import the `ngModel` directive from `FormsModule`. 1. Add `FormsModule` to the imports section of the relevant Angular module. 1. To conditionally exclude an `<option>`, wrap the `<option>` in an `<ng-container>`. <docs-code header="src/app/app.component.html (select-ngcontainer)" path="adev/src/content/examples/structural-directives/src/app/app.component.html" visibleRegion="select-ngcontainer"/> <img alt="ngcontainer options work properly" src="assets/images/guide/structural-directives/select-ngcontainer-anim.gif">
004539
# Structural directives Structural directives are directives applied to an `<ng-template>` element that conditionally or repeatedly render the content of that `<ng-template>`. ## Example use case In this guide you'll build a structural directive which fetches data from a given data source and renders its template when that data is available. This directive is called `SelectDirective`, after the SQL keyword `SELECT`, and match it with an attribute selector `[select]`. `SelectDirective` will have an input naming the data source to be used, which you will call `selectFrom`. The `select` prefix for this input is important for the [shorthand syntax](#structural-directive-shorthand). The directive will instantiate its `<ng-template>` with a template context providing the selected data. The following is an example of using this directive directly on an `<ng-template>` would look like: ```angular-html <ng-template select let-data [selectFrom]="source"> <p>The data is: {{ data }}</p> </ng-template> ``` The structural directive can wait for the data to become available and then render its `<ng-template>`. HELPFUL: Note that Angular's `<ng-template>` element defines a template that doesn't render anything by default, if you just wrap elements in an `<ng-template>` without applying a structural directive those elements will not be rendered. For more information, see the [ng-template API](api/core/ng-template) documentation. ## Structural directive shorthand Angular supports a shorthand syntax for structural directives which avoids the need to explicitly author an `<ng-template>` element. Structural directives can be applied directly on an element by prefixing the directive attribute selector with an asterisk (`*`), such as `*select`. Angular transforms the asterisk in front of a structural directive into an `<ng-template>` that hosts the directive and surrounds the element and its descendants. You can use this with `SelectDirective` as follows: ```angular-html <p *select="let data from source">The data is: {{data}}</p> ``` This example shows the flexibility of structural directive shorthand syntax, which is sometimes called _microsyntax_. When used in this way, only the structural directive and its bindings are applied to the `<ng-template>`. Any other attributes or bindings on the `<p>` tag are left alone. For example, these two forms are equivalent: ```angular-html <!-- Shorthand syntax: --> <p class="data-view" *select="let data from source">The data is: {{data}}</p> <!-- Long-form syntax: --> <ng-template select let-data [selectFrom]="source"> <p class="data-view">The data is: {{data}}</p> </ng-template> ``` Shorthand syntax is expanded through a set of conventions. A more thorough [grammar](#structural-directive-syntax-reference) is defined below, but in the above example, this transformation can be explained as follows: The first part of the `*select` expression is `let data`, which declares a template variable `data`. Since no assignment follows, the template variable is bound to the template context property `$implicit`. The second piece of syntax is a key-expression pair, `from source`. `from` is a binding key and `source` is a regular template expression. Binding keys are mapped to properties by transforming them to PascalCase and prepending the structural directive selector. The `from` key is mapped to `selectFrom`, which is then bound to the expression `source`. This is why many structural directives will have inputs that are all prefixed with the structural directive's selector. ## One structural directive per element You can only apply one structural directive per element when using the shorthand syntax. This is because there is only one `<ng-template>` element onto which that directive gets unwrapped. Multiple directives would require multiple nested `<ng-template>`, and it's unclear which directive should be first. `<ng-container>` can be used when to create wrapper layers when multiple structural directives need to be applied around the same physical DOM element or component, which allows the user to define the nested structure. ## Creating a structural directive This section guides you through creating the `SelectDirective`. <docs-workflow> <docs-step title="Generate the directive"> Using the Angular CLI, run the following command, where `select` is the name of the directive: ```shell ng generate directive select ``` Angular creates the directive class and specifies the CSS selector, `[select]`, that identifies the directive in a template. </docs-step> <docs-step title="Make the directive structural"> Import `TemplateRef`, and `ViewContainerRef`. Inject `TemplateRef` and `ViewContainerRef` in the directive constructor as private variables. ```ts import {Directive, TemplateRef, ViewContainerRef} from '@angular/core'; @Directive({ standalone: true, selector: '[select]', }) export class SelectDirective { constructor(private templateRef: TemplateRef, private ViewContainerRef: ViewContainerRef) {} } ``` </docs-step> <docs-step title="Add the 'selectFrom' input"> Add a `selectFrom` `@Input()` property. ```ts export class SelectDirective { // ... @Input({required: true}) selectFrom!: DataSource; } ``` </docs-step> <docs-step title="Add the business logic"> With `SelectDirective` now scaffolded as a structural directive with its input, you can now add the logic to fetch the data and render the template with it: ```ts export class SelectDirective { // ... async ngOnInit() { const data = await this.selectFrom.load(); this.viewContainerRef.createEmbeddedView(this.templateRef, { // Create the embedded view with a context object that contains // the data via the key `$implicit`. $implicit: data, }); } } ``` </docs-step> </docs-workflow> That's it - `SelectDirective` is up and running. A follow-up step might be to [add template type-checking support](#typing-the-directives-context). ## Structural directive syntax reference When you write your own structural directives, use the following syntax: <docs-code hideCopy language="typescript"> *:prefix="( :let | :expression ) (';' | ',')? ( :let | :as | :keyExp )*" </docs-code> The following patterns describe each portion of the structural directive grammar: ```ts as = :export "as" :local ";"? keyExp = :key ":"? :expression ("as" :local)? ";"? let = "let" :local "=" :export ";"? ``` | Keyword | Details | | :----------- | :------------------------------------------------- | | `prefix` | HTML attribute key | | `key` | HTML attribute key | | `local` | Local variable name used in the template | | `export` | Value exported by the directive under a given name | | `expression` | Standard Angular expression | ### How Angular translates shorthand Angular translates structural directive shorthand into the normal binding syntax as follows: | Shorthand | Translation | |:--- |:--- | | `prefix` and naked `expression` | `[prefix]="expression"` | | `keyExp` | `[prefixKey]="expression"` (The `prefix` is added to the `key`) | | `let local` | `let-local="export"` | ### Shorthand examples The following table provides shorthand examples: | Shorthand | How Angular interprets the syntax | |:--- |:--- | | `*ngFor="let item of [1,2,3]"` | `<ng-template ngFor let-item [ngForOf]="[1, 2, 3]">` | | `*ngFor="let item of [1,2,3] as items; trackBy: myTrack; index as i"` | `<ng-template ngFor let-item [ngForOf]="[1,2,3]" let-items="ngForOf" [ngForTrackBy]="myTrack" let-i="index">` | | `*ngIf="exp"`| `<ng-template [ngIf]="exp">` | | `*ngIf="exp as value"` | `<ng-template [ngIf]="exp" let-value="ngIf">` |
004541
# Singleton services A singleton service is a service for which only one instance exists in an application. ## Providing a singleton service There are two ways to make a service a singleton in Angular: * Set the `providedIn` property of the `@Injectable()` to `"root"` * Include the service in the `AppModule` or in a module that is only imported by the `AppModule` ### Using `providedIn` The preferred way to create a singleton service is to set `providedIn` to `root` on the service's `@Injectable()` decorator. This tells Angular to provide the service in the application root. <docs-code header="src/app/user.service.ts" highlight="[4]"> import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class UserService { } </docs-code> ### NgModule `providers` array In applications built with Angular versions prior to 6.0, services were commonly registered in the `@NgModule` `providers` field as followed: <docs-code language="typescript"> @NgModule({ // ... providers: [UserService], }) </docs-code> If this NgModule were the root `AppModule`, the `UserService` would be a singleton and available throughout the application. Though you may see it coded this way, using the `providedIn` property of the `@Injectable()` decorator on the service itself is preferable as of Angular 6.0 as it makes your services tree-shakable. ## The `forRoot()` pattern Generally, you'll only need `providedIn` for providing services and `forRoot()`/`forChild()` for routing. However, understanding how `forRoot()` works to make sure a service is a singleton will inform your development at a deeper level. If a module defines both providers and declarations (components, directives, pipes), then loading the module in multiple feature modules would duplicate the registration of the service. This could result in multiple service instances and the service would no longer behave as a singleton. There are multiple ways to prevent this: * Use the [`providedIn` syntax](#using-providedin) instead of registering the service in the module. * Separate your services into their own module that is imported once. * Define `forRoot()` and `forChild()` methods in the module. For an introductory explanation see the [Lazy Loading Feature Modules](guide/ngmodules/lazy-loading) guide. Use `forRoot()` to separate providers from a module so you can import that module into the root module with `providers` and child modules without `providers`. 1. Create a static method `forRoot()` on the module. 1. Place the providers into the `forRoot()` method. <docs-code header="src/app/greeting/greeting.module.ts" highlight="[3,6,7]" language="typescript"> @NgModule({...}) export class GreetingModule { static forRoot(config: UserServiceConfig): ModuleWithProviders<GreetingModule> { return { ngModule: GreetingModule, providers: [ {provide: UserServiceConfig, useValue: config } ] }; } } </docs-code> ### `forRoot()` and the `Router` `RouterModule` provides the `Router` service, as well as router directives, such as `RouterOutlet` and `routerLink`. The root application module imports `RouterModule` so that the application has a `Router` and the root application components can access the router directives. Any feature modules must also import `RouterModule` so that their components can place router directives into their templates. If the `RouterModule` didn't have `forRoot()` then each feature module would instantiate a new `Router` instance, which would break the application as there can only be one `Router`. By using the `forRoot()` method, the root application module imports `RouterModule.forRoot(...)` and gets a `Router`, and all feature modules import `RouterModule.forChild(...)` which does not instantiate another `Router`. HELPFUL: If you have a module which has both providers and declarations, you *can* use this technique to separate them out and you may see this pattern in legacy applications. However, since Angular 6.0, the best practice for providing services is with the `@Injectable()` `providedIn` property. ### How `forRoot()` works `forRoot()` takes a service configuration object and returns a [ModuleWithProviders](api/core/ModuleWithProviders), which is a simple object with the following properties: | Properties | Details | |:--- |:--- | | `ngModule` | In this example, the `GreetingModule` class | | `providers` | The configured providers | Specifically, Angular accumulates all imported providers before appending the items listed in `@NgModule.providers`. This sequence ensures that whatever you add explicitly to the `AppModule` providers takes precedence over the providers of imported modules. The sample application imports `GreetingModule` and uses its `forRoot()` method one time, in `AppModule`. Registering it once like this prevents multiple instances. In the following example, the `UserServiceConfig` is optionally injected in the `UserService`. If a config exists, the service sets the user name based on the retrieved config. <docs-code header="src/app/greeting/user.service.ts (constructor)" language="typescript"> constructor(@Optional() config?: UserServiceConfig) { if (config) { this._userName = config.userName; } } </docs-code> Here's `forRoot()` that takes a `UserServiceConfig` object: <docs-code header="src/app/greeting/greeting.module.ts" highlight="[3,6,7]" language="typescript"> @NgModule({...}) export class GreetingModule { static forRoot(config: UserServiceConfig): ModuleWithProviders<GreetingModule> { return { ngModule: GreetingModule, providers: [ {provide: UserServiceConfig, useValue: config } ] }; } } </docs-code> Lastly, call it within the `imports` list of the `AppModule`. In the following snippet, other parts of the file are left out. <docs-code header="src/app/app.module.ts (imports)" language="typescript"> import { GreetingModule } from './greeting/greeting.module'; @NgModule({ // ... imports: [ // ... GreetingModule.forRoot({userName: 'Miss Marple'}), ], }) </docs-code> The application will then display "Miss Marple" as the user. Remember to import `GreetingModule` as a JavaScript import, and don't add usages of `forRoot` to more than one `@NgModule` `imports` list. ## Prevent reimport of the `GreetingModule` Only the root `AppModule` should import the `GreetingModule`. If a lazy-loaded module imports it too, the application can generate [multiple instances](guide/ngmodules/faq#why-is-it-bad-if-a-shared-module-provides-a-service-to-a-lazy-loaded-module?) of a service. To guard against a lazy loaded module re-importing `GreetingModule`, add the following `GreetingModule` constructor. <docs-code header="src/app/greeting/greeting.module.ts" language="typescript"> constructor(@Optional() @SkipSelf() parentModule?: GreetingModule) { if (parentModule) { throw new Error( 'GreetingModule is already loaded. Import it in the AppModule only'); } } </docs-code> The constructor tells Angular to inject the `GreetingModule` into itself. The injection would be circular if Angular looked for `GreetingModule` in the *current* injector, but the `@SkipSelf()` decorator means "look for `GreetingModule` in an ancestor injector, above me in the injector hierarchy". By default, the injector throws an error when it can't find a requested provider. The `@Optional()` decorator means not finding the service is OK. The injector returns `null`, the `parentModule` parameter is null, and the constructor concludes uneventfully. It's a different story if you improperly import `GreetingModule` into a lazy loaded module such as `CustomersModule`. Angular creates a lazy loaded module with its own injector, a child of the root injector. `@SkipSelf()` causes Angular to look for a `GreetingModule` in the parent injector, which this time is the root injector. Of course it finds the instance imported by the root `AppModule`. Now `parentModule` exists and the constructor throws the error. ## More on NgModules <docs-pill-row> <docs-pill href="/guide/ngmodules/sharing" title="Sharing Modules"/> <docs-pill href="/guide/ngmodules/lazy-loading" title="Lazy Loading Modules"/> <docs-pill href="/guide/ngmodules/faq" title="NgModule FAQ"/> </docs-pill-row>
004543
Step-by-step setup Setting up a lazy-loaded feature module requires two main steps: 1. Create the feature module with the Angular CLI, using the `--route` flag. 1. Configure the routes. ### Set up an application If you don't already have an application, follow the following steps to create one with the Angular CLI. If you already have an application, skip to [Configure the routes](#imports-and-route-configuration). Enter the following command where `customer-app` is the name of your app: <docs-code language="shell"> ng new customer-app --no-standalone --routing </docs-code> This creates an application called `customer-app`, `--no-standalone` flag makes the app module-based, and the `--routing` flag generates a file called `app-routing.module.ts`. This is one of the files you need for setting up lazy loading for your feature module. Navigate into the project by issuing the command `cd customer-app`. ### Create a feature module with routing Next, you need a feature module with a component to route to. To make one, enter the following command in the command line tool, where `customers` is the name of the feature module. The path for loading the `customers` feature modules is also `customers` because it is specified with the `--route` option: <docs-code language="shell"> ng generate module customers --route customers --module app.module </docs-code> This creates a `customers` directory having the new lazy-loadable feature module `CustomersModule` defined in the `customers.module.ts` file and the routing module `CustomersRoutingModule` defined in the `customers-routing.module.ts` file. The command automatically declares the `CustomersComponent` and imports `CustomersRoutingModule` inside the new feature module. Because the new module is meant to be lazy-loaded, the command does **not** add a reference to it in the application's root module file, `app.module.ts`. Instead, it adds the declared route, `customers` to the `routes` array declared in the module provided as the `--module` option. <docs-code header="src/app/app-routing.module.ts" language="typescript"> const routes: Routes = [ { path: 'customers', loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) } ]; </docs-code> Notice that the lazy-loading syntax uses `loadChildren` followed by a function that uses the browser's built-in `import('...')` syntax for dynamic imports. The import path is the relative path to the module. <docs-callout title="String-based lazy loading"> In Angular version 8, the string syntax for the `loadChildren` route specification was deprecated in favor of the `import()` syntax. You can opt into using string-based lazy loading (`loadChildren: './path/to/module#Module'`) by including the lazy-loaded routes in your `tsconfig` file, which includes the lazy-loaded files in the compilation. By default the Angular CLI generates projects with stricter file inclusions intended to be used with the `import()` syntax. </docs-callout> ### Add another feature module Use the same command to create a second lazy-loaded feature module with routing, along with its stub component. <docs-code language="shell"> ng generate module orders --route orders --module app.module </docs-code> This creates a new directory called `orders` containing the `OrdersModule` and `OrdersRoutingModule`, along with the new `OrdersComponent` source files. The `orders` route, specified with the `--route` option, is added to the `routes` array inside the `app-routing.module.ts` file, using the lazy-loading syntax. <docs-code header="src/app/app-routing.module.ts" language="typescript" highlight="[6,7,8,9]"> const routes: Routes = [ { path: 'customers', loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) }, { path: 'orders', loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule) } ]; </docs-code> ### Set up the UI Though you can type the URL into the address bar, a navigation UI is straightforward for the user and more common. Replace the default placeholder markup in `app.component.html` with a custom nav, so you can navigate to your modules in the browser: <docs-code header="src/app/app.component.html" language="html" highlight="[4,5,6]"> <h1> {{title}} </h1> <button type="button" routerLink="/customers">Customers</button> <button type="button" routerLink="/orders">Orders</button> <button type="button" routerLink="">Home</button> <router-outlet></router-outlet> </docs-code> To see your application in the browser so far, enter the following command in the command line tool window: <docs-code language="shell"> ng serve </docs-code> Then go to `localhost:4200` where you should see "customer-app" and three buttons. <img alt="three buttons in the browser" src="assets/images/guide/modules/lazy-loading-three-buttons.png" width="300"> These buttons work, because the Angular CLI automatically added the routes for the feature modules to the `routes` array in `app-routing.module.ts`. ### Imports and route configuration The Angular CLI automatically added each feature module to the routes map at the application level. Finish this off by adding the default route. In the `app-routing.module.ts` file, update the `routes` array with the following: <docs-code header="src/app/app-routing.module.ts" language="typescript"> const routes: Routes = [ { path: 'customers', loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) }, { path: 'orders', loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule) }, { path: '', redirectTo: '', pathMatch: 'full' } ]; </docs-code> The first two paths are the routes to the `CustomersModule` and the `OrdersModule`. The final entry defines a default route. The empty path matches everything that doesn't match an earlier path. ### Inside the feature module Next, take a look at the `customers.module.ts` file. If you're using the Angular CLI and following the steps outlined in this page, you don't have to do anything here. <docs-code header="src/app/customers/customers.module.ts" language="typescript"> import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CustomersRoutingModule } from './customers-routing.module'; import { CustomersComponent } from './customers.component'; @NgModule({ imports: [ CommonModule, CustomersRoutingModule ], declarations: [CustomersComponent] }) export class CustomersModule { } </docs-code> The `customers.module.ts` file imports the `customers-routing.module.ts` and `customers.component.ts` files. `CustomersRoutingModule` is listed in the `@NgModule` `imports` array giving `CustomersModule` access to its own routing module. `CustomersComponent` is in the `declarations` array, which means `CustomersComponent` belongs to the `CustomersModule`. The `app-routing.module.ts` then imports the feature module, `customers.module.ts` using JavaScript's dynamic import. The feature-specific route definition file `customers-routing.module.ts` imports its own feature component defined in the `customers.component.ts` file, along with the other JavaScript import statements. It then maps the empty path to the `CustomersComponent`. <docs-code header="src/app/customers/customers-routing.module.ts" language="typescript" highlight="[8,9]"> import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CustomersComponent } from './customers.component'; const routes: Routes = [ { path: '', component: CustomersComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class CustomersRoutingModule { } </docs-code> The `path` here is set to an empty string because the path in `AppRoutingModule` is already set to `customers`, so this route in the `CustomersRoutingModule`, is already within the `customers` context. Every route in this routing module is a child route. The other feature module's routing module is configured similarly. <docs-code header="src/app/orders/orders-routing.module.ts (excerpt)" language="typescript"> import { OrdersComponent } from './orders.component'; const routes: Routes = [ { path: '', component: OrdersComponent } ]; </docs-code> ##
004544
# Verify lazy loading You can verify that a module is indeed being lazy loaded with the Chrome developer tools. In Chrome, open the developer tools by pressing <kbd>⌘ Cmd</kbd>+<kbd>Option</kbd>+<kbd>i</kbd> on a Mac or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>j</kbd> on a PC and go to the Network Tab. <img alt="lazy loaded modules diagram" src="assets/images/guide/modules/lazy-loading-network-tab.png" width="600"> Click on the Orders or Customers button. If you see a chunk appear, everything is wired up properly and the feature module is being lazy loaded. A chunk should appear for Orders and for Customers but only appears once for each. <img alt="lazy loaded modules diagram" src="assets/images/guide/modules/lazy-loading-chunk-arrow.png" width="600"> To see it again, or to test after making changes, click the circle with a line through it in the upper left of the Network Tab: <img alt="lazy loaded modules diagram" src="assets/images/guide/modules/lazy-loading-clear.gif" width="200"> Then reload with <kbd>⌘ Cmd</kbd>+<kbd>R</kbd> or <kbd>Ctrl</kbd>+<kbd>R</kbd>, depending on your platform. ## `forRoot()` and `forChild()` You might have noticed that the Angular CLI adds `RouterModule.forRoot(routes)` to the `AppRoutingModule` `imports` array. This lets Angular know that the `AppRoutingModule` is a routing module and `forRoot()` specifies that this is the root routing module. It configures all the routes you pass to it, gives you access to the router directives, and registers the `Router` service. Use `forRoot()` only once in the application, inside the `AppRoutingModule`. The Angular CLI also adds `RouterModule.forChild(routes)` to feature routing modules. This way, Angular knows that the route list is only responsible for providing extra routes and is intended for feature modules. You can use `forChild()` in multiple modules. The `forRoot()` method takes care of the *global* injector configuration for the Router. The `forChild()` method has no injector configuration. It uses directives such as `RouterOutlet` and `RouterLink`. For more information, see the [`forRoot()` pattern](guide/ngmodules/singleton-services#forRoot) section of the singleton services guide. ## Preloading Preloading improves UX by loading parts of your application in the background. You can preload modules, standalone components or component data. ### Preloading modules and standalone components Preloading modules and standalone components improves UX by loading parts of your application in the background. By doing this, users don't have to wait for the elements to download when they activate a route. To enable preloading of all lazy loaded modules and standalone components, import the `PreloadAllModules` token from the Angular `router`. ### Module based application <docs-code header="AppRoutingModule (excerpt)" language="typescript"> import { PreloadAllModules } from '@angular/router'; </docs-code> Then, specify your preloading strategy in the `AppRoutingModule`'s `RouterModule.forRoot()` call. <docs-code header="AppRoutingModule (excerpt)" language="typescript" highlight="[4]"> RouterModule.forRoot( appRoutes, { preloadingStrategy: PreloadAllModules } ) </docs-code> ### Standalone application For standalone applications configure preloading strategies by adding `withPreloading` to `provideRouter`s RouterFeatures in `app.config.ts` <docs-code header="app.config.ts" language="typescript" highlight="[3,5,14]"> import { ApplicationConfig } from '@angular/core'; import { PreloadAllModules, provideRouter withPreloading, } from '@angular/router'; import { routes } from './app.routes'; export const appConfig: ApplicationConfig = { providers: [ provideRouter( routes, withPreloading(PreloadAllModules) ), ], }; </docs-code> ### Preloading component data To preload component data, use a `resolver`. Resolvers improve UX by blocking the page load until all necessary data is available to fully display the page. #### Resolvers Create a resolver service. With the Angular CLI, the command to create a service is as follows: <docs-code language="shell"> ng generate service <service-name> </docs-code> In the newly created service, implement the `Resolve` interface provided by the `@angular/router` package: <docs-code header="Resolver service (excerpt)" language="typescript"> import { Resolve } from '@angular/router'; … /*An interface that represents your data model*/ export interface Crisis { id: number; name: string; } export class CrisisDetailResolverService implements Resolve<Crisis> { resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Crisis> { // your logic goes here } } </docs-code> Import this resolver into your module's routing module. <docs-code header="Feature module's routing module (excerpt)" language="typescript"> import { CrisisDetailResolverService } from './crisis-detail-resolver.service'; </docs-code> Add a `resolve` object to the component's `route` configuration. <docs-code header="Feature module's routing module (excerpt)" language="typescript" highlight="[4,5,6]"> { path: '/your-path', component: YourComponent, resolve: { crisis: CrisisDetailResolverService } } </docs-code> In the component's constructor, inject an instance of the `ActivatedRoute` class that represents the current route. <docs-code header="Component's constructor (excerpt)"> import { ActivatedRoute } from '@angular/router'; @Component({ … }) class YourComponent { constructor(private route: ActivatedRoute) {} } </docs-code> Use the injected instance of the `ActivatedRoute` class to access `data` associated with a given route. <docs-code header="Component's ngOnInit lifecycle hook (excerpt)" language="typescript" highlight="[1,5,8]"> import { ActivatedRoute } from '@angular/router'; @Component({ … }) class YourComponent { constructor(private route: ActivatedRoute) {} ngOnInit() { this.route.data .subscribe(data => { const crisis: Crisis = data.crisis; // … }); } } </docs-code> ## Troubleshooting lazy-loading modules A common error when lazy-loading modules is importing common modules in multiple places within an application. Test for this condition by first generating the module using the Angular CLI and including the `--route route-name` parameter, where `route-name` is the name of your module. Next, create the module without the `--route` parameter. If `ng generate module` with the `--route` parameter returns an error, but runs correctly without it, you might have imported the same module in multiple places. Remember, many common Angular modules should be imported at the base of your application. For more information on Angular Modules, see [NgModules](guide/ngmodules). ## More on NgModules and routing You might also be interested in the following: * [Routing and Navigation](guide/routing) * [Providers](guide/ngmodules/providers) * [Types of Feature Modules](guide/ngmodules/module-types) * [Route-level code-splitting in Angular](https://web.dev/route-level-code-splitting-in-angular) * [Route preloading strategies in Angular](https://web.dev/route-preloading-in-angular)
004546
# NgModules **NgModules** configure the injector, the compiler and help organize related things together. An NgModule is a class marked by the `@NgModule` decorator. `@NgModule` takes a metadata object that describes how to compile a component's template and how to create an injector at runtime. It identifies the module's own components, directives, and pipes, making some of them public, through the `exports` property, so that external components can use them. `@NgModule` can also add service providers to the application dependency injectors. ## Angular modularity Modules are a great way to organize an application and extend it with capabilities from external libraries. Angular libraries are NgModules, such as `FormsModule`, `HttpClientModule`, and `RouterModule`. Many third-party libraries are available as NgModules such as the [Material Design component library](https://material.angular.io), [Ionic](https://ionicframework.com), or [Angular's Firebase integration](https://github.com/angular/angularfire). NgModules consolidate components, directives, and pipes into cohesive blocks of functionality, each focused on a feature area, application business domain, workflow, or common collection of utilities. Modules can also add services to the application. Such services might be internally developed, like something you'd develop yourself or come from outside sources, such as the Angular router and HTTP client. Modules can be loaded eagerly when the application starts or lazy loaded asynchronously by the router. NgModule metadata does the following: * Declares which components, directives, and pipes belong to the module * Makes some of those components, directives, and pipes public so that other module's component templates can use them * Imports other modules with the components, directives, and pipes that components in the current module need * Provides services that other application components can use Every Module-based Angular application has at least one module, the root module. You [bootstrap](guide/ngmodules/bootstrapping) that module to launch the application. The root module is all you need in an application with few components. As the application grows, you refactor the root module into [feature modules](guide/ngmodules/feature-modules) that represent collections of related functionality. You then import these modules into the root module. ## The basic NgModule The [Angular CLI](/tools/cli) generates the following basic `AppModule` when creating a new application with the `--no-standalone` option. <docs-code header="src/app/app.module.ts"> import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule], providers: [], bootstrap: [AppComponent] }) export class AppModule {} </docs-code> At the top are the import statements. The next section is where you configure the `@NgModule` by stating what components and directives belong to it (`declarations`) as well as which other modules it uses (`imports`). For more information on the structure of an `@NgModule`, be sure to read [Bootstrapping](guide/ngmodules/bootstrapping). ## More on NgModules <docs-pill-row> <docs-pill href="/guide/ngmodules/feature-modules" title="Feature Modules"/> <docs-pill href="/guide/ngmodules/providers" title="Providers"/> <docs-pill href="/guide/ngmodules/module-types" title="Types of NgModules"/> </docs-pill-row>
004547
# Providing dependencies in modules A provider is an instruction to the [Dependency Injection](guide/di) system on how to obtain a value for a dependency. Most of the time, these dependencies are services that you create and provide. ## Providing a service If you already have an application that was created with the [Angular CLI](/tools/cli), you can create a service using the `ng generate` CLI command in the root project directory. Replace *User* with the name of your service. <docs-code language="shell"> ng generate service User </docs-code> This command creates the following `UserService` skeleton: <docs-code header="src/app/user.service.ts"> import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class UserService { } </docs-code> You can now inject `UserService` anywhere in your application. The service itself is a class that the CLI generated and that's decorated with `@Injectable()`. By default, this decorator has a `providedIn` property, which creates a provider for the service. In this case, `providedIn: 'root'` specifies that Angular should provide the service in the root injector. ## Provider scope When you add a service provider to the root application injector, it's available throughout the application. Additionally, these providers are also available to all the classes in the application as long they have the lookup token. You should always provide your service in the root injector unless there is a case where you want the service to be available only if the consumer imports a particular `@NgModule`. ## Limiting provider scope by lazy loading modules In the basic CLI-generated app, modules are eagerly loaded which means that they are all loaded when the application launches. Angular uses an injector system to make things available between modules. In an eagerly loaded app, the root application injector makes all of the providers in all of the modules available throughout the application. This behavior necessarily changes when you use lazy loading. Lazy loading is when you load modules only when you need them; for example, when routing. They aren't loaded right away like with eagerly loaded modules. This means that any services listed in their provider arrays aren't available because the root injector doesn't know about these modules. <!--todo: KW--Make diagram here --> <!--todo: KW--per Misko: not clear if the lazy modules are siblings or grand-children. They are both depending on router structure. --> When the Angular router lazy-loads a module, it creates a new injector. This injector is a child of the root application injector. Imagine a tree of injectors; there is a single root injector and then a child injector for each lazy loaded module. This child injector gets populated with all the module-specific providers, if any. Look up resolution for every provider follows the [rules of dependency injection hierarchy](guide/di/hierarchical-dependency-injection#resolution-rules). Any component created within a lazy loaded module's context, such as by router navigation, gets its own local instance of child provided services, not the instance in the root application injector. Components in external modules continue to receive the instances created for the application root injector. Though you can provide services by lazy loading modules, not all services can be lazy loaded. For instance, some modules only work in the root module, such as the Router. The Router works with the global location object in the browser. As of Angular version 9, you can provide a new instance of a service with each lazy loaded module. The following code adds this functionality to `UserService`. <docs-code header="src/app/user.service.ts" highlight="[4]"> import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'any', }) export class UserService { } </docs-code> With `providedIn: 'any'`, all eagerly loaded modules share a singleton instance; however, lazy loaded modules each get their own unique instance, as shown in the following diagram. <img alt="any-provider-scope" class="left" src="assets/images/guide/providers/any-provider.svg"> ## Limiting provider scope with components Another way to limit provider scope is by adding the service you want to limit to the component's `providers` array. Component providers and NgModule providers are independent of each other. This method is helpful when you want to eagerly load a module that needs a service all to itself. Providing a service in the component limits the service only to that component and its descendants. Other components in the same module can't access it. <docs-code header="src/app/app.component.ts"> @Component({ // ... providers: [UserService] }) export class AppComponent {} </docs-code> ## Providing services in modules vs. components Generally, provide services the whole application needs in the root module and scope services by providing them in lazy loaded modules. The router works at the root level so if you put providers in a component, even `AppComponent`, lazy loaded modules, which rely on the router, can't see them. <!-- KW--Make a diagram here --> Register a provider with a component when you must limit a service instance to a component and its component tree, that is, its child components. For example, a user editing component, `UserEditorComponent`, that needs a private copy of a caching `UserService` should register the `UserService` with the `UserEditorComponent`. Then each new instance of the `UserEditorComponent` gets its own cached service instance. ## Injector hierarchy and service instances Services are singletons within the scope of an injector, which means there is at most one instance of a service in a given injector. Angular DI has a [hierarchical injection system](guide/di/hierarchical-dependency-injection), which means that nested injectors can create their own service instances. Whenever Angular creates a new instance of a component that has `providers` specified in `@Component()`, it also creates a new child injector for that instance. Similarly, when a new NgModule is lazy-loaded at run time, Angular can create an injector for it with its own providers. Child modules and component injectors are independent of each other, and create their own separate instances of the provided services. When Angular destroys an NgModule or component instance, it also destroys that injector and that injector's service instances. For more information, see [Hierarchical injectors](guide/di/hierarchical-dependency-injection). ## More on NgModules <docs-pill-row> <docs-pill href="/guide/ngmodules/singleton-services" title="Singleton Services"/> <docs-pill href="/guide/ngmodules/lazy-loading" title="Lazy Loading Modules"/> <docs-pill href="/guide/di/dependency-injection-providers" title="Dependency providers"/> <docs-pill href="/guide/ngmodules/faq" title="NgModule FAQ"/> </docs-pill-row>
004548
# NgModule API At a high level, NgModules are a way to organize Angular applications and they accomplish this through the metadata in the `@NgModule` decorator. The metadata falls into three categories: | Category | Details | |:--- |:--- | | Static | Compiler configuration which tells the compiler about directive selectors and where in templates the directives should be applied through selector matching. This is configured using the `declarations` array. | | Runtime | Injector configuration using the `providers` array. | | Composability / Grouping | Bringing NgModules together and making them available using the `imports` and `exports` arrays. | <docs-code language="typescript" highlight="[2,5,8]"> @NgModule({ // Static, that is compiler configuration declarations: [], // Configure the selectors // Runtime, or injector configuration providers: [], // Runtime injector configuration // Composability / Grouping imports: [], // composing NgModules together exports: [] // making NgModules available to other parts of the app }) </docs-code> ## `@NgModule` metadata The following table summarizes the `@NgModule` metadata properties. | Property | Details | |:--- |:--- | | `declarations` | A list of [declarable](guide/ngmodules/faq#what-is-a-declarable?) classes (*components*, *directives*, and *pipes*) that *belong to this module*. <ol> <li> When compiling a template, you need to determine a set of selectors which should be used for triggering their corresponding directives. </li> <li> The template is compiled within the context of an NgModule —the NgModule within which the template's component is declared— which determines the set of selectors using the following rules: <ul> <li> All selectors of directives listed in `declarations`. </li> <li> All selectors of directives exported from imported NgModules. </li> </ul> </li> </ol> Components, directives, and pipes must belong to *exactly* one module. The compiler emits an error if you try to declare the same class in more than one module. Be careful not to re-declare a class that is imported directly or indirectly from another module. | | `providers` | A list of dependency-injection providers. <br /> Angular registers these providers with the NgModule's injector. If it is the NgModule used for bootstrapping then it is the root injector. <br /> These services become available for injection into any component, directive, pipe or service which is a child of this injector. <br /> A lazy-loaded module has its own injector which is typically a child of the application root injector. <br /> Lazy-loaded services are scoped to the lazy module's injector. If a lazy-loaded module also provides the `UserService`, any component created within that module's context (such as by router navigation) gets the local instance of the service, not the instance in the root application injector. <br /> Components in external modules continue to receive the instance provided by their injectors. <br /> For more information on injector hierarchy and scoping, see [Providers](guide/ngmodules/providers) and the [DI Guide](guide/di). | | `imports` | A list of modules which should be folded into this module. Folded means it is as if all the imported NgModule's exported properties were declared here. <br /> Specifically, it is as if the list of modules whose exported components, directives, or pipes are referenced by the component templates were declared in this module. <br /> A component template can [reference](guide/ngmodules/faq#how-does-angular-find-components,-directives,-and-pipes-in-a-template?-what-is-a-template-reference?) another component, directive, or pipe when the reference is declared in this module or if the imported module has exported it. For example, a component can use the `NgIf` and `NgFor` directives only if the module has imported the Angular `CommonModule` (perhaps indirectly by importing `BrowserModule`). <br /> You can import many standard directives from the `CommonModule` but some familiar directives belong to other modules. For example, you can use `[(ngModel)]` only after importing the Angular `FormsModule`. | | `exports` | A list of declarations —*component*, *directive*, and *pipe* classes— that an importing module can use. <br /> Exported declarations are the module's *public API*. A component in another module can use *this* module's `UserComponent` if it imports this module and this module exports `UserComponent`. <br /> Declarations are private by default. If this module does *not* export `UserComponent`, then only the components within *this* module can use `UserComponent`. <br /> Importing a module does *not* automatically re-export the imported module's imports. Module 'B' can't use `ngIf` just because it imported module 'A' which imported `CommonModule`. Module 'B' must import `CommonModule` itself. <br /> A module can list another module among its `exports`, in which case all of that module's public components, directives, and pipes are exported. <br /> [Re-export](guide/ngmodules/faq#what-should-i-export?) makes module transitivity explicit. If Module 'A' re-exports `CommonModule` and Module 'B' imports Module 'A', Module 'B' components can use `ngIf` even though 'B' itself didn't import `CommonModule`. | | `bootstrap` | A list of components that are automatically bootstrapped. <br /> Usually there's only one component in this list, the *root component* of the application. <br /> Angular can launch with multiple bootstrap components, each with its own location in the host web page. | ## More on NgModules <docs-pill-row> <docs-pill href="guide/ngmodules/feature-modules" title="Feature Modules"/> <docs-pill href="guide/ngmodules/providers" title="Providers"/> <docs-pill href="guide/ngmodules/module-types" title="Types of Feature Modules"/> </docs-pill-row>
004549
# Launching your app with a root module An NgModule describes how the application parts fit together. Every application has at least one Angular module, the *root* module, which must be present for bootstrapping the application on launch. By convention and by default, this NgModule is named `AppModule`. When you use the [Angular CLI](/tools/cli) `ng new` command with the `no-standalone` option to generate an app, the default `AppModule` looks like the following: <docs-code language="typescript"> import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } </docs-code> The `@NgModule` decorator identifies `AppModule` as an `NgModule` class. `@NgModule` takes a metadata object that tells Angular how to compile and launch the application. | Metadata field | Details | |:--- |:--- | | `declarations` | Includes the *root* application component. | | `imports` | Imports `BrowserModule` to enable browser-specific services (such as DOM rendering, sanitization) | | `providers` | The service providers. | | `bootstrap` | The *root* component that Angular creates and inserts into the `index.html` host web page. | ## The `declarations` array The module's `declarations` array tells Angular which components belong to that module. As you create more components, add them to `declarations`. The `declarations` array only takes declarables. Declarables are [components](guide/components), [directives](guide/directives), and [pipes](guide/templates/pipes). All of a module's declarables must be in the `declarations` array. Declarables must belong to exactly one module. The compiler returns an error if declare the same class in multiple modules. These declared classes are usable within the module but private to components in a different module, unless they are exported from this module and the other module imports this one. An example of what goes into a declarations array follows: <docs-code language="typescript"> declarations: [ YourComponent, YourPipe, YourDirective ], </docs-code> ### Using directives with `@NgModule` Use the `declarations` array for directives. To use a directive, component, or pipe in a module, you must do a few things: 1. Export it from the TypeScript file where you wrote it 2. Import it into the appropriate file containing the `@NgModule` class. 3. Declare it in the `@NgModule` `declarations` array. Those three steps look like the following. In the file where you create your directive, export it. The following example shows an empty directive named `ItemDirective`. <docs-code header="src/app/item.directive.ts" highlight="[6]"> import { Directive } from '@angular/core'; @Directive({ selector: '[appItem]' }) export class ItemDirective { // your code here } </docs-code> The key point here is that you have to export it, so that you can import it elsewhere. Next, import it into the file in which your `NgModule` lives. In this example, this is the `app.module.ts` file. <docs-code header="src/app/app.module.ts"> import { ItemDirective } from './item.directive'; </docs-code> And in the same file, add it to the `@NgModule` `declarations` array: <docs-code header="src/app/app.module.ts" highlight="[3]"> declarations: [ AppComponent, ItemDirective ], </docs-code> Now you can use `ItemDirective` in a component. This example uses `AppModule`, but you would follow the same steps for a feature module. For more about directives, see [Attribute Directives](guide/directives/attribute-directives) and [Structural Directives](guide/directives/structural-directives). You'd also use the same technique for [pipes](guide/templates/pipes) and [components](guide/components). Remember, components, directives, and pipes belong to one module only. You only need to declare them once in your application because you share them by importing the necessary modules. This saves you time and helps keep your application lean. ## The `imports` array Modules accept an `imports` array in the `@NgModule` metadata object. It tells Angular about other NgModules that this particular module needs to function properly. <docs-code header="src/app/app.module.ts"> imports: [ BrowserModule, FormsModule, HttpClientModule ], </docs-code> This list of modules are those that export components, directives, or pipes that component templates in this module reference. In this case, the component is `AppComponent`, which references components, directives, or pipes in `BrowserModule`, `FormsModule`, or `HttpClientModule`. A component template can reference another component, directive, or pipe when the referenced class is declared in this module, or the class was imported from another module. ## The `providers` array The providers array is where you list the services the application needs. When you list services here, they are available app-wide. You can scope them when using feature modules and lazy loading. For more information, see [Providers in modules](guide/ngmodules/providers). ## The `bootstrap` array The application launches by bootstrapping the root `AppModule`. The bootstrapping process creates the component(s) listed in the `bootstrap` array and inserts each one into the browser DOM, if it finds an element matching the component's `selector`. Each bootstrapped component is the base of its own tree of components. Inserting a bootstrapped component usually triggers a cascade of component creations that builds up that tree. While you can put more than one component tree on a host web page, most applications have only one component tree and bootstrap a single root component. The root component is commonly called `AppComponent` and is in the root module's `bootstrap` array. In a situation where you want to bootstrap a component based on an API response, or you want to mount the `AppComponent` in a different DOM node that doesn't match the component selector, please refer to `ApplicationRef.bootstrap()` documentation. ## More about Angular Modules See [Frequently Used Modules](guide/ngmodules/frequent) to learn more about modules you will commonly see in applications.
004550
# NgModule FAQ NgModules help organize an application into cohesive blocks of functionality. This page answers the questions many developers ask about NgModule design and implementation. ## What classes should I add to the `declarations` array? Add [declarable](guide/ngmodules/bootstrapping#the-declarations-array) classes —components, directives, and pipes— to a `declarations` list. Declare these classes in *exactly one* module of the application. Declare them in a module if they belong to that particular module. ## What is a `declarable`? Declarables are the class types —components, directives, and pipes— that you can add to a module's `declarations` list. They're the only classes that you can add to `declarations`. ## What classes should I *not* add to `declarations`? Add only [declarable](guide/ngmodules/bootstrapping#the-declarations-array) classes to an NgModule's `declarations` list. Do *not* declare the following: * A class that's already declared in another module, whether an application module, `@NgModule`, or third-party module. * An array of directives imported from another module. For example, don't declare `FORMS_DIRECTIVES` from `@angular/forms` because the `FormsModule` already declares it. * Module classes. * Service classes. * Non-Angular classes and objects, such as strings, numbers, functions, entity models, configurations, business logic, and helper classes. ## Why list the same component in multiple `NgModule` properties? `AppComponent` is often listed in both `declarations` and `bootstrap`. You might see the same component listed in `declarations` and `exports`. While that seems redundant, these properties have different functions. Membership in one list doesn't imply membership in another list. * `AppComponent` could be declared in this module but not bootstrapped. * `AppComponent` could be bootstrapped in this module but declared in a different feature module. * A component could be imported from another application module (so you can't declare it) and re-exported by this module. * A component could be exported for inclusion in an external component's template as well as dynamically loaded in a pop-up dialog. ## What does "Can't bind to 'x' since it isn't a known property of 'y'" mean? This error often means that you haven't declared the directive "x" or haven't imported the NgModule to which "x" belongs. HELPFUL: Perhaps you declared "x" in an application submodule but forgot to export it. The "x" class isn't visible to other modules until you add it to the `exports` list. ## What should I import? Import NgModules whose public (exported) [declarable classes](guide/ngmodules/bootstrapping#the-declarations-array) you need to reference in this module's component templates. This always means importing `CommonModule` from `@angular/common` for access to the Angular directives such as `NgIf` and `NgFor`. You can import it directly or from another NgModule that [re-exports](#can-i-re-export-classes-and-modules?) it. Import [BrowserModule](#should-i-import-browsermodule-or-commonmodule?) only in the root `AppModule`. Import `FormsModule` from `@angular/forms` if your components have `[(ngModel)]` two-way binding expressions. Import *shared* and *feature* modules when your components use their components, directives, and pipes. ## Should I import `BrowserModule` or `CommonModule`? The root application module, `AppModule`, of almost every browser application should import `BrowserModule` from `@angular/platform-browser`. `BrowserModule` provides services that are essential to launch and run a browser application. `BrowserModule` also re-exports `CommonModule` from `@angular/common`, which means that components in the `AppModule` also have access to the Angular directives every application needs, such as `NgIf` and `NgFor`. Do not import `BrowserModule` in any other module. *Feature modules* and *lazy-loaded modules* should import `CommonModule` instead. They need the common directives. They don't need to re-install the app-wide providers. Note: Importing `CommonModule` also frees feature modules for use on *any* target platform, not just browsers. ## What if I import the same module twice? That's not a problem. When three modules all import Module 'A', Angular evaluates Module 'A' once, the first time it encounters it, and doesn't do so again. That's true at whatever level `A` appears in a hierarchy of imported NgModules. When Module 'B' imports Module 'A', Module 'C' imports 'B', and Module 'D' imports `[C, B, A]`, then 'D' triggers the evaluation of 'C', which triggers the evaluation of 'B', which evaluates 'A'. When Angular gets to the 'B' and 'A' in 'D', they're already cached and ready to go. Angular doesn't like NgModules with circular references, so don't let Module 'A' import Module 'B', which imports Module 'A'. ## What should I export? Export [declarable](guide/ngmodules/bootstrapping#the-declarations-array) classes that components in *other* NgModules should be able to use in their templates. These are your *public* classes. If you don't export a declarable class, it stays *private*, visible only to other components declared in this NgModule. You *can* export any declarable class —components, directives, and pipes— whether it's declared in this NgModule or in an imported NgModule. You *can* re-export entire imported NgModules, which effectively re-export all of their exported classes. An NgModule can even export a module that it doesn't import. ## What should I *not* export? Don't export the following: * Private components, directives, and pipes that you need only within components declared in this NgModule. If you don't want another NgModule to see it, don't export it. * Non-declarable objects such as services, functions, configurations, and entity models. * Components that are only loaded dynamically by the router or by bootstrapping. Such components can never be selected in another component's template. While there's no harm in exporting them, there's also no benefit. * Pure service modules that don't have public (exported) declarations. For example, there's no point in re-exporting `HttpClientModule` because it doesn't export anything. Its only purpose is to add http service providers to the application as a whole. ## Can I re-export classes and modules? Absolutely. NgModules are a great way to selectively aggregate classes from other NgModules and re-export them in a consolidated, convenience module. An NgModule can re-export entire NgModules, which effectively re-exports all of their exported classes. Angular's own `BrowserModule` exports a couple of NgModules like this: <docs-code language="typescript"> exports: [CommonModule, ApplicationModule] </docs-code> An NgModule can export a combination of its own declarations, selected imported classes, and imported NgModules. Don't bother re-exporting pure service modules. Pure service modules don't export [declarable](guide/ngmodules/bootstrapping#the-declarations-array) classes that another NgModule could use. For example, there's no point in re-exporting `HttpClientModule` because it doesn't export anything. Its only purpose is to add http service providers to the application as a whole. ## What is the `forRoot()` method? The `forRoot()` static method is a convention that makes it easy for developers to configure services and providers that are intended to be singletons. A good example of `forRoot()` is the `RouterModule.forRoot()` method. For more information on `forRoot()` see [the `forRoot()` pattern](guide/ngmodules/singleton-services#the-forroot()-pattern) section of the [Singleton Services](guide/ngmodules/singleton-services) guide. ## Why is a
004551
service provided in a feature module visible everywhere? Providers listed in the `@NgModule.providers` of a bootstrapped module have application scope. Adding a service provider to `@NgModule.providers` effectively publishes the service to the entire application. When you import an NgModule, Angular adds the module's service providers (the contents of its `providers` list) to the application root injector. This makes the provider visible to every class in the application that knows the provider's lookup token, or name. Extensibility through NgModule imports is a primary goal of the NgModule system. Merging NgModule providers into the application injector makes it easy for a module library to enrich the entire application with new services. By adding the `HttpClientModule` once, every application component can make HTTP requests. However, this might feel like an unwelcome surprise if you expect the module's services to be visible only to the components declared by that feature module. If the `HeroModule` provides the `HeroService` and the root `AppModule` imports `HeroModule`, any class that knows the `HeroService` *type* can inject that service, not just the classes declared in the `HeroModule`. To limit access to a service, consider lazy loading the NgModule that provides that service. See [How do I restrict service scope to a module?](#how-do-i-restrict-service-scope-to-a-module?) for more information. ## Why is a service provided in a lazy-loaded module visible only to that module? Unlike providers of the modules loaded at launch, providers of lazy-loaded modules are *module-scoped*. When the Angular router lazy-loads a module, it creates a new execution context. That [context has its own injector](#why-does-lazy-loading-create-a-child-injector? "Why Angular creates a child injector"), which is a direct child of the application injector. The router adds the lazy module's providers and the providers of its imported NgModules to this child injector. These providers are insulated from changes to application providers with the same lookup token. When the router creates a component within the lazy-loaded context, Angular prefers service instances created from these providers to the service instances of the application root injector. ## What if two modules provide the same service? When two imported modules, loaded at the same time, list a provider with the same token, the second module's provider "wins". That's because both providers are added to the same injector. When Angular looks to inject a service for that token, it creates and delivers the instance created by the second provider. *Every* class that injects this service gets the instance created by the second provider. Even classes declared within the first module get the instance created by the second provider. If NgModule A provides a service for token 'X' and imports an NgModule B that also provides a service for token 'X', then NgModule A's service definition "wins". The service provided by the root `AppModule` takes precedence over services provided by imported NgModules. The `AppModule` always wins. ## How do I restrict service scope to a module? When a module is loaded at application launch, its `@NgModule.providers` have *application-wide scope*; that is, they are available for injection throughout the application. Imported providers are easily replaced by providers from another imported NgModule. Such replacement might be by design. It could be unintentional and have adverse consequences. As a general rule, import modules with providers *exactly once*, preferably in the application's *root module*. That's also usually the best place to configure, wrap, and override them. Suppose a module requires a customized `HttpBackend` that adds a special header for all Http requests. If another module elsewhere in the application also customizes `HttpBackend` or merely imports the `HttpClientModule`, it could override this module's `HttpBackend` provider, losing the special header. The server will reject http requests from this module. To avoid this problem, import the `HttpClientModule` only in the `AppModule`, the application *root module*. If you must guard against this kind of "provider corruption", *don't rely on a launch-time module's `providers`*. Load the module lazily if you can. Angular gives a [lazy-loaded module](#why-is-a-service-provided-in-a-lazy-loaded-module-visible-only-to-that-module?) its own child injector. The module's providers are visible only within the component tree created with this injector. ### Alternative: Restricting scope to a component and its children Continuing with the same example, suppose the components of a module truly require a private, custom `HttpBackend`. Create a "top component" that acts as the root for all of the module's components. Add the custom `HttpBackend` provider to the top component's `providers` list rather than the module's `providers`. Recall that Angular creates a child injector for each component instance and populates the injector with the component's own providers. When a child of this component asks for the `HttpBackend` service, Angular provides the local `HttpBackend` service, not the version provided in the application root injector. Child components can then make configured HTTP requests no matter how other modules configure `HttpBackend`. Make sure to create components needing access to this special-configuration `HttpBackend` as children of this component. You can embed the child components in the top component's template. Alternatively, make the top component a routing host by giving it a `<router-outlet>`. Define child routes and let the router load module components into that outlet. Though you can limit access to a service by providing it in a lazy loaded module or providing it in a component, providing services in a component can lead to multiple instances of those services. Thus, the lazy loading is preferable. ## Should I add application-wide providers to the root `AppModule` or the root `AppComponent`? Define application-wide providers by specifying `providedIn: 'root'` on its `@Injectable()` decorator (in the case of services) or at `InjectionToken` construction (in the case where tokens are provided). Providers that are created this way automatically are made available to the entire application and don't need to be listed in any module. If a provider cannot be configured in this way \(perhaps because it has no sensible default value\), then register application-wide providers in the root `AppModule`, not in the `AppComponent`. Lazy-loaded modules and their components can inject `AppModule` services; they can't inject `AppComponent` services. Register a service in `AppComponent` providers *only* if the service must be hidden from components outside the `AppComponent` tree. This is a rare use case. More generally, [prefer registering providers in NgModules](#should-i-add-other-providers-to-a-module-or-a-component?) to registering in components. ### Discussion Angular registers all startup module providers with the application root injector. The services that root injector providers create have application scope, which means they are available to the entire application. Certain services, such as the `Router`, only work when you register them in the application root injector. By contrast, Angular registers `AppComponent` providers with the `AppComponent`'s own injector. `AppComponent` services are available only to that component and its component tree. They have component scope. The `AppComponent`'s injector is a child of the root injector, one down in the injector hierarchy. For applications that don't use the router, that's almost the entire application. But in routed applications, routing operates at the root level where `AppComponent` services don't exist. This means that lazy-loaded modules can't reach them. ## Should I add other providers to a module or a component? Providers should be configured using `@Injectable` syntax. If possible, they should be provided in the application root (`providedIn: 'root'`). Services that are configured this way are lazily loaded if they are only used from a lazily loaded context. If it's the consumer's decision whether a provider is available application-wide or not, then register providers in modules (`@NgModule.providers`) instead of registering in components (`@Component.providers`). Register a provider with a component when you *must* limit the scope of a service instance to that component and its component tree. Apply the same reasoning to registering a provider with a directive. For example, an editing component that needs a private copy of a caching service should register the service with the component. Then each new instance of the component gets its own cached service instance. The changes that editor makes in its service don't touch the instances elsewhere in the application. [Always register *application-wide* services with the root `AppModule`](#should-i-add-application-wide-providers-to-the-root-appmodule-or-the-root-appcomponent?), not the root `AppComponent`. ## Why is it
004552
bad if a shared module provides a service to a lazy-loaded module? ### The eagerly loaded scenario When an eagerly loaded module provides a service, for example a `UserService`, that service is available application-wide. If the root module provides `UserService` and imports another module that provides the same `UserService`, Angular registers one of them in the root application injector (see [What if I import the same module twice?](#what-if-i-import-the-same-module-twice?)). Then, when some component injects `UserService`, Angular finds it in the application root injector, and delivers the app-wide singleton service. No problem. ### The lazy loaded scenario Now consider a lazy loaded module that also provides a service called `UserService`. When the router lazy loads a module, it creates a child injector and registers the `UserService` provider with that child injector. The child injector is *not* the root injector. When Angular creates a lazy component for that module and injects `UserService`, it finds a `UserService` provider in the lazy module's *child injector* and creates a *new* instance of the `UserService`. This is an entirely different `UserService` instance than the app-wide singleton version that Angular injected in one of the eagerly loaded components. This scenario causes your application to create a new instance every time, instead of using the singleton. ## Why does lazy loading create a child injector? Angular adds `@NgModule.providers` to the application root injector, unless the NgModule is lazy-loaded. For a lazy-loaded NgModule, Angular creates a *child injector* and adds the module's providers to the child injector. This means that an NgModule behaves differently depending on whether it's loaded during application start or lazy-loaded later. Neglecting that difference can lead to [adverse consequences](#why-is-it-bad-if-a-shared-module-provides-a-service-to-a-lazy-loaded-module?). Why doesn't Angular add lazy-loaded providers to the application root injector as it does for eagerly loaded NgModules? The answer is grounded in a fundamental characteristic of the Angular dependency-injection system. An injector can add providers *until it's first used*. Once an injector starts creating and delivering services, its provider list is frozen; no new providers are allowed. When an application starts, Angular first configures the root injector with the providers of all eagerly loaded NgModules *before* creating its first component and injecting any of the provided services. Once the application begins, the application root injector is closed to new providers. Time passes and application logic triggers lazy loading of an NgModule. Angular must add the lazy-loaded module's providers to an injector somewhere. It can't add them to the application root injector because that injector is closed to new providers. So Angular creates a new child injector for the lazy-loaded module context. ## How can I tell if an NgModule or service was previously loaded? Some NgModules and their services should be loaded only once by the root `AppModule`. Importing the module a second time by lazy loading a module could [produce errant behavior](#why-is-it-bad-if-a-shared-module-provides-a-service-to-a-lazy-loaded-module?) that may be difficult to detect and diagnose. To prevent this issue, write a constructor that attempts to inject the module or service from the root application injector. If the injection succeeds, the class has been loaded a second time. You can throw an error or take other remedial action. Certain NgModules, such as `BrowserModule`, implement such a guard. Here is a custom constructor for an NgModule called `GreetingModule`. <docs-code header="src/app/greeting/greeting.module.ts" language="typescript"> @NgModule({...}) export class GreetingModule { constructor(@Optional() @SkipSelf() parentModule?: GreetingModule) { if (parentModule) { throw new Error( 'GreetingModule is already loaded. Import it in the AppModule only'); } } } </docs-code> ## What kinds of modules should I have and how should I use them? Every application is different. Developers have various levels of experience and comfort with the available choices. Some suggestions and guidelines appear to have wide appeal. ### `SharedModule` `SharedModule` is a conventional name for an `NgModule` with the components, directives, and pipes that you use everywhere in your application. This module should consist entirely of `declarations`, most of them exported. The `SharedModule` may re-export other widget modules, such as `CommonModule`, `FormsModule`, and NgModules with the UI controls that you use most widely. The `SharedModule` should not have `providers` for reasons [explained previously](#why-is-it-bad-if-a-shared-module-provides-a-service-to-a-lazy-loaded-module?). Nor should any of its imported or re-exported modules have `providers`. Import the `SharedModule` in your *feature* modules. ### Feature Modules Feature modules are modules you create around specific application business domains, user workflows, and utility collections. They support your application by containing a particular feature, such as routes, services, widgets, etc. To conceptualize what a feature module might be in your app, consider that if you would put the files related to a certain functionality, like a search, in one folder, that the contents of that folder would be a feature module that you might call your `SearchModule`. It would contain all of the components, routing, and templates that would make up the search functionality. For more information, see [Feature Modules](guide/ngmodules/feature-modules) and [Module Types](guide/ngmodules/module-types) ## What's the difference between NgModules and JavaScript Modules? In an Angular app, NgModules and JavaScript modules work together. In modern JavaScript, every file is a module (see the [Modules](https://exploringjs.com/es6/ch_modules.html) page of the Exploring ES6 website). Within each file you write an `export` statement to make parts of the module public. An Angular NgModule is a class with the `@NgModule` decorator —JavaScript modules don't have to have the `@NgModule` decorator. Angular's `NgModule` has `imports` and `exports` and they serve a similar purpose. You *import* other NgModules so you can use their exported classes in component templates. You *export* this NgModule's classes so they can be imported and used by components of *other* NgModules. For more information, see [JavaScript Modules vs. NgModules](guide/ngmodules/vs-jsmodule). ## What is a template reference? How does Angular find components, directives, and pipes in a template? The [Angular compiler](#what-is-the-angular-compiler?) looks inside component templates for other components, directives, and pipes. When it finds one, that's a template reference. The Angular compiler finds a component or directive in a template when it can match the *selector* of that component or directive to some HTML in that template. The compiler finds a pipe if the pipe's *name* appears within the pipe syntax of the template HTML. Angular only matches selectors and pipe names for classes that are declared by this module or exported by a module that this module imports. ## What is the Angular compiler? The Angular compiler converts the application code you write into highly performant JavaScript code. The `@NgModule` metadata plays an important role in guiding the compilation process. The code you write isn't immediately executable. For example, components have templates that contain custom elements, attribute directives, Angular binding declarations, and some peculiar syntax that clearly isn't native HTML. The Angular compiler reads the template markup, combines it with the corresponding component class code, and emits *component factories*. A component factory creates a pure, 100% JavaScript representation of the component that incorporates everything described in its `@Component` metadata: The HTML, the binding instructions, the attached styles. Because directives and pipes appear in component templates, the Angular compiler incorporates them into compiled component code too. `@NgModule` metadata tells the Angular compiler what components to compile for this module and how to link this module with other modules.
004553
# Guidelines for creating NgModules This topic provides a conceptual overview of the different categories of NgModules you can create in order to organize your code in a modular structure. These categories are not cast in stone —they are suggestions. You may want to create NgModules for other purposes, or combine the characteristics of some of these categories. NgModules are a great way to organize an application and keep code related to a specific functionality or feature separate from other code. Use NgModules to consolidate components, directives, and pipes into cohesive blocks of functionality. Focus each block on a feature or business domain, a workflow or navigation flow, a common collection of utilities, or one or more providers for services. ## Summary of NgModule categories All module-based applications start by [bootstrapping a root NgModule](guide/ngmodules/bootstrapping "Launching an app with a root NgModule"). You can organize your other NgModules any way you want. This topic provides some guidelines for the following general categories of NgModules: | Category | Details | |:--- |:--- | | [Domain](#domain-ngmodules) | Is organized around a feature, business domain, or user experience. | | [Routing](#routing-ngmodules) | Provides the routing configuration for another NgModule. | | [Service](#service-ngmodules) | Provides utility services such as data access and messaging. | | [Widget](#widget-ngmodules) | Makes a component, directive, or pipe available to other NgModules. | | [Shared](#shared-ngmodules) | Makes a set of components, directives, and pipes available to other NgModules. | The following table summarizes the key characteristics of each category. | NgModule | Declarations | Providers | Exports | Imported by | |:--- |:--- |:--- |:--- |:--- | | Domain | Yes | Rare | Top component | Another domain, `AppModule` | | Routed | Yes | Rare | No | None | | Routing | No | Yes \(Guards\) | RouterModule | Another domain \(for routing\) | | Service | No | Yes | No | `AppModule` | | Widget | Yes | Rare | Yes | Another domain | | Shared | Yes | No | Yes | Another domain | ## Domain NgModules Use a domain NgModule to deliver a user experience dedicated to a particular feature or application domain, such as editing a customer or placing an order. A domain NgModule organizes the code related to a certain function, containing all of the components, routing, and templates that make up the function. Your top component in the domain NgModule acts as the feature or domain's root, and is the only component you export. Private supporting subcomponents descend from it. Import a domain NgModule exactly once into another NgModule, such as a domain NgModule, or into the root NgModule (`AppModule`) of an application that contains only a few NgModules. Domain NgModules consist mostly of declarations. You rarely include providers. If you do, the lifetime of the provided services should be the same as the lifetime of the NgModule. ## Routing NgModules Use a routing NgModule to provide the routing configuration for a domain NgModule, thereby separating routing concerns from its companion domain NgModule. HELPFUL: For an overview and details about routing, see [In-app navigation: routing to views](guide/routing "In-app navigation: routing to views"). Use a routing NgModule to do the following tasks: * Define routes * Add router configuration to the NgModule via `imports` * Add guard and resolver service providers to the NgModule's providers The name of the routing NgModule should parallel the name of its companion NgModule, using the suffix `Routing`. For example, consider a `ContactModule` in `contact.module.ts` has a routing NgModule named `ContactRoutingModule` in `contact-routing.module.ts`. Import a routing NgModule only into its companion NgModule. If the companion NgModule is the root `AppModule`, the `AppRoutingModule` adds router configuration to its imports with `RouterModule.forRoot(routes)`. All other routing NgModules are children that import using `RouterModule.forChild(routes)`. In your routing NgModule, re-export the `RouterModule` as a convenience so that components of the companion NgModule have access to router directives such as `RouterLink` and `RouterOutlet`. Don't use declarations in a routing NgModule. Components, directives, and pipes are the responsibility of the companion domain NgModule, not the routing NgModule. ## Service NgModules Use a service NgModule to provide a utility service such as data access or messaging. Ideal service NgModules consist entirely of providers and have no declarations. Angular's `HttpClientModule` is a good example of a service NgModule. Use only the root `AppModule` to import service NgModules. ## Widget NgModules Use a widget NgModule to make a component, directive, or pipe available to external NgModules. Import widget NgModules into any NgModules that need the widgets in their templates. Many third-party UI component libraries are provided as widget NgModules. A widget NgModule should consist entirely of declarations, most of them exported. It would rarely have providers. ## Shared NgModules Put commonly used directives, pipes, and components into one NgModule, typically named `SharedModule`, and then import just that NgModule wherever you need it in other parts of your application. You can import the shared NgModule in your domain NgModules, including [lazy-loaded NgModules](guide/ngmodules/lazy-loading "Lazy-loading an NgModule"). Note: Shared NgModules should not include providers, nor should any of its imported or re-exported NgModules include providers. To learn how to use shared modules to organize and streamline your code, see [Sharing NgModules in an app](guide/ngmodules/sharing "Sharing NgModules in an app"). ## Next steps If you want to manage NgModule loading and the use of dependencies and services, see the following: * To learn about loading NgModules eagerly when the application starts, or lazy-loading NgModules asynchronously by the router, see [Lazy-loading feature modules](guide/ngmodules/lazy-loading) * To understand how to provide a service or other dependency for your app, see [Providing Dependencies for an NgModule](guide/ngmodules/providers "Providing Dependencies for an NgModule") * To learn how to create a singleton service to use in NgModules, see [Making a service a singleton](guide/ngmodules/singleton-services "Making a service a singleton")
004554
# Frequently-used modules A Module-based Angular application needs at least one module that serves as the root module. As you add features to your app, you can add them in modules. The following are frequently used Angular modules with examples of some of the things they contain: | NgModule | Import it from | Why you use it | |:--- |:--- |:--- | | `BrowserModule` | `@angular/platform-browser` | To run your application in a browser. | | `CommonModule` | `@angular/common` | To use `NgIf` and `NgFor`. | | `FormsModule` | `@angular/forms` | To build template driven forms \(includes `NgModel`\). | | `ReactiveFormsModule` | `@angular/forms` | To build reactive forms. | | `RouterModule` | `@angular/router` | To use `RouterLink`, `.forRoot()`, and `.forChild()`. | | `HttpClientModule` | `@angular/common/http` | To communicate with a server using the HTTP protocol. | ## Importing modules When you use these Angular modules, import them in `AppModule`, or your feature module as appropriate, and list them in the `@NgModule` `imports` array. For example, in a new application generated by the [Angular CLI](/tools/cli) with the `--no-standalone` option, `BrowserModule` is imported into the `AppModule`. <docs-code language="typescript" highlight="[1,11,12]"> import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ /* add modules here so Angular knows to use them */ BrowserModule, ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } </docs-code> The imports at the top of the array are JavaScript import statements while the `imports` array within `@NgModule` is Angular specific. For more information on the difference, see [JavaScript Modules vs. NgModules](guide/ngmodules/vs-jsmodule). ## `BrowserModule` and `CommonModule` `BrowserModule` re-exports `CommonModule`, which exposes many common directives such as `ngIf` and `ngFor`. These directives are available to any module that imports the browser module, given the re-export. For applications that run in the browser, import `BrowserModule` in the root `AppModule` because it provides services that are essential to launch and render your application in browsers. Note: `BrowserModule`'s providers are for the whole application so it should only be in the root module, not in feature modules. Feature modules only need the common directives in `CommonModule`; they don't need to re-install app-wide providers.
004555
# Feature modules Feature modules are NgModules for the purpose of organizing code. As your application grows, you can organize code relevant for a specific feature. This helps apply clear boundaries for features. With feature modules, you can keep code related to a specific functionality or feature separate from other code. Delineating areas of your application helps with collaboration between developers and teams, separating directives, and managing the size of the root module. ## Feature modules vs. root modules A feature module is an organizational best practice, as opposed to a concept of the core Angular API. A feature module delivers a cohesive set of functionality focused on a specific application need such as a user workflow, routing, or forms. While you can do everything within the root module, feature modules help you partition the application into focused areas. A feature module collaborates with the root module and with other modules through the services it provides and the components, directives, and pipes that it shares. ## How to make a feature module Assuming you already have an application that you created with the [Angular CLI](/tools/cli), create a feature module using the CLI by entering the following command in the root project directory. You can omit the "Module" suffix from the name because the CLI appends it: <docs-code language="shell"> ng generate module CustomerDashboard </docs-code> This causes the CLI to create a folder called `customer-dashboard` with a file inside called `customer-dashboard.module.ts` with the following contents: <docs-code language="typescript"> import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; @NgModule({ imports: [ CommonModule ], declarations: [] }) export class CustomerDashboardModule { } </docs-code> The structure of an NgModule is the same whether it is a root module or a feature module. In the CLI generated feature module, there are two JavaScript import statements at the top of the file: the first imports `NgModule`, which, like the root module, lets you use the `@NgModule` decorator; the second imports `CommonModule`, which contributes many common directives such as `ngIf` and `ngFor`. Note: Feature modules import `CommonModule` instead of `BrowserModule`, which is only imported once in the root module. `CommonModule` only contains information for common directives such as `ngIf` and `ngFor` which are needed in most templates, whereas `BrowserModule` configures the Angular application for the browser which needs to be done only once. The `declarations` array is available for you to add declarables, which are components, directives, and pipes that belong exclusively to this particular module. To add a component, enter the following command at the command line where `customer-dashboard` is the directory where the CLI generated the feature module and `CustomerDashboard` is the name of the component: <docs-code language="shell"> ng generate component customer-dashboard/CustomerDashboard </docs-code> This generates a folder for the new component within the `customer-dashboard` folder and updates `CustomerDashboardModule`. <docs-code header="src/app/customer-dashboard/customer-dashboard.module.ts" highlight="[4,11,14]"> import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CustomerDashboardComponent } from './customer-dashboard/customer-dashboard.component'; @NgModule({ imports: [ CommonModule ], declarations: [ CustomerDashboardComponent ], exports: [ CustomerDashboardComponent ] }) export class CustomerDashboardModule { } </docs-code> The `CustomerDashboardComponent` is now in the JavaScript import list at the top and added to the `declarations` array, which lets Angular know to associate this new component with this feature module. ## Importing a feature module To incorporate the feature module into your app, you have to let the root module, `app.module.ts`, know about it. Notice the `CustomerDashboardModule` export at the bottom of `customer-dashboard.module.ts`. This exposes it so that other modules can get to it. To import it into the `AppModule`, add it to the imports in `app.module.ts` and to the `imports` array: <docs-code header="src/app/app.module.ts" highlight="[5,6,14]"> import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; // import the feature module here so you can add it to the imports array below import { CustomerDashboardModule } from './customer-dashboard/customer-dashboard.module'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, CustomerDashboardModule // add the feature module here ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } </docs-code> Now the `AppModule` knows about the feature module and `AppComponent` can use the customer dashboard component. More details on this in the section below. If you were to add any service providers to the feature module, `AppModule` would know about those too, as would any other imported feature modules. ## Rendering a feature module's component template When the CLI generated the `CustomerDashboardComponent` for the feature module, it included a template, `customer-dashboard.component.html`, with the following markup: <docs-code header="src/app/customer-dashboard/customer-dashboard/customer-dashboard.component.html" language="html"> <p> customer-dashboard works! </p> </docs-code> To see this HTML in the `AppComponent`, you first have to export the `CustomerDashboardComponent` in the `CustomerDashboardModule`. In `customer-dashboard.module.ts`, just beneath the `declarations` array, add an `exports` array containing `CustomerDashboardComponent`: <docs-code header="src/app/customer-dashboard/customer-dashboard.module.ts" highlight="[2]"> exports: [ CustomerDashboardComponent ] </docs-code> Next, in the `AppComponent`, `app.component.html`, add the tag `<app-customer-dashboard>`: <docs-code header="src/app/app.component.html" highlight="[5]" language="html"> <h1> {{title}} </h1> <app-customer-dashboard></app-customer-dashboard> </docs-code> Now, in addition to the title that renders by default, the `CustomerDashboardComponent` template renders too: <img alt="feature module component" src="assets/images/guide/modules/feature-module.png"> ## More on NgModules <docs-pill-row> <docs-pill href="/guide/ngmodules/lazy-loading" title="Lazy Loading Modules with the Angular Router"/> <docs-pill href="/guide/ngmodules/providers" title="Providers"/> <docs-pill href="/guide/ngmodules/module-types" title="Types of Feature Modules"/> </docs-pill-row>
004557
# Sharing modules Creating shared modules allows you to organize and streamline your code. You can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your application. Consider the following module from an imaginary app: <docs-code language="typescript" highlight="[9,19,20]"> import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { CustomerComponent } from './customer.component'; import { NewItemDirective } from './new-item.directive'; import { OrdersPipe } from './orders.pipe'; @NgModule({ imports: [CommonModule], declarations: [ CustomerComponent, NewItemDirective, OrdersPipe ], exports: [ CustomerComponent, NewItemDirective, OrdersPipe, CommonModule, FormsModule ], }) export class SharedModule { } </docs-code> Notice the following: * It imports the `CommonModule` because the module's component needs common directives * It declares and exports the utility pipe, directive, and component classes * It re-exports the `CommonModule` and `FormsModule` By re-exporting `CommonModule` and `FormsModule`, any other module that imports this `SharedModule`, gets access to directives like `NgIf` and `NgFor` from `CommonModule` and can bind to component properties with `[(ngModel)]`, a directive in the `FormsModule`. Even though the components declared by `SharedModule` might not bind with `[(ngModel)]` and there may be no need for `SharedModule` to import `FormsModule`, `SharedModule` can still export `FormsModule` without listing it among its `imports`. This way, you can give other modules access to `FormsModule` without having to make it available for itself. ## More on NgModules <docs-pill-row> <docs-pill href="/guide/ngmodules/providers" title="Providers"/> <docs-pill href="/guide/ngmodules/module-types" title="Types of Feature Modules"/> </docs-pill-row>
004559
# Creating an injectable service Service is a broad category encompassing any value, function, or feature that an application needs. A service is typically a class with a narrow, well-defined purpose. A component is one type of class that can use DI. Angular distinguishes components from services to increase modularity and reusability. By separating a component's view-related features from other kinds of processing, you can make your component classes lean and efficient. Ideally, a component's job is to enable the user experience and nothing more. A component should present properties and methods for data binding, to mediate between the view (rendered by the template) and the application logic (which often includes some notion of a model). A component can delegate certain tasks to services, such as fetching data from the server, validating user input, or logging directly to the console. By defining such processing tasks in an injectable service class, you make those tasks available to any component. You can also make your application more adaptable by configuring different providers of the same kind of service, as appropriate in different circumstances. Angular does not enforce these principles. Angular helps you follow these principles by making it easy to factor your application logic into services and make those services available to components through DI. ## Service examples Here's an example of a service class that logs to the browser console: <docs-code header="src/app/logger.service.ts (class)" language="typescript"> export class Logger { log(msg: unknown) { console.log(msg); } error(msg: unknown) { console.error(msg); } warn(msg: unknown) { console.warn(msg); } } </docs-code> Services can depend on other services. For example, here's a `HeroService` that depends on the `Logger` service, and also uses `BackendService` to get heroes. That service in turn might depend on the `HttpClient` service to fetch heroes asynchronously from a server: <docs-code header="src/app/hero.service.ts (class)" language="typescript" highlight="[5,6,10,12]"> export class HeroService { private heroes: Hero[] = []; constructor( private backend: BackendService, private logger: Logger) {} async getHeroes() { // Fetch this.heroes = await this.backend.getAll(Hero); // Log this.logger.log(`Fetched ${this.heroes.length} heroes.`); return this.heroes; } } </docs-code> ## Creating an injectable service The Angular CLI provides a command to create a new service. In the following example, you add a new service to an existing application. To generate a new `HeroService` class in the `src/app/heroes` folder, follow these steps: 1. Run this [Angular CLI](/tools/cli) command: <docs-code language="sh"> ng generate service heroes/hero </docs-code> This command creates the following default `HeroService`: <docs-code header="src/app/heroes/hero.service.ts (CLI-generated)" language="typescript"> import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class HeroService {} </docs-code> The `@Injectable()` decorator specifies that Angular can use this class in the DI system. The metadata, `providedIn: 'root'`, means that the `HeroService` is provided throughout the application. Add a `getHeroes()` method that returns the heroes from `mock.heroes.ts` to get the hero mock data: <docs-code header="src/app/heroes/hero.service.ts" language="typescript"> import { Injectable } from '@angular/core'; import { HEROES } from './mock-heroes'; @Injectable({ // declares that this service should be created // by the root application injector. providedIn: 'root', }) export class HeroService { getHeroes() { return HEROES; } } </docs-code> For clarity and maintainability, it is recommended that you define components and services in separate files. ## Injecting services To inject a service as a dependency into a component, you can use the component's `constructor()` and supply a constructor argument with the dependency type. The following example specifies the `HeroService` in the `HeroListComponent` constructor. The type of `heroService` is `HeroService`. Angular recognizes the `HeroService` type as a dependency, since that class was previously annotated with the `@Injectable` decorator: <docs-code header="src/app/heroes/hero-list.component (constructor signature)" language="typescript"> constructor(heroService: HeroService) </docs-code> ## Injecting services in other services When a service depends on another service, follow the same pattern as injecting into a component. In the following example, `HeroService` depends on a `Logger` service to report its activities: <docs-code header="src/app/heroes/hero.service.ts" language="typescript" highlight="[3,9,12]"> import { Injectable } from '@angular/core'; import { HEROES } from './mock-heroes'; import { Logger } from '../logger.service'; @Injectable({ providedIn: 'root', }) export class HeroService { constructor(private logger: Logger) {} getHeroes() { this.logger.log('Getting heroes.'); return HEROES; } } </docs-code> In this example, the `getHeroes()` method uses the `Logger` service by logging a message when fetching heroes. ## What's next <docs-pill-row> <docs-pill href="/guide/di/dependency-injection-providers" title="Configuring dependency providers"/> <docs-pill href="/guide/di/dependency-injection-providers#using-an-injectiontoken-object" title="`InjectionTokens`"/> </docs-pill-row>
004560
# Configuring dependency providers The previous sections described how to use class instances as dependencies. Aside from classes, you can also use values such as `boolean`, `string`, `Date`, and objects as dependencies. Angular provides the necessary APIs to make the dependency configuration flexible, so you can make those values available in DI. ## Specifying a provider token If you specify the service class as the provider token, the default behavior is for the injector to instantiate that class using the `new` operator. In the following example, the app component provides a `Logger` instance: <docs-code header="src/app/app.component.ts" language="typescript"> providers: [Logger], </docs-code> You can, however, configure DI to associate the `Logger` provider token with a different class or any other value. So when the `Logger` is injected, the configured value is used instead. In fact, the class provider syntax is a shorthand expression that expands into a provider configuration, defined by the `Provider` interface. Angular expands the `providers` value in this case into a full provider object as follows: <docs-code header="src/app/app.component.ts" language="typescript"> [{ provide: Logger, useClass: Logger }] </docs-code> The expanded provider configuration is an object literal with two properties: - The `provide` property holds the token that serves as the key for consuming the dependency value. - The second property is a provider definition object, which tells the injector **how** to create the dependency value. The provider-definition can be one of the following: - `useClass` - this option tells Angular DI to instantiate a provided class when a dependency is injected - `useExisting` - allows you to alias a token and reference any existing one. - `useFactory` - allows you to define a function that constructs a dependency. - `useValue` - provides a static value that should be used as a dependency. The sections below describe how to use the different provider definitions. ### Class providers: useClass The `useClass` provider key lets you create and return a new instance of the specified class. You can use this type of provider to substitute an alternative implementation for a common or default class. The alternative implementation can, for example, implement a different strategy, extend the default class, or emulate the behavior of the real class in a test case. In the following example, `BetterLogger` would be instantiated when the `Logger` dependency is requested in a component or any other class: <docs-code header="src/app/app.component.ts" language="typescript"> [{ provide: Logger, useClass: BetterLogger }] </docs-code> If the alternative class providers have their own dependencies, specify both providers in the providers metadata property of the parent module or component: <docs-code header="src/app/app.component.ts" language="typescript"> [ UserService, // dependency needed in `EvenBetterLogger`. { provide: Logger, useClass: EvenBetterLogger }, ] </docs-code> In this example, `EvenBetterLogger` displays the user name in the log message. This logger gets the user from an injected `UserService` instance: <docs-code header="src/app/even-better-logger.component.ts" language="typescript" highlight="[[3],[6]]"> @Injectable() export class EvenBetterLogger extends Logger { constructor(private userService: UserService) {} override log(message: string) { const name = this.userService.user.name; super.log(`Message to ${name}: ${message}`); } } </docs-code> Angular DI knows how to construct the `UserService` dependency, since it has been configured above and is available in the injector. ### Alias providers: useExisting The `useExisting` provider key lets you map one token to another. In effect, the first token is an alias for the service associated with the second token, creating two ways to access the same service object. In the following example, the injector injects the singleton instance of `NewLogger` when the component asks for either the new or the old logger: In this way, `OldLogger` is an alias for `NewLogger`. <docs-code header="src/app/app.component.ts" language="typescript" highlight="[4]"> [ NewLogger, // Alias OldLogger w/ reference to NewLogger { provide: OldLogger, useExisting: NewLogger}, ] </docs-code> Note: Ensure you do not alias `OldLogger` to `NewLogger` with `useClass`, as this creates two different `NewLogger` instances. ### Factory providers: useFactory The `useFactory` provider key lets you create a dependency object by calling a factory function. With this approach, you can create a dynamic value based on information available in the DI and elsewhere in the app. In the following example, only authorized users should see secret heroes in the `HeroService`. Authorization can change during the course of a single application session, as when a different user logs in . To keep security-sensitive information in `UserService` and out of `HeroService`, give the `HeroService` constructor a boolean flag to control display of secret heroes: <docs-code header="src/app/heroes/hero.service.ts" language="typescript" highlight="[[4],[7]]"> class HeroService { constructor( private logger: Logger, private isAuthorized: boolean) { } getHeroes() { const auth = this.isAuthorized ? 'authorized' : 'unauthorized'; this.logger.log(`Getting heroes for ${auth} user.`); return HEROES.filter(hero => this.isAuthorized || !hero.isSecret); } } </docs-code> To implement the `isAuthorized` flag, use a factory provider to create a new logger instance for `HeroService`. This is necessary as we need to manually pass `Logger` when constructing the hero service: <docs-code header="src/app/heroes/hero.service.provider.ts" language="typescript"> const heroServiceFactory = (logger: Logger, userService: UserService) => new HeroService(logger, userService.user.isAuthorized); </docs-code> The factory function has access to `UserService`. You inject both `Logger` and `UserService` into the factory provider so the injector can pass them along to the factory function: <docs-code header="src/app/heroes/hero.service.provider.ts" language="typescript" highlight="[3,4]"> export const heroServiceProvider = { provide: HeroService, useFactory: heroServiceFactory, deps: [Logger, UserService] }; </docs-code> - The `useFactory` field specifies that the provider is a factory function whose implementation is `heroServiceFactory`. - The `deps` property is an array of provider tokens. The `Logger` and `UserService` classes serve as tokens for their own class providers. The injector resolves these tokens and injects the corresponding services into the matching `heroServiceFactory` factory function parameters, based on the order specified. Capturing the factory provider in the exported variable, `heroServiceProvider`, makes the factory provider reusable. ### Value providers: useValue The `useValue` key lets you associate a static value with a DI token. Use this technique to provide runtime configuration constants such as website base addresses and feature flags. You can also use a value provider in a unit test to provide mock data in place of a production data service. The next section provides more information about the `useValue` key. ## Using an `InjectionToken` object Use an `InjectionToken` object as provider token for non-class dependencies. The following example defines a token, `APP_CONFIG`. of the type `InjectionToken`: <docs-code header="src/app/app.config.ts" language="typescript" highlight="[3]"> import { InjectionToken } from '@angular/core'; export interface AppConfig { title: string; } export const APP_CONFIG = new InjectionToken<AppConfig>('app.config description'); </docs-code> The optional type parameter, `<AppConfig>`, and the token description, `app.config description`, specify the token's purpose. Next, register the dependency provider in the component using the `InjectionToken` object of `APP_CONFIG`: <docs-code header="src/app/app.component.ts" language="typescript"> const MY_APP_CONFIG_VARIABLE: AppConfig = { title: 'Hello', }; providers: [{ provide: APP_CONFIG, useValue: MY_APP_CONFIG_VARIABLE }] </docs-code> Now, inject the configuration object into the constructor with the `@Inject()` parameter decorator: <docs-code header="src/app/app.component.ts" language="typescript" highlight="[2]"> export class AppComponent { constructor(@Inject(APP_CONFIG) config: AppConfig) { this.title = config.title; } } </docs-code> ### Interfaces and DI Though the TypeScript `AppConfig` interface supports typing within the class, the `AppConfig` interface plays no role in DI. In TypeScript, an interface is a design-time artifact, and does not have a runtime representation, or token, that the DI framework can use. When the TypeScript transpiles to JavaScript, the interface disappears because JavaScript doesn't have interfaces. Because there is no interface for Angular to find at runtime, the interface cannot be a token, nor can you inject it: <docs-code header="src/app/app.component.ts" language="typescript"> // Can't use interface as provider token [{ provide: AppConfig, useValue: MY_APP_CONFIG_VARIABLE })] </docs-code> <docs-code header="src/app/app.component.ts" language="typescript" highlight="[3]"> export class AppComponent { // Can't inject using the interface as the parameter type constructor(private config: AppConfig) {} } </docs-code>
004562
# Understanding dependency injection Dependency injection, or DI, is one of the fundamental concepts in Angular. DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need. Two main roles exist in the DI system: dependency consumer and dependency provider. Angular facilitates the interaction between dependency consumers and dependency providers using an abstraction called `Injector`. When a dependency is requested, the injector checks its registry to see if there is an instance already available there. If not, a new instance is created and stored in the registry. Angular creates an application-wide injector (also known as the "root" injector) during the application bootstrap process. In most cases you don't need to manually create injectors, but you should know that there is a layer that connects providers and consumers. This topic covers basic scenarios of how a class can act as a dependency. Angular also allows you to use functions, objects, primitive types such as string or Boolean, or any other types as dependencies. For more information, see [Dependency providers](guide/di/dependency-injection-providers). ## Providing a dependency Consider a class called `HeroService` that needs to act as a dependency in a component. The first step is to add the `@Injectable` decorator to show that the class can be injected. <docs-code language="typescript" highlight="[1]"> @Injectable() class HeroService {} </docs-code> The next step is to make it available in the DI by providing it. A dependency can be provided in multiple places: * [**Preferred**: At the application root level using `providedIn`.](#preferred-at-the-application-root-level-using-providedin) * [At the Component level.](#at-the-component-level) * [At the application root level using `ApplicationConfig`.](#at-the-application-root-level-using-applicationconfig) * [`NgModule` based applications.](#ngmodule-based-applications) ### **Preferred**: At the application root level using `providedIn` Providing a service at the application root level using `providedIn` allows injecting the service into all other classes. Using `providedIn` enables Angular and JavaScript code optimizers to effectively remove services that are unused (known as tree-shaking). You can provide a service by using `providedIn: 'root'` in the `@Injectable` decorator: <docs-code language="typescript" highlight="[2]"> @Injectable({ providedIn: 'root' }) class HeroService {} </docs-code> When you provide the service at the root level, Angular creates a single, shared instance of the `HeroService` and injects it into any class that asks for it. ### At the Component level You can provide services at `@Component` level by using the `providers` field of the `@Component` decorator. In this case the `HeroService` becomes available to all instances of this component and other components and directives used in the template. For example: <docs-code language="typescript" highlight="[5]"> @Component({ standalone: true, selector: 'hero-list', template: '...', providers: [HeroService] }) class HeroListComponent {} </docs-code> When you register a provider at the component level, you get a new instance of the service with each new instance of that component. Note: Declaring a service like this causes `HeroService` to always be included in your application— even if the service is unused. ### At the application root level using `ApplicationConfig` You can use the `providers` field of the `ApplicationConfig` (passed to the `bootstrapApplication` function) to provide a service or other `Injectable` at the application level. In the example below, the `HeroService` is available to all components, directives, and pipes: <docs-code language="typescript" highlight="[3]"> export const appConfig: ApplicationConfig = { providers: [ { provide: HeroService }, ] }; </docs-code> Then, in `main.ts`: <docs-code language="typescript"> bootstrapApplication(AppComponent, appConfig) </docs-code> Note: Declaring a service like this causes `HeroService` to always be included in your application— even if the service is unused. ### `NgModule` based applications `@NgModule`-based applications use the `providers` field of the `@NgModule` decorator to provide a service or other `Injectable` available at the application level. A service provided in a module is available to all declarations of the module, or to any other modules which share the same `ModuleInjector`. To understand all edge-cases, see [Hierarchical injectors](guide/di/hierarchical-dependency-injection). Note: Declaring a service using `providers` causes the service to be included in your application— even if the service is unused. ## Injecting/consuming a dependency The most common way to inject a dependency is to declare it in a class constructor. When Angular creates a new instance of a component, directive, or pipe class, it determines which services or other dependencies that class needs by looking at the constructor parameter types. For example, if the `HeroListComponent` needs the `HeroService`, the constructor can look like this: <docs-code language="typescript" highlight="[3]"> @Component({ … }) class HeroListComponent { constructor(private service: HeroService) {} } </docs-code> Another option is to use the [inject](api/core/inject) method: <docs-code language="typescript" highlight="[3]"> @Component({ … }) class HeroListComponent { private service = inject(HeroService); } </docs-code> When Angular discovers that a component depends on a service, it first checks if the injector has any existing instances of that service. If a requested service instance doesn't yet exist, the injector creates one using the registered provider, and adds it to the injector before returning the service to Angular. When all requested services have been resolved and returned, Angular can call the component's constructor with those services as arguments. ```mermaid graph TD; subgraph Injector serviceA[Service A] heroService[HeroService] serviceC[Service C] serviceD[Service D] end direction TB componentConstructor["Component\nconstructor(HeroService)"] heroService-->componentConstructor style componentConstructor text-align: left ``` ## What's next <docs-pill-row> <docs-pill href="/guide/di/creating-injectable-service" title="Creating an injectable service"/> </docs-pill-row>
004563
# Injection context The dependency injection (DI) system relies internally on a runtime context where the current injector is available. This means that injectors can only work when code is executed in such a context. The injection context is available in these situations: * During construction (via the `constructor`) of a class being instantiated by the DI system, such as an `@Injectable` or `@Component`. * In the initializer for fields of such classes. * In the factory function specified for `useFactory` of a `Provider` or an `@Injectable`. * In the `factory` function specified for an `InjectionToken`. * Within a stack frame that runs in an injection context. Knowing when you are in an injection context will allow you to use the [`inject`](api/core/inject) function to inject instances. ## Class constructors Every time the DI system instantiates a class, it does so in an injection context. This is handled by the framework itself. The constructor of the class is executed in that runtime context, which also allows injection of a token using the [`inject`](api/core/inject) function. <docs-code language="typescript" highlight="[[3],[6]]"> class MyComponent { private service1: Service1; private service2: Service2 = inject(Service2); // In context constructor() { this.service1 = inject(Service1) // In context } } </docs-code> ## Stack frame in context Some APIs are designed to be run in an injection context. This is the case, for example, with router guards. This allows the use of [`inject`](api/core/inject) within the guard function to access a service. Here is an example for `CanActivateFn` <docs-code language="typescript" highlight="[3]"> const canActivateTeam: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { return inject(PermissionsService).canActivate(inject(UserToken), route.params.id); }; </docs-code> ## Run within an injection context When you want to run a given function in an injection context without already being in one, you can do so with `runInInjectionContext`. This requires access to a given injector, like the `EnvironmentInjector`, for example: <docs-code header="src/app/heroes/hero.service.ts" language="typescript" highlight="[9]"> @Injectable({ providedIn: 'root', }) export class HeroService { private environmentInjector = inject(EnvironmentInjector); someMethod() { runInInjectionContext(this.environmentInjector, () => { inject(SomeService); // Do what you need with the injected service }); } } </docs-code> Note that `inject` will return an instance only if the injector can resolve the required token. ## Asserts the context Angular provides the `assertInInjectionContext` helper function to assert that the current context is an injection context. ## Using DI outside of a context Calling [`inject`](api/core/inject) or calling `assertInInjectionContext` outside of an injection context will throw [error NG0203](/errors/NG0203).
004564
# Hierarchical injectors Injectors in Angular have rules that you can leverage to achieve the desired visibility of injectables in your applications. By understanding these rules, you can determine whether to declare a provider at the application level, in a Component, or in a Directive. The applications you build with Angular can become quite large, and one way to manage this complexity is to split up the application into a well-defined tree of components. There can be sections of your page that work in a completely independent way than the rest of the application, with its own local copies of the services and other dependencies that it needs. Some of the services that these sections of the application use might be shared with other parts of the application, or with parent components that are further up in the component tree, while other dependencies are meant to be private. With hierarchical dependency injection, you can isolate sections of the application and give them their own private dependencies not shared with the rest of the application, or have parent components share certain dependencies with its child components only but not with the rest of the component tree, and so on. Hierarchical dependency injection enables you to share dependencies between different parts of the application only when and if you need to. ## Types of injector hierarchies Angular has two injector hierarchies: | Injector hierarchies | Details | |:--- |:--- | | `EnvironmentInjector` hierarchy | Configure an `EnvironmentInjector` in this hierarchy using `@Injectable()` or `providers` array in `ApplicationConfig`. | | `ElementInjector` hierarchy | Created implicitly at each DOM element. An `ElementInjector` is empty by default unless you configure it in the `providers` property on `@Directive()` or `@Component()`. | <docs-callout title="NgModule Based Applications"> For `NgModule` based applications, you can provide dependencies with the `ModuleInjector` hierarchy using an `@NgModule()` or `@Injectable()` annotation. </docs-callout> ### `EnvironmentInjector` The `EnvironmentInjector` can be configured in one of two ways by using: * The `@Injectable()` `providedIn` property to refer to `root` or `platform` * The `ApplicationConfig` `providers` array <docs-callout title="Tree-shaking and @Injectable()"> Using the `@Injectable()` `providedIn` property is preferable to using the `ApplicationConfig` `providers` array. With `@Injectable()` `providedIn`, optimization tools can perform tree-shaking, which removes services that your application isn't using. This results in smaller bundle sizes. Tree-shaking is especially useful for a library because the application which uses the library may not have a need to inject it. </docs-callout> `EnvironmentInjector` is configured by the `ApplicationConfig.providers`. Provide services using `providedIn` of `@Injectable()` as follows: <docs-code language="typescript" highlight="[4]"> import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' // <--provides this service in the root EnvironmentInjector }) export class ItemService { name = 'telephone'; } </docs-code> The `@Injectable()` decorator identifies a service class. The `providedIn` property configures a specific `EnvironmentInjector`, here `root`, which makes the service available in the `root` `EnvironmentInjector`. ### ModuleInjector In the case of `NgModule` based applications, the ModuleInjector can be configured in one of two ways by using: * The `@Injectable()` `providedIn` property to refer to `root` or `platform` * The `@NgModule()` `providers` array `ModuleInjector` is configured by the `@NgModule.providers` and `NgModule.imports` property. `ModuleInjector` is a flattening of all the providers arrays that can be reached by following the `NgModule.imports` recursively. Child `ModuleInjector` hierarchies are created when lazy loading other `@NgModules`. ### Platform injector There are two more injectors above `root`, an additional `EnvironmentInjector` and `NullInjector()`. Consider how Angular bootstraps the application with the following in `main.ts`: <docs-code language="javascript"> bootstrapApplication(AppComponent, appConfig); </docs-code> The `bootstrapApplication()` method creates a child injector of the platform injector which is configured by the `ApplicationConfig` instance. This is the `root` `EnvironmentInjector`. The `platformBrowserDynamic()` method creates an injector configured by a `PlatformModule`, which contains platform-specific dependencies. This allows multiple applications to share a platform configuration. For example, a browser has only one URL bar, no matter how many applications you have running. You can configure additional platform-specific providers at the platform level by supplying `extraProviders` using the `platformBrowser()` function. The next parent injector in the hierarchy is the `NullInjector()`, which is the top of the tree. If you've gone so far up the tree that you are looking for a service in the `NullInjector()`, you'll get an error unless you've used `@Optional()` because ultimately, everything ends at the `NullInjector()` and it returns an error or, in the case of `@Optional()`, `null`. For more information on `@Optional()`, see the [`@Optional()` section](#optional) of this guide. The following diagram represents the relationship between the `root` `ModuleInjector` and its parent injectors as the previous paragraphs describe. ```mermaid stateDiagram-v2 elementInjector: EnvironmentInjector\n(configured by Angular)\nhas special things like DomSanitizer => providedIn 'platform' rootInjector: root EnvironmentInjector\n(configured by AppConfig)\nhas things for your app => bootstrapApplication(..., AppConfig) nullInjector: NullInjector\nalways throws an error unless\nyou use @Optional() direction BT rootInjector --> elementInjector elementInjector --> nullInjector ``` While the name `root` is a special alias, other `EnvironmentInjector` hierarchies don't have aliases. You have the option to create `EnvironmentInjector` hierarchies whenever a dynamically loaded component is created, such as with the Router, which will create child `EnvironmentInjector` hierarchies. All requests forward up to the root injector, whether you configured it with the `ApplicationConfig` instance passed to the `bootstrapApplication()` method, or registered all providers with `root` in their own services. <docs-callout title="@Injectable() vs. ApplicationConfig"> If you configure an app-wide provider in the `ApplicationConfig` of `bootstrapApplication`, it overrides one configured for `root` in the `@Injectable()` metadata. You can do this to configure a non-default provider of a service that is shared with multiple applications. Here is an example of the case where the component router configuration includes a non-default [location strategy](guide/routing#location-strategy) by listing its provider in the `providers` list of the `ApplicationConfig`. ```ts providers: [ { provide: LocationStrategy, useClass: HashLocationStrategy } ] ``` For `NgModule` based applications, configure app-wide providers in the `AppModule` `providers`. </docs-callout> ### `ElementInjector` Angular creates `ElementInjector` hierarchies implicitly for each DOM element. Providing a service in the `@Component()` decorator using its `providers` or `viewProviders` property configures an `ElementInjector`. For example, the following `TestComponent` configures the `ElementInjector` by providing the service as follows: <docs-code language="typescript" highlight="[3]"> @Component({ … providers: [{ provide: ItemService, useValue: { name: 'lamp' } }] }) export class TestComponent </docs-code> HELPFUL: See the [resolution rules](#resolution-rules) section to understand the relationship between the `EnvironmentInjector` tree, the `ModuleInjector` and the `ElementInjector` tree. When you provide services in a component, that service is available by way of the `ElementInjector` at that component instance. It may also be visible at child component/directives based on visibility rules described in the [resolution rules](#resolution-rules) section. When the component instance is destroyed, so is that service instance. #### `@Directive()` and `@Component()` A component is a special type of directive, which means that just as `@Directive()` has a `providers` property, `@Component()` does too. This means that directives as well as components can configure providers, using the `providers` property. When you configure a provider for a component or directive using the `providers` property, that provider belongs to the `ElementInjector` of that component or directive. Components and directives on the same element share an injector. ##
004571
ses The ability to configure one or more providers at different levels opens up useful possibilities. ### Scenario: service isolation Architectural reasons may lead you to restrict access to a service to the application domain where it belongs. For example, consider we build a `VillainsListComponent` that displays a list of villains. It gets those villains from a `VillainsService`. If you provide `VillainsService` in the root `AppModule`, it will make `VillainsService` visible everywhere in the application. If you later modify the `VillainsService`, you could break something in other components that started depending this service by accident. Instead, you should provide the `VillainsService` in the `providers` metadata of the `VillainsListComponent` like this: <docs-code header="src/app/villains-list.component.ts (metadata)" language="typescript" highlight="[4]"> @Component({ selector: 'app-villains-list', templateUrl: './villains-list.component.html', providers: [VillainsService] }) export class VillainsListComponent {} </docs-code> By providing `VillainsService` in the `VillainsListComponent` metadata and nowhere else, the service becomes available only in the `VillainsListComponent` and its subcomponent tree. `VillainService` is a singleton with respect to `VillainsListComponent` because that is where it is declared. As long as `VillainsListComponent` does not get destroyed it will be the same instance of `VillainService` but if there are multiple instances of `VillainsListComponent`, then each instance of `VillainsListComponent` will have its own instance of `VillainService`. ### Scenario: multiple edit sessions Many applications allow users to work on several open tasks at the same time. For example, in a tax preparation application, the preparer could be working on several tax returns, switching from one to the other throughout the day. To demonstrate that scenario, imagine a `HeroListComponent` that displays a list of super heroes. To open a hero's tax return, the preparer clicks on a hero name, which opens a component for editing that return. Each selected hero tax return opens in its own component and multiple returns can be open at the same time. Each tax return component has the following characteristics: * Is its own tax return editing session * Can change a tax return without affecting a return in another component * Has the ability to save the changes to its tax return or cancel them Suppose that the `HeroTaxReturnComponent` had logic to manage and restore changes. That would be a straightforward task for a hero tax return. In the real world, with a rich tax return data model, the change management would be tricky. You could delegate that management to a helper service, as this example does. The `HeroTaxReturnService` caches a single `HeroTaxReturn`, tracks changes to that return, and can save or restore it. It also delegates to the application-wide singleton `HeroService`, which it gets by injection. <docs-code header="src/app/hero-tax-return.service.ts" language="typescript"> import { Injectable } from '@angular/core'; import { HeroTaxReturn } from './hero'; import { HeroesService } from './heroes.service'; @Injectable() export class HeroTaxReturnService { private currentTaxReturn!: HeroTaxReturn; private originalTaxReturn!: HeroTaxReturn; constructor(private heroService: HeroesService) {} set taxReturn(htr: HeroTaxReturn) { this.originalTaxReturn = htr; this.currentTaxReturn = htr.clone(); } get taxReturn(): HeroTaxReturn { return this.currentTaxReturn; } restoreTaxReturn() { this.taxReturn = this.originalTaxReturn; } saveTaxReturn() { this.taxReturn = this.currentTaxReturn; this.heroService.saveTaxReturn(this.currentTaxReturn).subscribe(); } } </docs-code> Here is the `HeroTaxReturnComponent` that makes use of `HeroTaxReturnService`. <docs-code header="src/app/hero-tax-return.component.ts" language="typescript"> import { Component, EventEmitter, Input, Output } from '@angular/core'; import { HeroTaxReturn } from './hero'; import { HeroTaxReturnService } from './hero-tax-return.service'; @Component({ selector: 'app-hero-tax-return', templateUrl: './hero-tax-return.component.html', styleUrls: [ './hero-tax-return.component.css' ], providers: [ HeroTaxReturnService ] }) export class HeroTaxReturnComponent { message = ''; @Output() close = new EventEmitter<void>(); get taxReturn(): HeroTaxReturn { return this.heroTaxReturnService.taxReturn; } @Input() set taxReturn(htr: HeroTaxReturn) { this.heroTaxReturnService.taxReturn = htr; } constructor(private heroTaxReturnService: HeroTaxReturnService) {} onCanceled() { this.flashMessage('Canceled'); this.heroTaxReturnService.restoreTaxReturn(); } onClose() { this.close.emit(); } onSaved() { this.flashMessage('Saved'); this.heroTaxReturnService.saveTaxReturn(); } flashMessage(msg: string) { this.message = msg; setTimeout(() => this.message = '', 500); } } </docs-code> The _tax-return-to-edit_ arrives by way of the `@Input()` property, which is implemented with getters and setters. The setter initializes the component's own instance of the `HeroTaxReturnService` with the incoming return. The getter always returns what that service says is the current state of the hero. The component also asks the service to save and restore this tax return. This won't work if the service is an application-wide singleton. Every component would share the same service instance, and each component would overwrite the tax return that belonged to another hero. To prevent this, configure the component-level injector of `HeroTaxReturnComponent` to provide the service, using the `providers` property in the component metadata. <docs-code header="src/app/hero-tax-return.component.ts (providers)" language="typescript"> providers: [HeroTaxReturnService] </docs-code> The `HeroTaxReturnComponent` has its own provider of the `HeroTaxReturnService`. Recall that every component _instance_ has its own injector. Providing the service at the component level ensures that _every_ instance of the component gets a private instance of the service. This makes sure that no tax return gets overwritten. HELPFUL: The rest of the scenario code relies on other Angular features and techniques that you can learn about elsewhere in the documentation. ### Scenario: specialized providers Another reason to provide a service again at another level is to substitute a _more specialized_ implementation of that service, deeper in the component tree. For example, consider a `Car` component that includes tire service information and depends on other services to provide more details about the car. The root injector, marked as (A), uses _generic_ providers for details about `CarService` and `EngineService`. 1. `Car` component (A). Component (A) displays tire service data about a car and specifies generic services to provide more information about the car. 2. Child component (B). Component (B) defines its own, _specialized_ providers for `CarService` and `EngineService` that have special capabilities suitable for what's going on in component (B). 3. Child component (C) as a child of Component (B). Component (C) defines its own, even _more specialized_ provider for `CarService`. ```mermaid graph TD; subgraph COMPONENT_A[Component A] subgraph COMPONENT_B[Component B] COMPONENT_C[Component C] end end style COMPONENT_A fill:#BDD7EE style COMPONENT_B fill:#FFE699 style COMPONENT_C fill:#A9D18E,color:#000 classDef noShadow filter:none class COMPONENT_A,COMPONENT_B,COMPONENT_C noShadow ``` Behind the scenes, each component sets up its own injector with zero, one, or more providers defined for that component itself. When you resolve an instance of `Car` at the deepest component (C), its injector produces: * An instance of `Car` resolved by injector (C) * An `Engine` resolved by injector (B) * Its `Tires` resolved by the root injector (A). ```mermaid graph BT; subgraph A[" "] direction LR RootInjector["(A) RootInjector"] ServicesA["CarService, EngineService, TiresService"] end subgraph B[" "] direction LR ParentInjector["(B) ParentInjector"] ServicesB["CarService2, EngineService2"] end subgraph C[" "] direction LR ChildInjector["(C) ChildInjector"] ServicesC["CarService3"] end direction LR car["(C) Car"] engine["(B) Engine"] tires["(A) Tires"] direction BT car-->ChildInjector ChildInjector-->ParentInjector-->RootInjector class car,engine,tires,RootInjector,ParentInjector,ChildInjector,ServicesA,ServicesB,ServicesC,A,B,C noShadow style car fill:#A9D18E,color:#000 style ChildInjector fill:#A9D18E,color:#000 style engine fill:#FFE699,color:#000 style ParentInjector fill:#FFE699,color:#000 style tires fill:#BDD7EE,color:#000 style RootInjector fill:#BDD7EE,color:#000 ``` ## More on dependency injection <do
004576
## Data flow in forms When an application contains a form, Angular must keep the view in sync with the component model and the component model in sync with the view. As users change values and make selections through the view, the new values must be reflected in the data model. Similarly, when the program logic changes values in the data model, those values must be reflected in the view. Reactive and template-driven forms differ in how they handle data flowing from the user or from programmatic changes. The following diagrams illustrate both kinds of data flow for each type of form, using the favorite-color input field defined above. ### Data flow in reactive forms In reactive forms each form element in the view is directly linked to the form model (a `FormControl` instance). Updates from the view to the model and from the model to the view are synchronous and do not depend on how the UI is rendered. The view-to-model diagram shows how data flows when an input field's value is changed from the view through the following steps. 1. The user types a value into the input element, in this case the favorite color *Blue*. 1. The form input element emits an "input" event with the latest value. 1. The `ControlValueAccessor` listening for events on the form input element immediately relays the new value to the `FormControl` instance. 1. The `FormControl` instance emits the new value through the `valueChanges` observable. 1. Any subscribers to the `valueChanges` observable receive the new value. ```mermaid flowchart TB U{User} I("<input>") CVA(ControlValueAccessor) FC(FormControl) O(Observers) U-->|Types in the input box|I I-->|Fires the 'input' event|CVA CVA-->|"Calls setValue() on the FormControl"|FC FC-.->|Fires a 'valueChanges' event to observers|O ``` The model-to-view diagram shows how a programmatic change to the model is propagated to the view through the following steps. 1. The user calls the `favoriteColorControl.setValue()` method, which updates the `FormControl` value. 1. The `FormControl` instance emits the new value through the `valueChanges` observable. 1. Any subscribers to the `valueChanges` observable receive the new value. 1. The control value accessor on the form input element updates the element with the new value. ```mermaid flowchart TB U{User} I(<input>) CVA(ControlValueAccessor) FC(FormControl) O(Observers) U-->|"Calls setValue() on the FormControl"|FC FC-->|Notifies the ControlValueAccessor|CVA FC-.->|Fires a 'valueChanges' event to observers|O CVA-->|"Updates the value of the <input>"|I ``` ### Data flow in template-driven forms In template-driven forms, each form element is linked to a directive that manages the form model internally. The view-to-model diagram shows how data flows when an input field's value is changed from the view through the following steps. 1. The user types *Blue* into the input element. 1. The input element emits an "input" event with the value *Blue*. 1. The control value accessor attached to the input triggers the `setValue()` method on the `FormControl` instance. 1. The `FormControl` instance emits the new value through the `valueChanges` observable. 1. Any subscribers to the `valueChanges` observable receive the new value. 1. The control value accessor also calls the `NgModel.viewToModelUpdate()` method which emits an `ngModelChange` event. 1. Because the component template uses two-way data binding for the `favoriteColor` property, the `favoriteColor` property in the component is updated to the value emitted by the `ngModelChange` event \(*Blue*\). ```mermaid flowchart TB U{User} I(<input>) CVA(ControlValueAccessor) FC(FormControl) M(NgModel) O(Observers) C(Component) P(Two-way binding) U-->|Types in the input box|I I-->|Fires the 'input' event|CVA CVA-->|"Calls setValue() on the FormControl"|FC FC-.->|Fires a 'valueChanges' event to observers|O CVA-->|"Calls viewToModelUpdate()"|M M-->|Emits an ngModelChange event|C C-->|Updates the value of the two-way bound property|P ``` The model-to-view diagram shows how data flows from model to view when the `favoriteColor` changes from *Blue* to *Red*, through the following steps 1. The `favoriteColor` value is updated in the component. 1. Change detection begins. 1. During change detection, the `ngOnChanges` lifecycle hook is called on the `NgModel` directive instance because the value of one of its inputs has changed. 1. The `ngOnChanges()` method queues an async task to set the value for the internal `FormControl` instance. 1. Change detection completes. 1. On the next tick, the task to set the `FormControl` instance value is executed. 1. The `FormControl` instance emits the latest value through the `valueChanges` observable. 1. Any subscribers to the `valueChanges` observable receive the new value. 1. The control value accessor updates the form input element in the view with the latest `favoriteColor` value. ```mermaid flowchart TB C(Component) P(Property bound to NgModel) C-->|Updates the property value|P P-->|Triggers CD|CD1 subgraph CD1 [First Change Detection] direction TB M(NgModel) FC(FormControl) M-->|Asynchronously sets FormControl value|FC end CD1-->|Async actions trigger a second round of Change Detection|CD2 subgraph CD2 [Second Change Detection] direction TB FC2(FormControl) O(Observers) CVA(ControlValueAccessor) I("<input>") FC2-.->|Fires a 'valueChanges' event to observers|O O-->|ControlValueAccessor receives valueChanges event|CVA CVA-->|Sets the value in the control|I end ``` Note: `NgModel` triggers a second change detection to avoid `ExpressionChangedAfterItHasBeenChecked` errors, because the value change originates in an input binding. ### Mutability of the data model The change-tracking method plays a role in the efficiency of your application. | Forms | Details | |:--- |:--- | | Reactive forms | Keep the data model pure by providing it as an immutable data structure. Each time a change is triggered on the data model, the `FormControl` instance returns a new data model rather than updating the existing data model. This gives you the ability to track unique changes to the data model through the control's observable. Change detection is more efficient because it only needs to update on unique changes. Because data updates follow reactive patterns, you can integrate with observable operators to transform data. | | Template-driven forms | Rely on mutability with two-way data binding to update the data model in the component as changes are made in the template. Because there are no unique changes to track on the data model when using two-way data binding, change detection is less efficient at determining when updates are required. | The difference is demonstrated in the previous examples that use the favorite-color input element. * With reactive forms, the **`FormControl` instance** always returns a new value when the control's value is updated * With template-driven forms, the **favorite color property** is always modified to its new value ## Form validation Validation is an integral part of managing any set of forms. Whether you're checking for required fields or querying an external API for an existing username, Angular provides a set of built-in validators as well as the ability to create custom validators. | Forms | Details | |:--- |:--- | | Reactive forms | Define custom validators as **functions** that receive a control to validate | | Template-driven forms | Tied to template **directives**, and must provide custom validator directives that wrap validation functions | For more information, see [Form Validation](guide/forms/form-validation#validating-input-in-reactive-forms).
004581
ing asynchronous validators Asynchronous validators implement the `AsyncValidatorFn` and `AsyncValidator` interfaces. These are very similar to their synchronous counterparts, with the following differences. * The `validate()` functions must return a Promise or an observable, * The observable returned must be finite, meaning it must complete at some point. To convert an infinite observable into a finite one, pipe the observable through a filtering operator such as `first`, `last`, `take`, or `takeUntil`. Asynchronous validation happens after the synchronous validation, and is performed only if the synchronous validation is successful. This check lets forms avoid potentially expensive async validation processes \(such as an HTTP request\) if the more basic validation methods have already found invalid input. After asynchronous validation begins, the form control enters a `pending` state. Inspect the control's `pending` property and use it to give visual feedback about the ongoing validation operation. A common UI pattern is to show a spinner while the async validation is being performed. The following example shows how to achieve this in a template-driven form. <docs-code language="html"> <input [(ngModel)]="name" #model="ngModel" appSomeAsyncValidator> <app-spinner *ngIf="model.pending"></app-spinner> </docs-code> ### Implementing a custom async validator In the following example, an async validator ensures that actors are cast for a role that is not already taken. New actors are constantly auditioning and old actors are retiring, so the list of available roles cannot be retrieved ahead of time. To validate the potential role entry, the validator must initiate an asynchronous operation to consult a central database of all currently cast actors. The following code creates the validator class, `UniqueRoleValidator`, which implements the `AsyncValidator` interface. <docs-code path="adev/src/content/examples/form-validation/src/app/shared/role.directive.ts" visibleRegion="async-validator"/> The constructor injects the `ActorsService`, which defines the following interface. <docs-code language="typescript"> interface ActorsService { isRoleTaken: (role: string) => Observable<boolean>; } </docs-code> In a real world application, the `ActorsService` would be responsible for making an HTTP request to the actor database to check if the role is available. From the validator's point of view, the actual implementation of the service is not important, so the example can just code against the `ActorsService` interface. As the validation begins, the `UnambiguousRoleValidator` delegates to the `ActorsService` `isRoleTaken()` method with the current control value. At this point the control is marked as `pending` and remains in this state until the observable chain returned from the `validate()` method completes. The `isRoleTaken()` method dispatches an HTTP request that checks if the role is available, and returns `Observable<boolean>` as the result. The `validate()` method pipes the response through the `map` operator and transforms it into a validation result. The method then, like any validator, returns `null` if the form is valid, and `ValidationErrors` if it is not. This validator handles any potential errors with the `catchError` operator. In this case, the validator treats the `isRoleTaken()` error as a successful validation, because failure to make a validation request does not necessarily mean that the role is invalid. You could handle the error differently and return the `ValidationError` object instead. After some time passes, the observable chain completes and the asynchronous validation is done. The `pending` flag is set to `false`, and the form validity is updated. ### Adding async validators to reactive forms To use an async validator in reactive forms, begin by injecting the validator into the constructor of the component class. <docs-code path="adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.2.ts" visibleRegion="async-validator-inject"/> Then, pass the validator function directly to the `FormControl` to apply it. In the following example, the `validate` function of `UnambiguousRoleValidator` is applied to `roleControl` by passing it to the control's `asyncValidators` option and binding it to the instance of `UnambiguousRoleValidator` that was injected into `ActorFormReactiveComponent`. The value of `asyncValidators` can be either a single async validator function, or an array of functions. To learn more about `FormControl` options, see the [AbstractControlOptions](api/forms/AbstractControlOptions) API reference. <docs-code path="adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.2.ts" visibleRegion="async-validator-usage"/> ### Adding async validators to template-driven forms To use an async validator in template-driven forms, create a new directive and register the `NG_ASYNC_VALIDATORS` provider on it. In the example below, the directive injects the `UniqueRoleValidator` class that contains the actual validation logic and invokes it in the `validate` function, triggered by Angular when validation should happen. <docs-code path="adev/src/content/examples/form-validation/src/app/shared/role.directive.ts" visibleRegion="async-validator-directive"/> Then, as with synchronous validators, add the directive's selector to an input to activate it. <docs-code header="template/actor-form-template.component.html (unique-unambiguous-role-input)" path="adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.html" visibleRegion="role-input"/> ### Optimizing performance of async validators By default, all validators run after every form value change. With synchronous validators, this does not normally have a noticeable impact on application performance. Async validators, however, commonly perform some kind of HTTP request to validate the control. Dispatching an HTTP request after every keystroke could put a strain on the backend API, and should be avoided if possible. You can delay updating the form validity by changing the `updateOn` property from `change` (default) to `submit` or `blur`. With template-driven forms, set the property in the template. <docs-code language="html"> <input [(ngModel)]="name" [ngModelOptions]="{updateOn: 'blur'}"> </docs-code> With reactive forms, set the property in the `FormControl` instance. <docs-code language="typescript"> new FormControl('', {updateOn: 'blur'}); </docs-code> ## Interaction with native HTML form validation By default, Angular disables [native HTML form validation](https://developer.mozilla.org/docs/Web/Guide/HTML/Constraint_validation) by adding the `novalidate` attribute on the enclosing `<form>` and uses directives to match these attributes with validator functions in the framework. If you want to use native validation **in combination** with Angular-based validation, you can re-enable it with the `ngNativeValidate` directive. See the [API docs](api/forms/NgForm#native-dom-validation-ui) for details.
004584
### Updating parts of the data model When updating the value for a form group instance that contains multiple controls, you might only want to update parts of the model. This section covers how to update specific parts of a form control data model. There are two ways to update the model value: | Methods | Details | |:--- |:--- | | `setValue()` | Set a new value for an individual control. The `setValue()` method strictly adheres to the structure of the form group and replaces the entire value for the control. | | `patchValue()` | Replace any properties defined in the object that have changed in the form model. | The strict checks of the `setValue()` method help catch nesting errors in complex forms, while `patchValue()` fails silently on those errors. In `ProfileEditorComponent`, use the `updateProfile` method with the following example to update the first name and street address for the user. <docs-code header="src/app/profile-editor/profile-editor.component.ts (patch value)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.1.ts" visibleRegion="patch-value"/> Simulate an update by adding a button to the template to update the user profile on demand. <docs-code header="src/app/profile-editor/profile-editor.component.html (update value)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.1.html" visibleRegion="patch-value"/> When a user clicks the button, the `profileForm` model is updated with new values for `firstName` and `street`. Notice that `street` is provided in an object inside the `address` property. This is necessary because the `patchValue()` method applies the update against the model structure. `PatchValue()` only updates properties that the form model defines. ## Using the FormBuilder service to generate controls Creating form control instances manually can become repetitive when dealing with multiple forms. The `FormBuilder` service provides convenient methods for generating controls. Use the following steps to take advantage of this service. 1. Import the `FormBuilder` class. 1. Inject the `FormBuilder` service. 1. Generate the form contents. The following examples show how to refactor the `ProfileEditor` component to use the form builder service to create form control and form group instances. <docs-workflow> <docs-step title="Import the FormBuilder class"> Import the `FormBuilder` class from the `@angular/forms` package. <docs-code header="src/app/profile-editor/profile-editor.component.ts (import)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.2.ts" visibleRegion="form-builder-imports"/> </docs-step> <docs-step title="Inject the FormBuilder service"> The `FormBuilder` service is an injectable provider from the reactive forms module. Use the `inject()` function to inject this dependency in your component. <docs-code header="src/app/profile-editor/profile-editor.component.ts (constructor)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.2.ts" visibleRegion="inject-form-builder"/> </docs-step> <docs-step title="Generate form controls"> The `FormBuilder` service has three methods: `control()`, `group()`, and `array()`. These are factory methods for generating instances in your component classes including form controls, form groups, and form arrays. Use the `group` method to create the `profileForm` controls. <docs-code header="src/app/profile-editor/profile-editor.component.ts (form builder)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.2.ts" visibleRegion="form-builder"/> In the preceding example, you use the `group()` method with the same object to define the properties in the model. The value for each control name is an array containing the initial value as the first item in the array. Tip: You can define the control with just the initial value, but if your controls need sync or async validation, add sync and async validators as the second and third items in the array. Compare using the form builder to creating the instances manually. <docs-code-multifile> <docs-code header="src/app/profile-editor/profile-editor.component.ts (instances)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.1.ts" visibleRegion="formgroup-compare"/> <docs-code header="src/app/profile-editor/profile-editor.component.ts (form builder)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.2.ts" visibleRegion="formgroup-compare"/> </docs-code-multifile> </docs-step> </docs-workflow> ## Validating form input *Form validation* is used to ensure that user input is complete and correct. This section covers adding a single validator to a form control and displaying the overall form status. Form validation is covered more extensively in the [Form Validation](guide/forms/form-validation) guide. Use the following steps to add form validation. 1. Import a validator function in your form component. 1. Add the validator to the field in the form. 1. Add logic to handle the validation status. The most common validation is making a field required. The following example shows how to add a required validation to the `firstName` control and display the result of validation. <docs-workflow> <docs-step title="Import a validator function"> Reactive forms include a set of validator functions for common use cases. These functions receive a control to validate against and return an error object or a null value based on the validation check. Import the `Validators` class from the `@angular/forms` package. <docs-code header="src/app/profile-editor/profile-editor.component.ts (import)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.ts" visibleRegion="validator-imports"/> </docs-step> <docs-step title="Make a field required"> In the `ProfileEditor` component, add the `Validators.required` static method as the second item in the array for the `firstName` control. <docs-code header="src/app/profile-editor/profile-editor.component.ts (required validator)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.ts" visibleRegion="required-validator"/> </docs-step> <docs-step title="Display form status"> When you add a required field to the form control, its initial status is invalid. This invalid status propagates to the parent form group element, making its status invalid. Access the current status of the form group instance through its `status` property. Display the current status of `profileForm` using interpolation. <docs-code header="src/app/profile-editor/profile-editor.component.html (display status)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.html" visibleRegion="display-status"/> The **Submit** button is disabled because `profileForm` is invalid due to the required `firstName` form control. After you fill out the `firstName` input, the form becomes valid and the **Submit** button is enabled. For more on form validation, visit the [Form Validation](guide/forms/form-validation) guide. </docs-step> </docs-workflow>
004585
## Creating dynamic forms `FormArray` is an alternative to `FormGroup` for managing any number of unnamed controls. As with form group instances, you can dynamically insert and remove controls from form array instances, and the form array instance value and validation status is calculated from its child controls. However, you don't need to define a key for each control by name, so this is a great option if you don't know the number of child values in advance. To define a dynamic form, take the following steps. 1. Import the `FormArray` class. 1. Define a `FormArray` control. 1. Access the `FormArray` control with a getter method. 1. Display the form array in a template. The following example shows you how to manage an array of *aliases* in `ProfileEditor`. <docs-workflow> <docs-step title="Import the `FormArray` class"> Import the `FormArray` class from `@angular/forms` to use for type information. The `FormBuilder` service is ready to create a `FormArray` instance. <docs-code header="src/app/profile-editor/profile-editor.component.ts (import)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.2.ts" visibleRegion="form-array-imports"/> </docs-step> <docs-step title="Define a `FormArray` control"> You can initialize a form array with any number of controls, from zero to many, by defining them in an array. Add an `aliases` property to the form group instance for `profileForm` to define the form array. Use the `FormBuilder.array()` method to define the array, and the `FormBuilder.control()` method to populate the array with an initial control. <docs-code header="src/app/profile-editor/profile-editor.component.ts (aliases form array)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.ts" visibleRegion="aliases"/> The aliases control in the form group instance is now populated with a single control until more controls are added dynamically. </docs-step> <docs-step title="Access the `FormArray` control"> A getter provides access to the aliases in the form array instance compared to repeating the `profileForm.get()` method to get each instance. The form array instance represents an undefined number of controls in an array. It's convenient to access a control through a getter, and this approach is straightforward to repeat for additional controls. <br /> Use the getter syntax to create an `aliases` class property to retrieve the alias's form array control from the parent form group. <docs-code header="src/app/profile-editor/profile-editor.component.ts (aliases getter)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.ts" visibleRegion="aliases-getter"/> Because the returned control is of the type `AbstractControl`, you need to provide an explicit type to access the method syntax for the form array instance. Define a method to dynamically insert an alias control into the alias's form array. The `FormArray.push()` method inserts the control as a new item in the array. <docs-code header="src/app/profile-editor/profile-editor.component.ts (add alias)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.ts" visibleRegion="add-alias"/> In the template, each control is displayed as a separate input field. </docs-step> <docs-step title="Display the form array in the template"> To attach the aliases from your form model, you must add it to the template. Similar to the `formGroupName` input provided by `FormGroupNameDirective`, `formArrayName` binds communication from the form array instance to the template with `FormArrayNameDirective`. Add the following template HTML after the `<div>` closing the `formGroupName` element. <docs-code header="src/app/profile-editor/profile-editor.component.html (aliases form array template)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.html" visibleRegion="formarrayname"/> The `*ngFor` directive iterates over each form control instance provided by the aliases form array instance. Because form array elements are unnamed, you assign the index to the `i` variable and pass it to each control to bind it to the `formControlName` input. Each time a new alias instance is added, the new form array instance is provided its control based on the index. This lets you track each individual control when calculating the status and value of the root control. </docs-step> <docs-step title="Add an alias"> Initially, the form contains one `Alias` field. To add another field, click the **Add Alias** button. You can also validate the array of aliases reported by the form model displayed by `Form Value` at the bottom of the template. Instead of a form control instance for each alias, you can compose another form group instance with additional fields. The process of defining a control for each item is the same. </docs-step> </docs-workflow> ## Reactive forms API summary The following table lists the base classes and services used to create and manage reactive form controls. For complete syntax details, see the API reference documentation for the [Forms package](api#forms "API reference"). ### Classes | Class | Details | |:--- |:--- | | `AbstractControl` | The abstract base class for the concrete form control classes `FormControl`, `FormGroup`, and `FormArray`. It provides their common behaviors and properties. | | `FormControl` | Manages the value and validity status of an individual form control. It corresponds to an HTML form control such as `<input>` or `<select>`. | | `FormGroup` | Manages the value and validity state of a group of `AbstractControl` instances. The group's properties include its child controls. The top-level form in your component is `FormGroup`. | | `FormArray` | Manages the value and validity state of a numerically indexed array of `AbstractControl` instances. | | `FormBuilder` | An injectable service that provides factory methods for creating control instances. | | `FormRecord` | Tracks the value and validity state of a collection of `FormControl` instances, each of which has the same value type. | ### Directives | Directive | Details | |:--- |:--- | | `FormControlDirective` | Syncs a standalone `FormControl` instance to a form control element. | | `FormControlName` | Syncs `FormControl` in an existing `FormGroup` instance to a form control element by name. | | `FormGroupDirective` | Syncs an existing `FormGroup` instance to a DOM element. | | `FormGroupName` | Syncs a nested `FormGroup` instance to a DOM element. | | `FormArrayName` | Syncs a nested `FormArray` instance to a DOM element. |
004586
# Building a template-driven form This tutorial shows you how to create a template-driven form. The control elements in the form are bound to data properties that have input validation. The input validation helps maintain data integrity and styling to improve the user experience. Template-driven forms use [two-way data binding](guide/templates/two-way-binding) to update the data model in the component as changes are made in the template and vice versa. <docs-callout helpful title="Template vs Reactive forms"> Angular supports two design approaches for interactive forms. Template-driven forms allow you to use form-specific directives in your Angular template. Reactive forms provide a model-driven approach to building forms. Template-driven forms are a great choice for small or simple forms, while reactive forms are more scalable and suitable for complex forms. For a comparison of the two approaches, see [Choosing an approach](guide/forms#choosing-an-approach) </docs-callout> You can build almost any kind of form with an Angular template —login forms, contact forms, and pretty much any business form. You can lay out the controls creatively and bind them to the data in your object model. You can specify validation rules and display validation errors, conditionally allow input from specific controls, trigger built-in visual feedback, and much more. ## Objectives This tutorial teaches you how to do the following: - Build an Angular form with a component and template - Use `ngModel` to create two-way data bindings for reading and writing input-control values - Provide visual feedback using special CSS classes that track the state of the controls - Display validation errors to users and conditionally allow input from form controls based on the form status - Share information across HTML elements using [template reference variables](guide/templates/variables#template-reference-variables) ## Build a template-driven form Template-driven forms rely on directives defined in the `FormsModule`. | Directives | Details | | :------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `NgModel` | Reconciles value changes in the attached form element with changes in the data model, allowing you to respond to user input with input validation and error handling. | | `NgForm` | Creates a top-level `FormGroup` instance and binds it to a `<form>` element to track aggregated form value and validation status. As soon as you import `FormsModule`, this directive becomes active by default on all `<form>` tags. You don't need to add a special selector. | | `NgModelGroup` | Creates and binds a `FormGroup` instance to a DOM element. | ### Step overview In the course of this tutorial, you bind a sample form to data and handle user input using the following steps. 1. Build the basic form. - Define a sample data model - Include required infrastructure such as the `FormsModule` 1. Bind form controls to data properties using the `ngModel` directive and two-way data-binding syntax. - Examine how `ngModel` reports control states using CSS classes - Name controls to make them accessible to `ngModel` 1. Track input validity and control status using `ngModel`. - Add custom CSS to provide visual feedback on the status - Show and hide validation-error messages 1. Respond to a native HTML button-click event by adding to the model data. 1. Handle form submission using the [`ngSubmit`](api/forms/NgForm#properties) output property of the form. - Disable the **Submit** button until the form is valid - After submit, swap out the finished form for different content on the page ## Build the form <!-- TODO: link to preview --> <!-- <docs-code live/> --> 1. The provided sample application creates the `Actor` class which defines the data model reflected in the form. <docs-code header="src/app/actor.ts" language="typescript" path="adev/src/content/examples/forms/src/app/actor.ts"/> 1. The form layout and details are defined in the `ActorFormComponent` class. <docs-code header="src/app/actor-form/actor-form.component.ts (v1)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.ts" visibleRegion="v1"/> The component's `selector` value of "app-actor-form" means you can drop this form in a parent template using the `<app-actor-form>` tag. 1. The following code creates a new actor instance, so that the initial form can show an example actor. <docs-code language="typescript" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.ts" language="typescript" visibleRegion="Marilyn"/> This demo uses dummy data for `model` and `skills`. In a real app, you would inject a data service to get and save real data, or expose these properties as inputs and outputs. 1. The application enables the Forms feature and registers the created form component. <docs-code header="src/app/app.module.ts" language="typescript" path="adev/src/content/examples/forms/src/app/app.module.ts"/> 1. The form is displayed in the application layout defined by the root component's template. <docs-code header="src/app/app.component.html" language="html" path="adev/src/content/examples/forms/src/app/app.component.html"/> The initial template defines the layout for a form with two form groups and a submit button. The form groups correspond to two properties of the Actor data model, name and studio. Each group has a label and a box for user input. - The **Name** `<input>` control element has the HTML5 `required` attribute - The **Studio** `<input>` control element does not because `studio` is optional The **Submit** button has some classes on it for styling. At this point, the form layout is all plain HTML5, with no bindings or directives. 1. The sample form uses some style classes from [Twitter Bootstrap](https://getbootstrap.com/css): `container`, `form-group`, `form-control`, and `btn`. To use these styles, the application's style sheet imports the library. <docs-code header="src/styles.css" path="adev/src/content/examples/forms/src/styles.1.css"/> 1. The form requires that an actor's skill is chosen from a predefined list of `skills` maintained internally in `ActorFormComponent`. The Angular [NgForOf directive](api/common/NgForOf 'API reference') iterates over the data values to populate the `<select>` element. <docs-code header="src/app/actor-form/actor-form.component.html (skills)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="skills"/> If you run the application right now, you see the list of skills in the selection control. The input elements are not yet bound to data values or events, so they are still blank and have no behavior. ##
004587
Bind input controls to data properties The next step is to bind the input controls to the corresponding `Actor` properties with two-way data binding, so that they respond to user input by updating the data model, and also respond to programmatic changes in the data by updating the display. The `ngModel` directive declared in the `FormsModule` lets you bind controls in your template-driven form to properties in your data model. When you include the directive using the syntax for two-way data binding, `[(ngModel)]`, Angular can track the value and user interaction of the control and keep the view synced with the model. 1. Edit the template file `actor-form.component.html`. 1. Find the `<input>` tag next to the **Name** label. 1. Add the `ngModel` directive, using two-way data binding syntax `[(ngModel)]="..."`. <docs-code header="src/app/actor-form/actor-form.component.html (excerpt)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="ngModelName-1"/> HELPFUL: This example has a temporary diagnostic interpolation after each input tag, `{{model.name}}`, to show the current data value of the corresponding property. The comment reminds you to remove the diagnostic lines when you have finished observing the two-way data binding at work. ### Access the overall form status When you imported the `FormsModule` in your component, Angular automatically created and attached an [NgForm](api/forms/NgForm) directive to the `<form>` tag in the template (because `NgForm` has the selector `form` that matches `<form>` elements). To get access to the `NgForm` and the overall form status, declare a [template reference variable](guide/templates/variables#template-reference-variables). 1. Edit the template file `actor-form.component.html`. 1. Update the `<form>` tag with a template reference variable, `#actorForm`, and set its value as follows. <docs-code header="src/app/actor-form/actor-form.component.html (excerpt)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="template-variable"/> The `actorForm` template variable is now a reference to the `NgForm` directive instance that governs the form as a whole. 1. Run the app. 1. Start typing in the **Name** input box. As you add and delete characters, you can see them appear and disappear from the data model. The diagnostic line that shows interpolated values demonstrates that values are really flowing from the input box to the model and back again. ### Naming control elements When you use `[(ngModel)]` on an element, you must define a `name` attribute for that element. Angular uses the assigned name to register the element with the `NgForm` directive attached to the parent `<form>` element. The example added a `name` attribute to the `<input>` element and set it to "name", which makes sense for the actor's name. Any unique value will do, but using a descriptive name is helpful. 1. Add similar `[(ngModel)]` bindings and `name` attributes to **Studio** and **Skill**. 1. You can now remove the diagnostic messages that show interpolated values. 1. To confirm that two-way data binding works for the entire actor model, add a new text binding with the [`json`](api/common/JsonPipe) pipe at the top to the component's template, which serializes the data to a string. After these revisions, the form template should look like the following: <docs-code header="src/app/actor-form/actor-form.component.html (excerpt)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="ngModel-2"/> You'll notice that: - Each `<input>` element has an `id` property. This is used by the `<label>` element's `for` attribute to match the label to its input control. This is a [standard HTML feature](https://developer.mozilla.org/docs/Web/HTML/Element/label). - Each `<input>` element also has the required `name` property that Angular uses to register the control with the form. When you have observed the effects, you can delete the `{{ model | json }}` text binding. ## Track form states Angular applies the `ng-submitted` class to `form` elements after the form has been submitted. This class can be used to change the form's style after it has been submitted. ##
004588
Track control states Adding the `NgModel` directive to a control adds class names to the control that describe its state. These classes can be used to change a control's style based on its state. The following table describes the class names that Angular applies based on the control's state. | States | Class if true | Class if false | | :------------------------------- | :------------ | :------------- | | The control has been visited. | `ng-touched` | `ng-untouched` | | The control's value has changed. | `ng-dirty` | `ng-pristine` | | The control's value is valid. | `ng-valid` | `ng-invalid` | Angular also applies the `ng-submitted` class to `form` elements upon submission, but not to the controls inside the `form` element. You use these CSS classes to define the styles for your control based on its status. ### Observe control states To see how the classes are added and removed by the framework, open the browser's developer tools and inspect the `<input>` element that represents the actor name. 1. Using your browser's developer tools, find the `<input>` element that corresponds to the **Name** input box. You can see that the element has multiple CSS classes in addition to "form-control". 1. When you first bring it up, the classes indicate that it has a valid value, that the value has not been changed since initialization or reset, and that the control has not been visited since initialization or reset. <docs-code language="html"> <input class="form-control ng-untouched ng-pristine ng-valid">; </docs-code> 1. Take the following actions on the **Name** `<input>` box, and observe which classes appear. - Look but don't touch. The classes indicate that it is untouched, pristine, and valid. - Click inside the name box, then click outside it. The control has now been visited, and the element has the `ng-touched` class instead of the `ng-untouched` class. - Add slashes to the end of the name. It is now touched and dirty. - Erase the name. This makes the value invalid, so the `ng-invalid` class replaces the `ng-valid` class. ### Create visual feedback for states The `ng-valid`/`ng-invalid` pair is particularly interesting, because you want to send a strong visual signal when the values are invalid. You also want to mark required fields. You can mark required fields and invalid data at the same time with a colored bar on the left of the input box. To change the appearance in this way, take the following steps. 1. Add definitions for the `ng-*` CSS classes. 1. Add these class definitions to a new `forms.css` file. 1. Add the new file to the project as a sibling to `index.html`: <docs-code header="src/assets/forms.css" language="css" path="adev/src/content/examples/forms/src/assets/forms.css"/> 1. In the `index.html` file, update the `<head>` tag to include the new style sheet. <docs-code header="src/index.html (styles)" path="adev/src/content/examples/forms/src/index.html" visibleRegion="styles"/> ### Show and hide validation error messages The **Name** input box is required and clearing it turns the bar red. That indicates that something is wrong, but the user doesn't know what is wrong or what to do about it. You can provide a helpful message by checking for and responding to the control's state. The **Skill** select box is also required, but it doesn't need this kind of error handling because the selection box already constrains the selection to valid values. To define and show an error message when appropriate, take the following steps. <docs-workflow> <docs-step title="Add a local reference to the input"> Extend the `input` tag with a template reference variable that you can use to access the input box's Angular control from within the template. In the example, the variable is `#name="ngModel"`. The template reference variable (`#name`) is set to `"ngModel"` because that is the value of the [`NgModel.exportAs`](api/core/Directive#exportAs) property. This property tells Angular how to link a reference variable to a directive. </docs-step> <docs-step title="Add the error message"> Add a `<div>` that contains a suitable error message. </docs-step> <docs-step title="Make the error message conditional"> Show or hide the error message by binding properties of the `name` control to the message `<div>` element's `hidden` property. </docs-step> <docs-code header="src/app/actor-form/actor-form.component.html (hidden-error-msg)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="hidden-error-msg"/> <docs-step title="Add a conditional error message to name"> Add a conditional error message to the `name` input box, as in the following example. <docs-code header="src/app/actor-form/actor-form.component.html (excerpt)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="name-with-error-msg"/> </docs-step> </docs-workflow> <docs-callout title='Illustrating the "pristine" state'> In this example, you hide the message when the control is either valid or _pristine_. Pristine means the user hasn't changed the value since it was displayed in this form. If you ignore the `pristine` state, you would hide the message only when the value is valid. If you arrive in this component with a new, blank actor or an invalid actor, you'll see the error message immediately, before you've done anything. You might want the message to display only when the user makes an invalid change. Hiding the message while the control is in the `pristine` state achieves that goal. You'll see the significance of this choice when you add a new actor to the form in the next step. </docs-callout> ## Add a new actor This exercise shows how you can respond to a native HTML button-click event by adding to the model data. To let form users add a new actor, you will add a **New Actor** button that responds to a click event. 1. In the template, place a "New Actor" `<button>` element at the bottom of the form. 1. In the component file, add the actor-creation method to the actor data model. <docs-code header="src/app/actor-form/actor-form.component.ts (New Actor method)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.ts" visibleRegion="new-actor"/> 1. Bind the button's click event to an actor-creation method, `newActor()`. <docs-code header="src/app/actor-form/actor-form.component.html (New Actor button)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="new-actor-button-no-reset"/> 1. Run the application again and click the **New Actor** button. The form clears, and the _required_ bars to the left of the input box are red, indicating invalid `name` and `skill` properties. Notice that the error messages are hidden. This is because the form is pristine; you haven't changed anything yet. 1. Enter a name and click **New Actor** again. Now the application displays a `Name is required` error message, because the input box is no longer pristine. The form remembers that you entered a name before clicking **New Actor**. 1. To restore the pristine state of the form controls, clear all of the flags imperatively by calling the form's `reset()` method after calling the `newActor()` method. <docs-code header="src/app/actor-form/actor-form.component.html (Reset the form)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="new-actor-button-form-reset"/> Now clicking **New Actor** resets both the form and its control flags. ##
004591
# Typed Forms As of Angular 14, reactive forms are strictly typed by default. As background for this guide, you should already be familiar with [Angular Reactive Forms](guide/forms/reactive-forms). ## Overview of Typed Forms <docs-video src="https://www.youtube.com/embed/L-odCf4MfJc" alt="Typed Forms in Angular" /> With Angular reactive forms, you explicitly specify a *form model*. As a simple example, consider this basic user login form: ```ts const login = new FormGroup({ email: new FormControl(''), password: new FormControl(''), }); ``` Angular provides many APIs for interacting with this `FormGroup`. For example, you may call `login.value`, `login.controls`, `login.patchValue`, etc. (For a full API reference, see the [API documentation](api/forms/FormGroup).) In previous Angular versions, most of these APIs included `any` somewhere in their types, and interacting with the structure of the controls, or the values themselves, was not type-safe. For example: you could write the following invalid code: ```ts const emailDomain = login.value.email.domain; ``` With strictly typed reactive forms, the above code does not compile, because there is no `domain` property on `email`. In addition to the added safety, the types enable a variety of other improvements, such as better autocomplete in IDEs, and an explicit way to specify form structure. These improvements currently apply only to *reactive* forms (not [*template-driven* forms](guide/forms/template-driven-forms)). ## Untyped Forms Non-typed forms are still supported, and will continue to work as before. To use them, you must import the `Untyped` symbols from `@angular/forms`: ```ts const login = new UntypedFormGroup({ email: new UntypedFormControl(''), password: new UntypedFormControl(''), }); ``` Each `Untyped` symbol has exactly the same semantics as in previous Angular version. By removing the `Untyped` prefixes, you can incrementally enable the types. ## `FormControl`: Getting Started The simplest possible form consists of a single control: ```ts const email = new FormControl('[email protected]'); ``` This control will be automatically inferred to have the type `FormControl<string|null>`. TypeScript will automatically enforce this type throughout the [`FormControl` API](api/forms/FormControl), such as `email.value`, `email.valueChanges`, `email.setValue(...)`, etc. ### Nullability You might wonder: why does the type of this control include `null`? This is because the control can become `null` at any time, by calling reset: ```ts const email = new FormControl('[email protected]'); email.reset(); console.log(email.value); // null ``` TypeScript will enforce that you always handle the possibility that the control has become `null`. If you want to make this control non-nullable, you may use the `nonNullable` option. This will cause the control to reset to its initial value, instead of `null`: ```ts const email = new FormControl('[email protected]', {nonNullable: true}); email.reset(); console.log(email.value); // [email protected] ``` To reiterate, this option affects the runtime behavior of your form when `.reset()` is called, and should be flipped with care. ### Specifying an Explicit Type It is possible to specify the type, instead of relying on inference. Consider a control that is initialized to `null`. Because the initial value is `null`, TypeScript will infer `FormControl<null>`, which is narrower than we want. ```ts const email = new FormControl(null); email.setValue('[email protected]'); // Error! ``` To prevent this, we explicitly specify the type as `string|null`: ```ts const email = new FormControl<string|null>(null); email.setValue('[email protected]'); ``` ## `FormArray`: Dynamic, Homogenous Collections A `FormArray` contains an open-ended list of controls. The type parameter corresponds to the type of each inner control: ```ts const names = new FormArray([new FormControl('Alex')]); names.push(new FormControl('Jess')); ``` This `FormArray` will have the inner controls type `FormControl<string|null>`. If you want to have multiple different element types inside the array, you must use `UntypedFormArray`, because TypeScript cannot infer which element type will occur at which position. ## `FormGroup` and `FormRecord` Angular provides the `FormGroup` type for forms with an enumerated set of keys, and a type called `FormRecord`, for open-ended or dynamic groups. ### Partial Values Consider again a login form: ```ts const login = new FormGroup({ email: new FormControl('', {nonNullable: true}), password: new FormControl('', {nonNullable: true}), }); ``` On any `FormGroup`, it is [possible to disable controls](api/forms/FormGroup). Any disabled control will not appear in the group's value. As a consequence, the type of `login.value` is `Partial<{email: string, password: string}>`. The `Partial` in this type means that each member might be undefined. More specifically, the type of `login.value.email` is `string|undefined`, and TypeScript will enforce that you handle the possibly `undefined` value (if you have `strictNullChecks` enabled). If you want to access the value *including* disabled controls, and thus bypass possible `undefined` fields, you can use `login.getRawValue()`. ### Optional Controls and Dynamic Groups Some forms have controls that may or may not be present, which can be added and removed at runtime. You can represent these controls using *optional fields*: ```ts interface LoginForm { email: FormControl<string>; password?: FormControl<string>; } const login = new FormGroup<LoginForm>({ email: new FormControl('', {nonNullable: true}), password: new FormControl('', {nonNullable: true}), }); login.removeControl('password'); ``` In this form, we explicitly specify the type, which allows us to make the `password` control optional. TypeScript will enforce that only optional controls can be added or removed. ### `FormRecord` Some `FormGroup` usages do not fit the above pattern because the keys are not known ahead of time. The `FormRecord` class is designed for that case: ```ts const addresses = new FormRecord<FormControl<string|null>>({}); addresses.addControl('Andrew', new FormControl('2340 Folsom St')); ``` Any control of type `string|null` can be added to this `FormRecord`. If you need a `FormGroup` that is both dynamic (open-ended) and heterogeneous (the controls are different types), no improved type safety is possible, and you should use `UntypedFormGroup`. A `FormRecord` can also be built with the `FormBuilder`: ```ts const addresses = fb.record({'Andrew': '2340 Folsom St'}); ``` ## `FormBuilder` and `NonNullableFormBuilder` The `FormBuilder` class has been upgraded to support the new types as well, in the same manner as the above examples. Additionally, an additional builder is available: `NonNullableFormBuilder`. This type is shorthand for specifying `{nonNullable: true}` on every control, and can eliminate significant boilerplate from large non-nullable forms. You can access it using the `nonNullable` property on a `FormBuilder`: ```ts const fb = new FormBuilder(); const login = fb.nonNullable.group({ email: '', password: '', }); ``` On the above example, both inner controls will be non-nullable (i.e. `nonNullable` will be set). You can also inject it using the name `NonNullableFormBuilder`.
004592
# RxJS Interop IMPORTANT: The RxJS Interop package is available for [developer preview](reference/releases#developer-preview). It's ready for you to try, but it might change before it is stable. Angular's `@angular/core/rxjs-interop` package provides useful utilities to integrate [Angular Signals](guide/signals) with RxJS Observables. ## `toSignal` Use the `toSignal` function to create a signal which tracks the value of an Observable. It behaves similarly to the `async` pipe in templates, but is more flexible and can be used anywhere in an application. ```ts import { Component } from '@angular/core'; import { AsyncPipe } from '@angular/common'; import { interval } from 'rxjs'; import { toSignal } from '@angular/core/rxjs-interop'; @Component({ template: `{{ counter() }}`, }) export class Ticker { counterObservable = interval(1000); // Get a `Signal` representing the `counterObservable`'s value. counter = toSignal(this.counterObservable, {initialValue: 0}); } ``` Like the `async` pipe, `toSignal` subscribes to the Observable immediately, which may trigger side effects. The subscription created by `toSignal` automatically unsubscribes from the given Observable when the component or service which calls `toSignal` is destroyed. IMPORTANT: `toSignal` creates a subscription. You should avoid calling it repeatedly for the same Observable, and instead reuse the signal it returns. ### Injection context `toSignal` by default needs to run in an [injection context](guide/di/dependency-injection-context), such as during construction of a component or service. If an injection context is not available, you can manually specify the `Injector` to use instead. ### Initial values Observables may not produce a value synchronously on subscription, but signals always require a current value. There are several ways to deal with this "initial" value of `toSignal` signals. #### The `initialValue` option As in the example above, you can specify an `initialValue` option with the value the signal should return before the Observable emits for the first time. #### `undefined` initial values If you don't provide an `initialValue`, the resulting signal will return `undefined` until the Observable emits. This is similar to the `async` pipe's behavior of returning `null`. #### The `requireSync` option Some Observables are guaranteed to emit synchronously, such as `BehaviorSubject`. In those cases, you can specify the `requireSync: true` option. When `requiredSync` is `true`, `toSignal` enforces that the Observable emits synchronously on subscription. This guarantees that the signal always has a value, and no `undefined` type or initial value is required. ### `manualCleanup` By default, `toSignal` automatically unsubscribes from the Observable when the component or service that creates it is destroyed. To override this behavior, you can pass the `manualCleanup` option. You can use this setting for Observables that complete themselves naturally. ### Error and Completion If an Observable used in `toSignal` produces an error, that error is thrown when the signal is read. If an Observable used in `toSignal` completes, the signal continues to return the most recently emitted value before completion. ## `toObservable` Use the `toObservable` utility to create an `Observable` which tracks the value of a signal. The signal's value is monitored with an `effect` which emits the value to the Observable when it changes. ```ts import { Component, signal } from '@angular/core'; @Component(...) export class SearchResults { query: Signal<string> = inject(QueryService).query; query$ = toObservable(this.query); results$ = this.query$.pipe( switchMap(query => this.http.get('/search?q=' + query )) ); } ``` As the `query` signal changes, the `query$` Observable emits the latest query and triggers a new HTTP request. ### Injection context `toObservable` by default needs to run in an [injection context](guide/di/dependency-injection-context), such as during construction of a component or service. If an injection context is not available, you can manually specify the `Injector` to use instead. ### Timing of `toObservable` `toObservable` uses an effect to track the value of the signal in a `ReplaySubject`. On subscription, the first value (if available) may be emitted synchronously, and all subsequent values will be asynchronous. Unlike Observables, signals never provide a synchronous notification of changes. Even if you update a signal's value multiple times, `toObservable` will only emit the value after the signal stabilizes. ```ts const obs$ = toObservable(mySignal); obs$.subscribe(value => console.log(value)); mySignal.set(1); mySignal.set(2); mySignal.set(3); ``` Here, only the last value (3) will be logged. ### `outputFromObservable` `outputFromObservable(...)` declares an Angular output that emits values based on an RxJS observable. ```ts class MyDir { nameChange$ = new Observable<string>(/* ... */); nameChange = outputFromObservable(this.nameChange$); // OutputRef<string> } ``` See more details in the [output() API guide](/guide/components/output-fn). ### `outputToObservable` `outputToObservable(...)` converts an Angular output to an observable. This allows you to integrate Angular outputs conveniently into RxJS streams. ```ts outputToObservable(myComp.instance.onNameChange) .pipe(...) .subscribe(...) ``` See more details in the [output() API guide](/guide/components/output-fn).
004594
<docs-decorative-header title="Angular Signals" imgSrc="adev/src/assets/images/signals.svg"> <!-- markdownlint-disable-line --> Angular Signals is a system that granularly tracks how and where your state is used throughout an application, allowing the framework to optimize rendering updates. </docs-decorative-header> Tip: Check out Angular's [Essentials](essentials/managing-dynamic-data) before diving into this comprehensive guide. ## What are signals? A **signal** is a wrapper around a value that notifies interested consumers when that value changes. Signals can contain any value, from primitives to complex data structures. You read a signal's value by calling its getter function, which allows Angular to track where the signal is used. Signals may be either _writable_ or _read-only_. ### Writable signals Writable signals provide an API for updating their values directly. You create writable signals by calling the `signal` function with the signal's initial value: ```ts const count = signal(0); // Signals are getter functions - calling them reads their value. console.log('The count is: ' + count()); ``` To change the value of a writable signal, either `.set()` it directly: ```ts count.set(3); ``` or use the `.update()` operation to compute a new value from the previous one: ```ts // Increment the count by 1. count.update(value => value + 1); ``` Writable signals have the type `WritableSignal`. ### Computed signals **Computed signal** are read-only signals that derive their value from other signals. You define computed signals using the `computed` function and specifying a derivation: ```typescript const count: WritableSignal<number> = signal(0); const doubleCount: Signal<number> = computed(() => count() * 2); ``` The `doubleCount` signal depends on the `count` signal. Whenever `count` updates, Angular knows that `doubleCount` needs to update as well. #### Computed signals are both lazily evaluated and memoized `doubleCount`'s derivation function does not run to calculate its value until the first time you read `doubleCount`. The calculated value is then cached, and if you read `doubleCount` again, it will return the cached value without recalculating. If you then change `count`, Angular knows that `doubleCount`'s cached value is no longer valid, and the next time you read `doubleCount` its new value will be calculated. As a result, you can safely perform computationally expensive derivations in computed signals, such as filtering arrays. #### Computed signals are not writable signals You cannot directly assign values to a computed signal. That is, ```ts doubleCount.set(3); ``` produces a compilation error, because `doubleCount` is not a `WritableSignal`. #### Computed signal dependencies are dynamic Only the signals actually read during the derivation are tracked. For example, in this `computed` the `count` signal is only read if the `showCount` signal is true: ```ts const showCount = signal(false); const count = signal(0); const conditionalCount = computed(() => { if (showCount()) { return `The count is ${count()}.`; } else { return 'Nothing to see here!'; } }); ``` When you read `conditionalCount`, if `showCount` is `false` the "Nothing to see here!" message is returned _without_ reading the `count` signal. This means that if you later update `count` it will _not_ result in a recomputation of `conditionalCount`. If you set `showCount` to `true` and then read `conditionalCount` again, the derivation will re-execute and take the branch where `showCount` is `true`, returning the message which shows the value of `count`. Changing `count` will then invalidate `conditionalCount`'s cached value. Note that dependencies can be removed during a derivation as well as added. If you later set `showCount` back to `false`, then `count` will no longer be considered a dependency of `conditionalCount`. ## Reading signals in `OnPush` components When you read a signal within an `OnPush` component's template, Angular tracks the signal as a dependency of that component. When the value of that signal changes, Angular automatically [marks](api/core/ChangeDetectorRef#markforcheck) the component to ensure it gets updated the next time change detection runs. Refer to the [Skipping component subtrees](best-practices/skipping-subtrees) guide for more information about `OnPush` components. ## Effects Signals are useful because they notify interested consumers when they change. An **effect** is an operation that runs whenever one or more signal values change. You can create an effect with the `effect` function: ```ts effect(() => { console.log(`The current count is: ${count()}`); }); ``` Effects always run **at least once.** When an effect runs, it tracks any signal value reads. Whenever any of these signal values change, the effect runs again. Similar to computed signals, effects keep track of their dependencies dynamically, and only track signals which were read in the most recent execution. Effects always execute **asynchronously**, during the change detection process. ### Use cases for effects Effects are rarely needed in most application code, but may be useful in specific circumstances. Here are some examples of situations where an `effect` might be a good solution: * Logging data being displayed and when it changes, either for analytics or as a debugging tool. * Keeping data in sync with `window.localStorage`. * Adding custom DOM behavior that can't be expressed with template syntax. * Performing custom rendering to a `<canvas>`, charting library, or other third party UI library. <docs-callout critical title="When not to use effects"> Avoid using effects for propagation of state changes. This can result in `ExpressionChangedAfterItHasBeenChecked` errors, infinite circular updates, or unnecessary change detection cycles. Because of these risks, Angular by default prevents you from setting signals in effects. It can be enabled if absolutely necessary by setting the `allowSignalWrites` flag when you create an effect. Instead, use `computed` signals to model state that depends on other state. </docs-callout> ### Injection context By default, you can only create an `effect()` within an [injection context](guide/di/dependency-injection-context) (where you have access to the `inject` function). The easiest way to satisfy this requirement is to call `effect` within a component, directive, or service `constructor`: ```ts @Component({...}) export class EffectiveCounterComponent { readonly count = signal(0); constructor() { // Register a new effect. effect(() => { console.log(`The count is: ${this.count()}`); }); } } ``` Alternatively, you can assign the effect to a field (which also gives it a descriptive name). ```ts @Component({...}) export class EffectiveCounterComponent { readonly count = signal(0); private loggingEffect = effect(() => { console.log(`The count is: ${this.count()}`); }); } ``` To create an effect outside of the constructor, you can pass an `Injector` to `effect` via its options: ```ts @Component({...}) export class EffectiveCounterComponent { readonly count = signal(0); constructor(private injector: Injector) {} initializeLogging(): void { effect(() => { console.log(`The count is: ${this.count()}`); }, {injector: this.injector}); } } ``` ### Destroying effects When you create an effect, it is automatically destroyed when its enclosing context is destroyed. This means that effects created within components are destroyed when the component is destroyed. The same goes for effects within directives, services, etc. Effects return an `EffectRef` that you can use to destroy them manually, by calling the `.destroy()` method. You can combine this with the `manualCleanup` option to create an effect that lasts until it is manually destroyed. Be careful to actually clean up such effects when they're no longer required.
004595
## Advanced topics ### Signal equality functions When creating a signal, you can optionally provide an equality function, which will be used to check whether the new value is actually different than the previous one. ```ts import _ from 'lodash'; const data = signal(['test'], {equal: _.isEqual}); // Even though this is a different array instance, the deep equality // function will consider the values to be equal, and the signal won't // trigger any updates. data.set(['test']); ``` Equality functions can be provided to both writable and computed signals. HELPFUL: By default, signals use referential equality ([`Object.is()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison). ### Reading without tracking dependencies Rarely, you may want to execute code which may read signals within a reactive function such as `computed` or `effect` _without_ creating a dependency. For example, suppose that when `currentUser` changes, the value of a `counter` should be logged. you could create an `effect` which reads both signals: ```ts effect(() => { console.log(`User set to ${currentUser()} and the counter is ${counter()}`); }); ``` This example will log a message when _either_ `currentUser` or `counter` changes. However, if the effect should only run when `currentUser` changes, then the read of `counter` is only incidental and changes to `counter` shouldn't log a new message. You can prevent a signal read from being tracked by calling its getter with `untracked`: ```ts effect(() => { console.log(`User set to ${currentUser()} and the counter is ${untracked(counter)}`); }); ``` `untracked` is also useful when an effect needs to invoke some external code which shouldn't be treated as a dependency: ```ts effect(() => { const user = currentUser(); untracked(() => { // If the `loggingService` reads signals, they won't be counted as // dependencies of this effect. this.loggingService.log(`User set to ${user}`); }); }); ``` ### Effect cleanup functions Effects might start long-running operations, which you should cancel if the effect is destroyed or runs again before the first operation finished. When you create an effect, your function can optionally accept an `onCleanup` function as its first parameter. This `onCleanup` function lets you register a callback that is invoked before the next run of the effect begins, or when the effect is destroyed. ```ts effect((onCleanup) => { const user = currentUser(); const timer = setTimeout(() => { console.log(`1 second ago, the user became ${user}`); }, 1000); onCleanup(() => { clearTimeout(timer); }); }); ```
004597
# Signal inputs Signal inputs allow values to be bound from parent components. Those values are exposed using a `Signal` and can change during the lifecycle of your component. Angular supports two variants of inputs: **Optional inputs** Inputs are optional by default, unless you use `input.required`. You can specify an explicit initial value, or Angular will use `undefined` implicitly. **Required inputs** Required inputs always have a value of the given input type. They are declared using the `input.required` function. ```typescript import {Component, input} from '@angular/core'; @Component({...}) export class MyComp { // optional firstName = input<string>(); // InputSignal<string|undefined> age = input(0); // InputSignal<number> // required lastName = input.required<string>(); // InputSignal<string> } ``` An input is automatically recognized by Angular whenever you use the `input` or `input.required` functions as initializer of class members. ## Aliasing an input Angular uses the class member name as the name of the input. You can alias inputs to change their public name to be different. ```typescript class StudentDirective { age = input(0, {alias: 'studentAge'}); } ``` This allows users to bind to your input using `[studentAge]`, while inside your component you can access the input values using `this.age`. ## Using in templates Signal inputs are read-only signals. As with signals declared via `signal()`, you access the current value of the input by calling the input signal. ```angular-html <p>First name: {{firstName()}}</p> <p>Last name: {{lastName()}}</p> ``` This access to the value is captured in reactive contexts and can notify active consumers, like Angular itself, whenever the input value changes. An input signal in practice is a trivial extension of signals that you know from [the signals guide](guide/signals). ```typescript export class InputSignal<T> extends Signal<T> { ... }`. ``` ## Deriving values As with signals, you can derive values from inputs using `computed`. ```typescript import {Component, input, computed} from '@angular/core'; @Component({...}) export class MyComp { age = input(0); // age multiplied by two. ageMultiplied = computed(() => this.age() * 2); } ``` Computed signals memoize values. See more details in the [dedicated section for computed](guide/signals#computed-signals). ## Monitoring changes With signal inputs, users can leverage the `effect` function. The function will execute whenever the input changes. Consider the following example. The new value is printed to the console whenever the `firstName` input changes. ```typescript import {input, effect} from '@angular/core'; class MyComp { firstName = input.required<string>(); constructor() { effect(() => { console.log(this.firstName()); }); } } ``` The `console.log` function is invoked every time the `firstName` input changes. This will happen as soon as `firstName` is available, and for subsequent changes during the lifetime of `MyComp`. ## Value transforms You may want to coerce or parse input values without changing the meaning of the input. Transforms convert the raw value from parent templates to the expected input type. Transforms should be [pure functions](https://en.wikipedia.org/wiki/Pure_function). ```typescript class MyComp { disabled = input(false, { transform: (value: boolean|string) => typeof value === 'string' ? value === '' : value, }); } ``` In the example above, you are declaring an input named `disabled` that is accepting values of type `boolean` and `string`. This is captured by the explicit parameter type of `value` in the `transform` option. These values are then parsed to a `boolean` with the transform, resulting in booleans. That way, you are only dealing with `boolean` inside your component when calling `this.disabled()`, while users of your component can pass an empty string as a shorthand to mark your component as disabled. ```angular-html <my-custom-comp disabled> ``` IMPORTANT: Do not use transforms if they change the meaning of the input, or if they are [impure](https://en.wikipedia.org/wiki/Pure_function#Impure_functions). Instead, use `computed` for transformations with different meaning, or an `effect` for impure code that should run whenever the input changes. ## Why should we use signal inputs and not `@Input()`? Signal inputs are a reactive alternative to decorator-based `@Input()`. In comparison to decorator-based `@Input`, signal inputs provide numerous benefits: 1. Signal inputs are more **type safe**: <br/>• Required inputs do not require initial values, or tricks to tell TypeScript that an input _always_ has a value. <br/>• Transforms are automatically checked to match the accepted input values. 2. Signal inputs, when used in templates, will **automatically** mark `OnPush` components as dirty. 3. Values can be easily **derived** whenever an input changes using `computed`. 4. Easier and more local monitoring of inputs using `effect` instead of `ngOnChanges` or setters.
004605
# Unwrapping data from an observable Observables let you pass messages between parts of your application. You can use observables for event handling, asynchronous programming, and handling multiple values. Observables can deliver single or multiple values of any type, either synchronously (as a function delivers a value to its caller) or asynchronously on a schedule. Use the built-in [`AsyncPipe`](api/common/AsyncPipe "API description of AsyncPipe") to accept an observable as input and subscribe to the input automatically. Without this pipe, your component code would have to subscribe to the observable to consume its values, extract the resolved values, expose them for binding, and unsubscribe when the observable is destroyed in order to prevent memory leaks. `AsyncPipe` is a pipe that saves boilerplate code in your component to maintain the subscription and keep delivering values from that observable as they arrive. The following code example binds an observable of message strings (`message$`) to a view with the `async` pipe. <!-- TODO: Enable preview if this example does not depend on Zone/ or if we run the example with Zone. --> <docs-code header="src/app/hero-async-message.component.ts" path="adev/src/content/examples/pipes/src/app/hero-async-message.component.ts" />
004609
# Basics of testing components A component, unlike all other parts of an Angular application, combines an HTML template and a TypeScript class. The component truly is the template and the class *working together*. To adequately test a component, you should test that they work together as intended. Such tests require creating the component's host element in the browser DOM, as Angular does, and investigating the component class's interaction with the DOM as described by its template. The Angular `TestBed` facilitates this kind of testing as you'll see in the following sections. But in many cases, *testing the component class alone*, without DOM involvement, can validate much of the component's behavior in a straightforward, more obvious way. ## Component DOM testing A component is more than just its class. A component interacts with the DOM and with other components. Classes alone cannot tell you if the component is going to render properly, respond to user input and gestures, or integrate with its parent and child components. * Is `Lightswitch.clicked()` bound to anything such that the user can invoke it? * Is the `Lightswitch.message` displayed? * Can the user actually select the hero displayed by `DashboardHeroComponent`? * Is the hero name displayed as expected \(such as uppercase\)? * Is the welcome message displayed by the template of `WelcomeComponent`? These might not be troubling questions for the preceding simple components illustrated. But many components have complex interactions with the DOM elements described in their templates, causing HTML to appear and disappear as the component state changes. To answer these kinds of questions, you have to create the DOM elements associated with the components, you must examine the DOM to confirm that component state displays properly at the appropriate times, and you must simulate user interaction with the screen to determine whether those interactions cause the component to behave as expected. To write these kinds of test, you'll use additional features of the `TestBed` as well as other testing helpers. ### CLI-generated tests The CLI creates an initial test file for you by default when you ask it to generate a new component. For example, the following CLI command generates a `BannerComponent` in the `app/banner` folder \(with inline template and styles\): <docs-code language="shell"> ng generate component banner --inline-template --inline-style --module app </docs-code> It also generates an initial test file for the component, `banner-external.component.spec.ts`, that looks like this: <docs-code header="app/banner/banner-external.component.spec.ts (initial)" path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v1"/> HELPFUL: Because `compileComponents` is asynchronous, it uses the [`waitForAsync`](api/core/testing/waitForAsync) utility function imported from `@angular/core/testing`. Refer to the [waitForAsync](guide/testing/components-scenarios#waitForAsync) section for more details. ### Reduce the setup Only the last three lines of this file actually test the component and all they do is assert that Angular can create the component. The rest of the file is boilerplate setup code anticipating more advanced tests that *might* become necessary if the component evolves into something substantial. You'll learn about these advanced test features in the following sections. For now, you can radically reduce this test file to a more manageable size: <docs-code header="app/banner/banner-initial.component.spec.ts (minimal)" path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v2"/> In this example, the metadata object passed to `TestBed.configureTestingModule` simply declares `BannerComponent`, the component to test. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="configureTestingModule"/> HELPFUL: There's no need to declare or import anything else. The default test module is pre-configured with something like the `BrowserModule` from `@angular/platform-browser`. Later you'll call `TestBed.configureTestingModule()` with imports, providers, and more declarations to suit your testing needs. Optional `override` methods can further fine-tune aspects of the configuration. ### `createComponent()` After configuring `TestBed`, you call its `createComponent()` method. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="createComponent"/> `TestBed.createComponent()` creates an instance of the `BannerComponent`, adds a corresponding element to the test-runner DOM, and returns a [`ComponentFixture`](#componentfixture). IMPORTANT: Do not re-configure `TestBed` after calling `createComponent`. The `createComponent` method freezes the current `TestBed` definition, closing it to further configuration. You cannot call any more `TestBed` configuration methods, not `configureTestingModule()`, nor `get()`, nor any of the `override...` methods. If you try, `TestBed` throws an error. ### `ComponentFixture` The [ComponentFixture](api/core/testing/ComponentFixture) is a test harness for interacting with the created component and its corresponding element. Access the component instance through the fixture and confirm it exists with a Jasmine expectation: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="componentInstance"/> ### `beforeEach()` You will add more tests as this component evolves. Rather than duplicate the `TestBed` configuration for each test, you refactor to pull the setup into a Jasmine `beforeEach()` and some supporting variables: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v3"/> Now add a test that gets the component's element from `fixture.nativeElement` and looks for the expected text. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v4-test-2"/> ### `nativeElement` The value of `ComponentFixture.nativeElement` has the `any` type. Later you'll encounter the `DebugElement.nativeElement` and it too has the `any` type. Angular can't know at compile time what kind of HTML element the `nativeElement` is or if it even is an HTML element. The application might be running on a *non-browser platform*, such as the server or a [Web Worker](https://developer.mozilla.org/docs/Web/API/Web_Workers_API), where the element might have a diminished API or not exist at all. The tests in this guide are designed to run in a browser so a `nativeElement` value will always be an `HTMLElement` or one of its derived classes. Knowing that it is an `HTMLElement` of some sort, use the standard HTML `querySelector` to dive deeper into the element tree. Here's another test that calls `HTMLElement.querySelector` to get the paragraph element and look for the banner text: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v4-test-3"/> ### `DebugElement` The Angular *fixture* provides the component's element directly through the `fixture.nativeElement`. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="nativeElement"/> This is actually a convenience method, implemented as `fixture.debugElement.nativeElement`. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="debugElement-nativeElement"/> There's a good reason for this circuitous path to the element. The properties of the `nativeElement` depend upon the runtime environment. You could be running these tests on a *non-browser* platform that doesn't have a DOM or whose DOM-emulation doesn't support the full `HTMLElement` API. Angular relies on the `DebugElement` abstraction to work safely across *all supported platforms*. Instead of creating an HTML element tree, Angular creates a `DebugElement` tree that wraps the *native elements* for the runtime platform. The `nativeElement` property unwraps the `DebugElement` and returns the platform-specific element object. Because the sample tests for this guide are designed to run only in a browser, a `nativeElement` in these tests is always an `HTMLElement` whose familiar methods and properties you can explore within a test. Here's the previous test, re-implemented with `fixture.debugElement.nativeElement`: <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="v4-test-4"/> The `DebugElement` has other methods and properties that are useful in tests, as you'll see elsewhere in this guide. You import the `DebugElement` symbol from the Angular core library. <docs-code path="adev/src/content/examples/testing/src/app/banner/banner-initial.component.spec.ts" visibleRegion="import-debug-element"/>
004611
# Testing services To check that your services are working as you intend, you can write tests specifically for them. Services are often the smoothest files to unit test. Here are some synchronous and asynchronous unit tests of the `ValueService` written without assistance from Angular testing utilities. <docs-code header="app/demo/demo.spec.ts" path="adev/src/content/examples/testing/src/app/demo/demo.spec.ts" visibleRegion="ValueService"/> ## Services with dependencies Services often depend on other services that Angular injects into the constructor. In many cases, you can create and *inject* these dependencies by hand while calling the service's constructor. The `MasterService` is a simple example: <docs-code header="app/demo/demo.ts" path="adev/src/content/examples/testing/src/app/demo/demo.ts" visibleRegion="MasterService"/> `MasterService` delegates its only method, `getValue`, to the injected `ValueService`. Here are several ways to test it. <docs-code header="app/demo/demo.spec.ts" path="adev/src/content/examples/testing/src/app/demo/demo.spec.ts" visibleRegion="MasterService"/> The first test creates a `ValueService` with `new` and passes it to the `MasterService` constructor. However, injecting the real service rarely works well as most dependent services are difficult to create and control. Instead, mock the dependency, use a dummy value, or create a [spy](https://jasmine.github.io/tutorials/your_first_suite#section-Spies) on the pertinent service method. HELPFUL: Prefer spies as they are usually the best way to mock services. These standard testing techniques are great for unit testing services in isolation. However, you almost always inject services into application classes using Angular dependency injection and you should have tests that reflect that usage pattern. Angular testing utilities make it straightforward to investigate how injected services behave. ## Testing services with the `TestBed` Your application relies on Angular [dependency injection (DI)](guide/di) to create services. When a service has a dependent service, DI finds or creates that dependent service. And if that dependent service has its own dependencies, DI finds-or-creates them as well. As a service *consumer*, you don't worry about any of this. You don't worry about the order of constructor arguments or how they're created. As a service *tester*, you must at least think about the first level of service dependencies but you *can* let Angular DI do the service creation and deal with constructor argument order when you use the `TestBed` testing utility to provide and create services. ## Angular `TestBed` The `TestBed` is the most important of the Angular testing utilities. The `TestBed` creates a dynamically-constructed Angular *test* module that emulates an Angular [@NgModule](guide/ngmodules). The `TestBed.configureTestingModule()` method takes a metadata object that can have most of the properties of an [@NgModule](guide/ngmodules). To test a service, you set the `providers` metadata property with an array of the services that you'll test or mock. <docs-code header="app/demo/demo.testbed.spec.ts (provide ValueService in beforeEach)" path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="value-service-before-each"/> Then inject it inside a test by calling `TestBed.inject()` with the service class as the argument. HELPFUL: `TestBed.get()` was deprecated as of Angular version 9. To help minimize breaking changes, Angular introduces a new function called `TestBed.inject()`, which you should use instead. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="value-service-inject-it"/> Or inside the `beforeEach()` if you prefer to inject the service as part of your setup. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="value-service-inject-before-each"> </docs-code> When testing a service with a dependency, provide the mock in the `providers` array. In the following example, the mock is a spy object. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="master-service-before-each"/> The test consumes that spy in the same way it did earlier. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="master-service-it"/> ## Testing without `beforeEach()` Most test suites in this guide call `beforeEach()` to set the preconditions for each `it()` test and rely on the `TestBed` to create classes and inject services. There's another school of testing that never calls `beforeEach()` and prefers to create classes explicitly rather than use the `TestBed`. Here's how you might rewrite one of the `MasterService` tests in that style. Begin by putting re-usable, preparatory code in a *setup* function instead of `beforeEach()`. <docs-code header="app/demo/demo.spec.ts (setup)" path="adev/src/content/examples/testing/src/app/demo/demo.spec.ts" visibleRegion="no-before-each-setup"/> The `setup()` function returns an object literal with the variables, such as `masterService`, that a test might reference. You don't define *semi-global* variables \(for example, `let masterService: MasterService`\) in the body of the `describe()`. Then each test invokes `setup()` in its first line, before continuing with steps that manipulate the test subject and assert expectations. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.spec.ts" visibleRegion="no-before-each-test"/> Notice how the test uses [*destructuring assignment*](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to extract the setup variables that it needs. <docs-code path="adev/src/content/examples/testing/src/app/demo/demo.spec.ts" visibleRegion="no-before-each-setup-call"/> Many developers feel this approach is cleaner and more explicit than the traditional `beforeEach()` style. Although this testing guide follows the traditional style and the default [CLI schematics](https://github.com/angular/angular-cli) generate test files with `beforeEach()` and `TestBed`, feel free to adopt *this alternative approach* in your own projects. ## Testing HTTP services Data services that make HTTP calls to remote servers typically inject and delegate to the Angular [`HttpClient`](guide/http/testing) service for XHR calls. You can test a data service with an injected `HttpClient` spy as you would test any service with a dependency. <docs-code header="app/model/hero.service.spec.ts (tests with spies)" path="adev/src/content/examples/testing/src/app/model/hero.service.spec.ts" visibleRegion="test-with-spies"/> IMPORTANT: The `HeroService` methods return `Observables`. You must *subscribe* to an observable to \(a\) cause it to execute and \(b\) assert that the method succeeds or fails. The `subscribe()` method takes a success \(`next`\) and fail \(`error`\) callback. Make sure you provide *both* callbacks so that you capture errors. Neglecting to do so produces an asynchronous uncaught observable error that the test runner will likely attribute to a completely different test. ## `HttpClientTestingModule` Extended interactions between a data service and the `HttpClient` can be complex and difficult to mock with spies. The `HttpClientTestingModule` can make these testing scenarios more manageable. While the *code sample* accompanying this guide demonstrates `HttpClientTestingModule`, this page defers to the [Http guide](guide/http/testing), which covers testing with the `HttpClientTestingModule` in detail.
004613
# Testing Utility APIs This page describes the most useful Angular testing features. The Angular testing utilities include the `TestBed`, the `ComponentFixture`, and a handful of functions that control the test environment. The [`TestBed`](#testbed-api-summary) and [`ComponentFixture`](#component-fixture-api-summary) classes are covered separately. Here's a summary of the stand-alone functions, in order of likely utility: | Function | Details | |:--- |:--- | | `waitForAsync` | Runs the body of a test \(`it`\) or setup \(`beforeEach`\) function within a special *async test zone*. See [waitForAsync](guide/testing/components-scenarios#waitForAsync). | | `fakeAsync` | Runs the body of a test \(`it`\) within a special *fakeAsync test zone*, enabling a linear control flow coding style. See [fakeAsync](guide/testing/components-scenarios#fake-async). | | `tick` | Simulates the passage of time and the completion of pending asynchronous activities by flushing both *timer* and *micro-task* queues within the *fakeAsync test zone*. The curious, dedicated reader might enjoy this lengthy blog post, ["*Tasks, microtasks, queues and schedules*"](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules). Accepts an optional argument that moves the virtual clock forward by the specified number of milliseconds, clearing asynchronous activities scheduled within that timeframe. See [tick](guide/testing/components-scenarios#tick). | | `inject` | Injects one or more services from the current `TestBed` injector into a test function. It cannot inject a service provided by the component itself. See discussion of the [debugElement.injector](guide/testing/components-scenarios#get-injected-services). | | `discardPeriodicTasks` | When a `fakeAsync()` test ends with pending timer event *tasks* \(queued `setTimeOut` and `setInterval` callbacks\), the test fails with a clear error message. <br /> In general, a test should end with no queued tasks. When pending timer tasks are expected, call `discardPeriodicTasks` to flush the *task* queue and avoid the error. | | `flushMicrotasks` | When a `fakeAsync()` test ends with pending *micro-tasks* such as unresolved promises, the test fails with a clear error message. <br /> In general, a test should wait for micro-tasks to finish. When pending microtasks are expected, call `flushMicrotasks` to flush the *micro-task* queue and avoid the error. | | `ComponentFixtureAutoDetect` | A provider token for a service that turns on [automatic change detection](guide/testing/components-scenarios#automatic-change-detection). | | `getTestBed` | Gets the current instance of the `TestBed`. Usually unnecessary because the static class methods of the `TestBed` class are typically sufficient. The `TestBed` instance exposes a few rarely used members that are not available as static methods. | ## `TestBed` class summary The `TestBed` class is one of the principal Angular testing utilities. Its API is quite large and can be overwhelming until you've explored it, a little at a time. Read the early part of this guide first to get the basics before trying to absorb the full API. The module definition passed to `configureTestingModule` is a subset of the `@NgModule` metadata properties. <docs-code language="javascript"> type TestModuleMetadata = { providers?: any[]; declarations?: any[]; imports?: any[]; schemas?: Array<SchemaMetadata | any[]>; }; </docs-code> Each override method takes a `MetadataOverride<T>` where `T` is the kind of metadata appropriate to the method, that is, the parameter of an `@NgModule`, `@Component`, `@Directive`, or `@Pipe`. <docs-code language="javascript"> type MetadataOverride<T> = { add?: Partial<T>; remove?: Partial<T>; set?: Partial<T>; }; </docs-code> The `TestBed` API consists of static class methods that either update or reference a *global* instance of the `TestBed`. Internally, all static methods cover methods of the current runtime `TestBed` instance, which is also returned by the `getTestBed()` function. Call `TestBed` methods *within* a `beforeEach()` to ensure a fresh start before each individual test. Here are the most important static methods, in order of likely utility. | Methods | Details | |:--- |:--- | | `configureTestingModule` | The testing shims \(`karma-test-shim`, `browser-test-shim`\) establish the [initial test environment](guide/testing) and a default testing module. The default testing module is configured with basic declaratives and some Angular service substitutes that every tester needs. <br /> Call `configureTestingModule` to refine the testing module configuration for a particular set of tests by adding and removing imports, declarations \(of components, directives, and pipes\), and providers. | | `compileComponents` | Compile the testing module asynchronously after you've finished configuring it. You **must** call this method if *any* of the testing module components have a `templateUrl` or `styleUrls` because fetching component template and style files is necessarily asynchronous. See [compileComponents](guide/testing/components-scenarios#calling-compilecomponents). <br /> After calling `compileComponents`, the `TestBed` configuration is frozen for the duration of the current spec. | | `createComponent<T>` | Create an instance of a component of type `T` based on the current `TestBed` configuration. After calling `createComponent`, the `TestBed` configuration is frozen for the duration of the current spec. | | `overrideModule` | Replace metadata for the given `NgModule`. Recall that modules can import other modules. The `overrideModule` method can reach deeply into the current testing module to modify one of these inner modules. | | `overrideComponent` | Replace metadata for the given component class, which could be nested deeply within an inner module. | | `overrideDirective` | Replace metadata for the given directive class, which could be nested deeply within an inner module. | | `overridePipe` | Replace metadata for the given pipe class, which could be nested deeply within an inner module. | | `inject` | Retrieve a service from the current `TestBed` injector. The `inject` function is often adequate for this purpose. But `inject` throws an error if it can't provide the service. <br /> What if the service is optional? <br /> The `TestBed.inject()` method takes an optional second parameter, the object to return if Angular can't find the provider \(`null` in this example\): <docs-code header="app/demo/demo.testbed.spec.ts" path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="testbed-get-w-null"/> After calling `TestBed.inject`, the `TestBed` configuration is frozen for the duration of the current spec. | | `initTestEnvironment` | Initialize the testing environment for the entire test run. <br /> The testing shims \(`karma-test-shim`, `browser-test-shim`\) call it for you so there is rarely a reason for you to call it yourself. <br /> Call this method *exactly once*. To change this default in the middle of a test run, call `resetTestEnvironment` first. <br /> Specify the Angular compiler factory, a `PlatformRef`, and a default Angular testing module. Alternatives for non-browser platforms are available in the general form `@angular/platform-<platform_name>/testing/<platform_name>`. | | `resetTestEnvironment` | Reset the initial test environment, including the default testing module. | A few of the `TestBed` instance methods are not covered by static `TestBed` *class* methods. These are rarely needed.
004614
## The `ComponentFixture` The `TestBed.createComponent<T>` creates an instance of the component `T` and returns a strongly typed `ComponentFixture` for that component. The `ComponentFixture` properties and methods provide access to the component, its DOM representation, and aspects of its Angular environment. ### `ComponentFixture` properties Here are the most important properties for testers, in order of likely utility. | Properties | Details | |:--- |:--- | | `componentInstance` | The instance of the component class created by `TestBed.createComponent`. | | `debugElement` | The `DebugElement` associated with the root element of the component. <br /> The `debugElement` provides insight into the component and its DOM element during test and debugging. It's a critical property for testers. The most interesting members are covered [below](#debug-element-details). | | `nativeElement` | The native DOM element at the root of the component. | | `changeDetectorRef` | The `ChangeDetectorRef` for the component. <br /> The `ChangeDetectorRef` is most valuable when testing a component that has the `ChangeDetectionStrategy.OnPush` method or the component's change detection is under your programmatic control. | ### `ComponentFixture` methods The *fixture* methods cause Angular to perform certain tasks on the component tree. Call these method to trigger Angular behavior in response to simulated user action. Here are the most useful methods for testers. | Methods | Details | |:--- |:--- | | `detectChanges` | Trigger a change detection cycle for the component. <br /> Call it to initialize the component \(it calls `ngOnInit`\) and after your test code, change the component's data bound property values. Angular can't see that you've changed `personComponent.name` and won't update the `name` binding until you call `detectChanges`. <br /> Runs `checkNoChanges` afterwards to confirm that there are no circular updates unless called as `detectChanges(false)`; | | `autoDetectChanges` | Set this to `true` when you want the fixture to detect changes automatically. <br /> When autodetect is `true`, the test fixture calls `detectChanges` immediately after creating the component. Then it listens for pertinent zone events and calls `detectChanges` accordingly. When your test code modifies component property values directly, you probably still have to call `fixture.detectChanges` to trigger data binding updates. <br /> The default is `false`. Testers who prefer fine control over test behavior tend to keep it `false`. | | `checkNoChanges` | Do a change detection run to make sure there are no pending changes. Throws an exceptions if there are. | | `isStable` | If the fixture is currently *stable*, returns `true`. If there are async tasks that have not completed, returns `false`. | | `whenStable` | Returns a promise that resolves when the fixture is stable. <br /> To resume testing after completion of asynchronous activity or asynchronous change detection, hook that promise. See [whenStable](guide/testing/components-scenarios#when-stable). | | `destroy` | Trigger component destruction. | #### `DebugElement` The `DebugElement` provides crucial insights into the component's DOM representation. From the test root component's `DebugElement` returned by `fixture.debugElement`, you can walk \(and query\) the fixture's entire element and component subtrees. Here are the most useful `DebugElement` members for testers, in approximate order of utility: | Members | Details | |:--- |:--- | | `nativeElement` | The corresponding DOM element in the browser | | `query` | Calling `query(predicate: Predicate<DebugElement>)` returns the first `DebugElement` that matches the [predicate](#query-predicate) at any depth in the subtree. | | `queryAll` | Calling `queryAll(predicate: Predicate<DebugElement>)` returns all `DebugElements` that matches the [predicate](#query-predicate) at any depth in subtree. | | `injector` | The host dependency injector. For example, the root element's component instance injector. | | `componentInstance` | The element's own component instance, if it has one. | | `context` | An object that provides parent context for this element. Often an ancestor component instance that governs this element. <br /> When an element is repeated within `*ngFor`, the context is an `NgForOf` whose `$implicit` property is the value of the row instance value. For example, the `hero` in `*ngFor="let hero of heroes"`. | | `children` | The immediate `DebugElement` children. Walk the tree by descending through `children`. `DebugElement` also has `childNodes`, a list of `DebugNode` objects. `DebugElement` derives from `DebugNode` objects and there are often more nodes than elements. Testers can usually ignore plain nodes. | | `parent` | The `DebugElement` parent. Null if this is the root element. | | `name` | The element tag name, if it is an element. | | `triggerEventHandler` | Triggers the event by its name if there is a corresponding listener in the element's `listeners` collection. The second parameter is the *event object* expected by the handler. See [triggerEventHandler](guide/testing/components-scenarios#trigger-event-handler). <br /> If the event lacks a listener or there's some other problem, consider calling `nativeElement.dispatchEvent(eventObject)`. | | `listeners` | The callbacks attached to the component's `@Output` properties and/or the element's event properties. | | `providerTokens` | This component's injector lookup tokens. Includes the component itself plus the tokens that the component lists in its `providers` metadata. | | `source` | Where to find this element in the source component template. | | `references` | Dictionary of objects associated with template local variables \(for example, `#foo`\), keyed by the local variable name. | The `DebugElement.query(predicate)` and `DebugElement.queryAll(predicate)` methods take a predicate that filters the source element's subtree for matching `DebugElement`. The predicate is any method that takes a `DebugElement` and returns a *truthy* value. The following example finds all `DebugElements` with a reference to a template local variable named "content": <docs-code header="app/demo/demo.testbed.spec.ts" path="adev/src/content/examples/testing/src/app/demo/demo.testbed.spec.ts" visibleRegion="custom-predicate"/> The Angular `By` class has three static methods for common predicates: | Static method | Details | |:--- |:--- | | `By.all` | Return all elements | | `By.css(selector)` | Return elements with matching CSS selectors | | `By.directive(directive)` | Return elements that Angular matched to an instance of the directive class | <docs-code header="app/hero/hero-list.component.spec.ts" path="adev/src/content/examples/testing/src/app/hero/hero-list.component.spec.ts" visibleRegion="by"/>
004619
## Component with async service In this sample, the `AboutComponent` template hosts a `TwainComponent`. The `TwainComponent` displays Mark Twain quotes. <docs-code header="app/twain/twain.component.ts (template)" path="adev/src/content/examples/testing/src/app/twain/twain.component.ts" visibleRegion="template" /> HELPFUL: The value of the component's `quote` property passes through an `AsyncPipe`. That means the property returns either a `Promise` or an `Observable`. In this example, the `TwainComponent.getQuote()` method tells you that the `quote` property returns an `Observable`. <docs-code header="app/twain/twain.component.ts (getQuote)" path="adev/src/content/examples/testing/src/app/twain/twain.component.ts" visibleRegion="get-quote"/> The `TwainComponent` gets quotes from an injected `TwainService`. The component starts the returned `Observable` with a placeholder value \(`'...'`\), before the service can return its first quote. The `catchError` intercepts service errors, prepares an error message, and returns the placeholder value on the success channel. These are all features you'll want to test. ### Testing with a spy When testing a component, only the service's public API should matter. In general, tests themselves should not make calls to remote servers. They should emulate such calls. The setup in this `app/twain/twain.component.spec.ts` shows one way to do that: <docs-code header="app/twain/twain.component.spec.ts (setup)" path="adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts" visibleRegion="setup"/> Focus on the spy. <docs-code path="adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts" visibleRegion="spy"/> The spy is designed such that any call to `getQuote` receives an observable with a test quote. Unlike the real `getQuote()` method, this spy bypasses the server and returns a synchronous observable whose value is available immediately. You can write many useful tests with this spy, even though its `Observable` is synchronous. HELPFUL: It is best to limit the usage of spies to only what is necessary for the test. Creating mocks or spies for more than what's necessary can be brittle. As the component and injectable evolves, the unrelated tests can fail because they no longer mock enough behaviors that would otherwise not affect the test. ### Async test with `fakeAsync()` To use `fakeAsync()` functionality, you must import `zone.js/testing` in your test setup file. If you created your project with the Angular CLI, `zone-testing` is already imported in `src/test.ts`. The following test confirms the expected behavior when the service returns an `ErrorObservable`. <docs-code path="adev/src/content/examples/testing/src/app/twain/twain.component.spec.ts" visibleRegion="error-test"/> HELPFUL: The `it()` function receives an argument of the following form. <docs-code language="javascript"> fakeAsync(() => { /*test body*/ }) </docs-code> The `fakeAsync()` function enables a linear coding style by running the test body in a special `fakeAsync test zone`. The test body appears to be synchronous. There is no nested syntax \(like a `Promise.then()`\) to disrupt the flow of control. HELPFUL: Limitation: The `fakeAsync()` function won't work if the test body makes an `XMLHttpRequest` \(XHR\) call. XHR calls within a test are rare, but if you need to call XHR, see the [`waitForAsync()`](#waitForAsync) section. IMPORTANT: Be aware that asynchronous tasks that happen inside the `fakeAsync` zone need to be manually executed with `flush` or `tick`. If you attempt to wait for them to complete (i.e. using `fixture.whenStable`) without using the `fakeAsync` test helpers to advance time, your test will likely fail. See below for more information. ### The `tick()` function You do have to call [tick()](api/core/testing/tick) to advance the virtual clock. Calling [tick()](api/core/testing/tick) simulates the passage of time until all pending asynchronous activities finish. In this case, it waits for the observable's `setTimeout()`. The [tick()](api/core/testing/tick) function accepts `millis` and `tickOptions` as parameters. The `millis` parameter specifies how much the virtual clock advances and defaults to `0` if not provided. For example, if you have a `setTimeout(fn, 100)` in a `fakeAsync()` test, you need to use `tick(100)` to trigger the fn callback. The optional `tickOptions` parameter has a property named `processNewMacroTasksSynchronously`. The `processNewMacroTasksSynchronously` property represents whether to invoke new generated macro tasks when ticking and defaults to `true`. <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-tick"/> The [tick()](api/core/testing/tick) function is one of the Angular testing utilities that you import with `TestBed`. It's a companion to `fakeAsync()` and you can only call it within a `fakeAsync()` body. ### tickOptions In this example, you have a new macro task, the nested `setTimeout` function. By default, when the `tick` is setTimeout, `outside` and `nested` will both be triggered. <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-tick-new-macro-task-sync"/> In some case, you don't want to trigger the new macro task when ticking. You can use `tick(millis, {processNewMacroTasksSynchronously: false})` to not invoke a new macro task. <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-tick-new-macro-task-async"/> ### Comparing dates inside fakeAsync() `fakeAsync()` simulates passage of time, which lets you calculate the difference between dates inside `fakeAsync()`. <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-date"/> ### jasmine.clock with fakeAsync() Jasmine also provides a `clock` feature to mock dates. Angular automatically runs tests that are run after `jasmine.clock().install()` is called inside a `fakeAsync()` method until `jasmine.clock().uninstall()` is called. `fakeAsync()` is not needed and throws an error if nested. By default, this feature is disabled. To enable it, set a global flag before importing `zone-testing`. If you use the Angular CLI, configure this flag in `src/test.ts`. <docs-code language="typescript"> [window as any]('&lowbar;&lowbar;zone&lowbar;symbol__fakeAsyncPatchLock') = true; import 'zone.js/testing'; </docs-code> <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-clock"/> ### Using the RxJS scheduler inside fakeAsync() You can also use RxJS scheduler in `fakeAsync()` just like using `setTimeout()` or `setInterval()`, but you need to import `zone.js/plugins/zone-patch-rxjs-fake-async` to patch RxJS scheduler. <docs-code path="adev/src/content/examples/testing/src/app/demo/async-helper.spec.ts" visibleRegion="fake-async-test-rxjs"/> ### Support more macroTasks By default, `fakeAsync()` supports the following macro tasks. * `setTimeout` * `setInterval` * `requestAnimationFrame` * `webkitRequestAnimationFrame` * `mozRequestAnimationFrame` If you run other macro tasks such as `HTMLCanvasElement.toBlob()`, an *"Unknown macroTask scheduled in fake async test"* error is thrown. <docs-code-multifile> <docs-code header="src/app/shared/canvas.component.spec.ts (failing)" path="adev/src/content/examples/testing/src/app/shared/canvas.component.spec.ts" visibleRegion="without-toBlob-macrotask"/> <docs-code header="src/app/shared/canvas.component.ts" path="adev/src/content/examples/testing/src/app/shared/canvas.component.ts" visibleRegion="main"/> </docs-code-multifile> If you want to support such a case, you need to define the macro task you want to support in `beforeEach()`. For example: <docs-code header="src/app/shared/canvas.component.spec.ts (excerpt)" path="adev/src/content/examples/testing/src/app/shared/canvas.component.spec.ts" visibleRegion="enable-toBlob-macrotask"/> HELPFUL: In order to make the `<canvas>` element Zone.js-aware in your app, you need to import the `zone-patch-canvas` patch \(either in `polyfills.ts` or in the specific file that uses `<canvas>`\): <docs-code header="src/polyfills.ts or src/app/shared/canvas.component.ts" path="adev/src/content/examples/testing/src/app/shared/canvas.component.ts" visibleRegion="import-canvas-patch"/>
004623
Calling `compileComponents()` HELPFUL: Ignore this section if you *only* run tests with the CLI `ng test` command because the CLI compiles the application before running the tests. If you run tests in a **non-CLI environment**, the tests might fail with a message like this one: <docs-code hideCopy language="shell"> Error: This test module uses the component BannerComponent which is using a "templateUrl" or "styleUrls", but they were never compiled. Please call "TestBed.compileComponents" before your test. </docs-code> The root of the problem is at least one of the components involved in the test specifies an external template or CSS file as the following version of the `BannerComponent` does. <docs-code header="app/banner/banner-external.component.ts (external template & css)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.ts"/> The test fails when the `TestBed` tries to create the component. <docs-code avoid header="app/banner/banner-external.component.spec.ts (setup that fails)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.spec.ts" visibleRegion="setup-may-fail"/> Recall that the application hasn't been compiled. So when you call `createComponent()`, the `TestBed` compiles implicitly. That's not a problem when the source code is in memory. But the `BannerComponent` requires external files that the compiler must read from the file system, an inherently *asynchronous* operation. If the `TestBed` were allowed to continue, the tests would run and fail mysteriously before the compiler could finish. The preemptive error message tells you to compile explicitly with `compileComponents()`. ### `compileComponents()` is async You must call `compileComponents()` within an asynchronous test function. CRITICAL: If you neglect to make the test function async (for example, forget to use `waitForAsync()` as described), you'll see this error message <docs-code hideCopy language="shell"> Error: ViewDestroyedError: Attempt to use a destroyed view </docs-code> A typical approach is to divide the setup logic into two separate `beforeEach()` functions: | Functions | Details | | :-------------------------- | :--------------------------- | | Asynchronous `beforeEach()` | Compiles the components | | Synchronous `beforeEach()` | Performs the remaining setup | ### The async `beforeEach` Write the first async `beforeEach` like this. <docs-code header="app/banner/banner-external.component.spec.ts (async beforeEach)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.spec.ts" visibleRegion="async-before-each"/> The `TestBed.configureTestingModule()` method returns the `TestBed` class so you can chain calls to other `TestBed` static methods such as `compileComponents()`. In this example, the `BannerComponent` is the only component to compile. Other examples configure the testing module with multiple components and might import application modules that hold yet more components. Any of them could require external files. The `TestBed.compileComponents` method asynchronously compiles all components configured in the testing module. IMPORTANT: Do not re-configure the `TestBed` after calling `compileComponents()`. Calling `compileComponents()` closes the current `TestBed` instance to further configuration. You cannot call any more `TestBed` configuration methods, not `configureTestingModule()` nor any of the `override...` methods. The `TestBed` throws an error if you try. Make `compileComponents()` the last step before calling `TestBed.createComponent()`. ### The synchronous `beforeEach` The second, synchronous `beforeEach()` contains the remaining setup steps, which include creating the component and querying for elements to inspect. <docs-code header="app/banner/banner-external.component.spec.ts (synchronous beforeEach)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.spec.ts" visibleRegion="sync-before-each"/> Count on the test runner to wait for the first asynchronous `beforeEach` to finish before calling the second. ### Consolidated setup You can consolidate the two `beforeEach()` functions into a single, async `beforeEach()`. The `compileComponents()` method returns a promise so you can perform the synchronous setup tasks *after* compilation by moving the synchronous code after the `await` keyword, where the promise has been resolved. <docs-code header="app/banner/banner-external.component.spec.ts (one beforeEach)" path="adev/src/content/examples/testing/src/app/banner/banner-external.component.spec.ts" visibleRegion="one-before-each"/> ### `compileComponents()` is harmless There's no harm in calling `compileComponents()` when it's not required. The component test file generated by the CLI calls `compileComponents()` even though it is never required when running `ng test`. The tests in this guide only call `compileComponents` when necessary. ## Setup with module imports Earlier component tests configured the testing module with a few `declarations` like this: <docs-code header="app/dashboard/dashboard-hero.component.spec.ts (configure TestBed)" path="adev/src/content/examples/testing/src/app/dashboard/dashboard-hero.component.spec.ts" visibleRegion="config-testbed"/> The `DashboardComponent` is simple. It needs no help. But more complex components often depend on other components, directives, pipes, and providers and these must be added to the testing module too. Fortunately, the `TestBed.configureTestingModule` parameter parallels the metadata passed to the `@NgModule` decorator which means you can also specify `providers` and `imports`. The `HeroDetailComponent` requires a lot of help despite its small size and simple construction. In addition to the support it receives from the default testing module `CommonModule`, it needs: * `NgModel` and friends in the `FormsModule` to enable two-way data binding * The `TitleCasePipe` from the `shared` folder * The Router services * The Hero data access services One approach is to configure the testing module from the individual pieces as in this example: <docs-code header="app/hero/hero-detail.component.spec.ts (FormsModule setup)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="setup-forms-module"/> HELPFUL: Notice that the `beforeEach()` is asynchronous and calls `TestBed.compileComponents` because the `HeroDetailComponent` has an external template and css file. As explained in [Calling `compileComponents()`](#calling-compilecomponents), these tests could be run in a non-CLI environment where Angular would have to compile them in the browser. ### Import a shared module Because many application components need the `FormsModule` and the `TitleCasePipe`, the developer created a `SharedModule` to combine these and other frequently requested parts. The test configuration can use the `SharedModule` too as seen in this alternative setup: <docs-code header="app/hero/hero-detail.component.spec.ts (SharedModule setup)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="setup-shared-module"/> It's a bit tighter and smaller, with fewer import statements, which are not shown in this example. ### Import a feature module The `HeroDetailComponent` is part of the `HeroModule` [Feature Module](guide/ngmodules/feature-modules) that aggregates more of the interdependent pieces including the `SharedModule`. Try a test configuration that imports the `HeroModule` like this one: <docs-code header="app/hero/hero-detail.component.spec.ts (HeroModule setup)" path="adev/src/content/examples/testing/src/app/hero/hero-detail.component.spec.ts" visibleRegion="setup-hero-module"/> Only the *test doubles* in the `providers` remain. Even the `HeroDetailComponent` declaration is gone. In fact, if you try to declare it, Angular will throw an error because `HeroDetailComponent` is declared in both the `HeroModule` and the `DynamicTestModule` created by the `TestBed`. HELPFUL: Importing the component's feature module can be the best way to configure tests when there are many mutual dependencies within the module and the module is small, as feature modules tend to be. ##
004625
# Component Lifecycle Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. A component's **lifecycle** is the sequence of steps that happen between the component's creation and its destruction. Each step represents a different part of Angular's process for rendering components and checking them for updates over time. In your components, you can implement **lifecycle hooks** to run code during these steps. Lifecycle hooks that relate to a specific component instance are implemented as methods on your component class. Lifecycle hooks that relate the Angular application as a whole are implemented as functions that accept a callback. A component's lifecycle is tightly connected to how Angular checks your components for changes over time. For the purposes of understanding this lifecycle, you only need to know that Angular walks your application tree from top to bottom, checking template bindings for changes. The lifecycle hooks described below run while Angular is doing this traversal. This traversal visits each component exactly once, so you should always avoid making further state changes in the middle of the process. ## Summary <div class="docs-table docs-scroll-track-transparent"> <table> <tr> <td><strong>Phase</strong></td> <td><strong>Method</strong></td> <td><strong>Summary</strong></td> </tr> <tr> <td>Creation</td> <td><code>constructor</code></td> <td> <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Classes/constructor" target="_blank"> Standard JavaScript class constructor </a>. Runs when Angular instantiates the component. </td> </tr> <tr> <td rowspan="7">Change<p>Detection</td> <td><code>ngOnInit</code> </td> <td>Runs once after Angular has initialized all the component's inputs.</td> </tr> <tr> <td><code>ngOnChanges</code></td> <td>Runs every time the component's inputs have changed.</td> </tr> <tr> <td><code>ngDoCheck</code></td> <td>Runs every time this component is checked for changes.</td> </tr> <tr> <td><code>ngAfterContentInit</code></td> <td>Runs once after the component's <em>content</em> has been initialized.</td> </tr> <tr> <td><code>ngAfterContentChecked</code></td> <td>Runs every time this component content has been checked for changes.</td> </tr> <tr> <td><code>ngAfterViewInit</code></td> <td>Runs once after the component's <em>view</em> has been initialized.</td> </tr> <tr> <td><code>ngAfterViewChecked</code></td> <td>Runs every time the component's view has been checked for changes.</td> </tr> <tr> <td rowspan="2">Rendering</td> <td><code>afterNextRender</code></td> <td>Runs once the next time that <strong>all</strong> components have been rendered to the DOM.</td> </tr> <tr> <td><code>afterRender</code></td> <td>Runs every time <strong>all</strong> components have been rendered to the DOM.</td> </tr> <tr> <td>Destruction</td> <td><code>ngOnDestroy</code></td> <td>Runs once before the component is destroyed.</td> </tr> </table> </div> ### ngOnInit The `ngOnInit` method runs after Angular has initialized all the components inputs with their initial values. A component's `ngOnInit` runs exactly once. This step happens _before_ the component's own template is initialized. This means that you can update the component's state based on its initial input values. ### ngOnChanges The `ngOnChanges` method runs after any component inputs have changed. This step happens _before_ the component's own template is checked. This means that you can update the component's state based on its initial input values. During initialization, the first `ngOnChanges` runs before `ngOnInit`. #### Inspecting changes The `ngOnChanges` method accepts one `SimpleChanges` argument. This object is a [`Record`](https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type) mapping each component input name to a `SimpleChange` object. Each `SimpleChange` contains the input's previous value, its current value, and a flag for whether this is the first time the input has changed. ```ts @Component({ /* ... */ }) export class UserProfile { @Input() name: string = ''; ngOnChanges(changes: SimpleChanges) { for (const inputName in changes) { const inputValues = changes[inputName]; console.log(`Previous ${inputName} == ${inputValues.previousValue}`); console.log(`Current ${inputName} == ${inputValues.currentValue}`); console.log(`Is first ${inputName} change == ${inputValues.firstChange}`); } } } ``` If you provide an `alias` for any input properties, the `SimpleChanges` Record still uses the TypeScript property name as a key, rather than the alias. ### ngOnDestroy The `ngOnDestroy` method runs once just before a component is destroyed. Angular destroys a component when it is no longer shown on the page, such as being hidden by `NgIf` or upon navigating to another page. #### DestroyRef As an alternative to the `ngOnDestroy` method, you can inject an instance of `DestroyRef`. You can register a callback to be invoked upon the component's destruction by calling the `onDestroy` method of `DestroyRef`. ```ts @Component({ /* ... */ }) export class UserProfile { constructor(private destroyRef: DestroyRef) { destroyRef.onDestroy(() => { console.log('UserProfile destruction'); }); } } ``` You can pass the `DestroyRef` instance to functions or classes outside your component. Use this pattern if you have other code that should run some cleanup behavior when the component is destroyed. You can also use `DestroyRef` to keep setup code close to cleanup code, rather than putting all cleanup code in the `ngOnDestroy` method. ### ngDoCheck The `ngDoCheck` method runs before every time Angular checks a component's template for changes. You can use this lifecycle hook to manually check for state changes outside of Angular's normal change detection, manually updating the component's state. This method runs very frequently and can significantly impact your page's performance. Avoid defining this hook whenever possible, only using it when you have no alternative. During initialization, the first `ngDoCheck` runs after `ngOnInit`. ### ngAfterContentInit The `ngAfterContentInit` method runs once after all the children nested inside the component (its _content_) have been initialized. You can use this lifecycle hook to read the results of [content queries](guide/components/queries#content-queries). While you can access the initialized state of these queries, attempting to change any state in this method results in an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100) ### ngAfterContentChecked The `ngAfterContentChecked` method runs every time the children nested inside the component (its _content_) have been checked for changes. This method runs very frequently and can significantly impact your page's performance. Avoid defining this hook whenever possible, only using it when you have no alternative. While you can access the updated state of [content queries](guide/components/queries#content-queries) here, attempting to change any state in this method results in an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100). ### ngAfterViewInit The `ngAfterViewInit` method runs once after all the children in the component's template (its _view_) have been initialized. You can use this lifecycle hook to read the results of [view queries](guide/components/queries#view-queries). While you can access the initialized state of these queries, attempting to change any state in this method results in an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100) ### ngAfterViewChecked The `ngAfterViewChecked` method runs every time the children in the component's template (its _view_) have been checked for changes. This method runs very frequently and can significantly impact your page's performance. Avoid defining this hook whenever possible, only using it when you have no alternative. While you can access the updated state of [view queries](guide/components/queries#view-queries) here, attempting to change any state in this method results in an [ExpressionChangedAfterItHasBeenCheckedError](errors/NG0100).
004626
### afterRender and afterNextRender The `afterRender` and `afterNextRender` functions let you register a **render callback** to be invoked after Angular has finished rendering _all components_ on the page into the DOM. These functions are different from the other lifecycle hooks described in this guide. Rather than a class method, they are standalone functions that accept a callback. The execution of render callbacks are not tied to any specific component instance, but instead an application-wide hook. `afterRender` and `afterNextRender` must be called in an [injection context](guide/di/dependency-injection-context), typically a component's constructor. You can use render callbacks to perform manual DOM operations. See [Using DOM APIs](guide/components/dom-apis) for guidance on working with the DOM in Angular. Render callbacks do not run during server-side rendering or during build-time pre-rendering. #### afterRender phases When using `afterRender` or `afterNextRender`, you can optionally split the work into phases. The phase gives you control over the sequencing of DOM operations, letting you sequence _write_ operations before _read_ operations in order to minimize [layout thrashing](https://web.dev/avoid-large-complex-layouts-and-layout-thrashing). In order to communicate across phases, a phase function may return a result value that can be accessed in the next phase. ```ts import {Component, ElementRef, afterNextRender} from '@angular/core'; @Component({...}) export class UserProfile { private prevPadding = 0; private elementHeight = 0; constructor(elementRef: ElementRef) { const nativeElement = elementRef.nativeElement; afterNextRender({ // Use the `Write` phase to write to a geometric property. write: () => { const padding = computePadding(); const changed = padding !== prevPadding; if (changed) { nativeElement.style.padding = padding; } return changed; // Communicate whether anything changed to the read phase. }, // Use the `Read` phase to read geometric properties after all writes have occurred. read: (didWrite) => { if (didWrite) { this.elementHeight = nativeElement.getBoundingClientRect().height; } } }); } } ``` There are four phases, run in the following order: | Phase | Description | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `earlyRead` | Use this phase to read any layout-affecting DOM properties and styles that are strictly necessary for subsequent calculation. Avoid this phase if possible, preferring the `write` and `read` phases. | | `mixedReadWrite` | Default phase. Use for any operations need to both read and write layout-affecting properties and styles. Avoid this phase if possible, preferring the explicit `write` and `read` phases. | | `write` | Use this phase to write layout-affecting DOM properties and styles. | | `read` | Use this phase to read any layout-affecting DOM properties. | ## Lifecycle interfaces Angular provides a TypeScript interface for each lifecycle method. You can optionally import and `implement` these interfaces to ensure that your implementation does not have any typos or misspellings. Each interface has the same name as the corresponding method without the `ng` prefix. For example, the interface for `ngOnInit` is `OnInit`. ```ts @Component({ /* ... */ }) export class UserProfile implements OnInit { ngOnInit() { /* ... */ } } ``` ## Execution order The following diagrams show the execution order of Angular's lifecycle hooks. ### During initialization ```mermaid graph TD; id[constructor]-->CHANGE; subgraph CHANGE [Change detection] direction TB ngOnChanges-->ngOnInit; ngOnInit-->ngDoCheck; ngDoCheck-->ngAfterContentInit; ngDoCheck-->ngAfterViewInit ngAfterContentInit-->ngAfterContentChecked ngAfterViewInit-->ngAfterViewChecked end CHANGE--Rendering-->afterRender ``` ### Subsequent updates ```mermaid graph TD; subgraph CHANGE [Change detection] direction TB ngOnChanges-->ngDoCheck ngDoCheck-->ngAfterContentChecked; ngDoCheck-->ngAfterViewChecked end CHANGE--Rendering-->afterRender ``` ### Ordering with directives When you put one or more directives on the same element as a component, either in a template or with the `hostDirectives` property, the framework does not guarantee any ordering of a given lifecycle hook between the component and the directives on a single element. Never depend on an observed ordering, as this may change in later versions of Angular.
004632
# Advanced component configuration Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. ## ChangeDetectionStrategy The `@Component` decorator accepts a `changeDetection` option that controls the component's **change detection mode**. There are two change detection mode options. **`ChangeDetectionStrategy.Default`** is, unsurprisingly, the default strategy. In this mode, Angular checks whether the component's DOM needs an update whenever any activity may have occurred application-wide. Activities that trigger this checking include user interaction, network response, timers, and more. **`ChangeDetectionStrategy.OnPush`** is an optional mode that reduces the amount of checking Angular needs to perform. In this mode, the framework only checks if a component's DOM needs an update when: - A component input has changes as a result of a binding in a template, or - An event listener in this component runs - The component is explicitly marked for check, via `ChangeDetectorRef.markForCheck` or something which wraps it, like `AsyncPipe`. Additionally, when an OnPush component is checked, Angular _also_ checks all of its ancestor components, traversing upwards through the application tree. ## PreserveWhitespaces By default, Angular removes and collapses superfluous whitespace in templates, most commonly from newlines and indentation. You can change this setting by explicitly setting `preserveWhitespaces` to `true` in a component's metadata. ## Custom element schemas By default, Angular throws an error when it encounters an unknown HTML element. You can disable this behavior for a component by including `CUSTOM_ELEMENTS_SCHEMA` in the `schemas` property in your component metadata. ```angular-ts import {Component, CUSTOM_ELEMENTS_SCHEMA} from '@angular/core'; @Component({ ..., schemas: [CUSTOM_ELEMENTS_SCHEMA], template: '<some-unknown-component></some-unknown-component>' }) export class ComponentWithCustomElements { } ``` Angular does not support any other schemas at this time.
004633
# Function-based outputs The `output()` function declares an output in a directive or component. Outputs allow you to emit values to parent components. <docs-code language="ts" highlight="[[5], [8]]"> import {Component, output} from '@angular/core'; @Component({...}) export class MyComp { nameChange = output<string>() // OutputEmitterRef<string> setNewName(newName: string) { this.nameChange.emit(newName); } } </docs-code> An output is automatically recognized by Angular whenever you use the `output` function as an initializer of a class member. Parent components can listen to outputs in templates by using the event binding syntax. ```angular-html <my-comp (nameChange)="showNewName($event)" /> ``` ## Aliasing an output Angular uses the class member name as the name of the output. You can alias outputs to change their public name to be different. ```typescript class MyComp { nameChange = output({alias: 'ngxNameChange'}); } ``` This allows users to bind to your output using `(ngxNameChange)`, while inside your component you can access the output emitter using `this.nameChange`. ## Subscribing programmatically Consumers may create your component dynamically with a reference to a `ComponentRef`. In those cases, parents can subscribe to outputs by directly accessing the property of type `OutputRef`. ```ts const myComp = viewContainerRef.createComponent(...); myComp.instance.nameChange.subscribe(newName => { console.log(newName); }); ``` Angular will automatically clean up the subscription when `myComp` is destroyed. Alternatively, an object with a function to explicitly unsubscribe earlier is returned. ## Using RxJS observables as source In some cases, you may want to emit output values based on RxJS observables. Angular provides a way to use RxJS observables as source for outputs. The `outputFromObservable` function is a compiler primitive, similar to the `output()` function, and declares outputs that are driven by RxJS observables. <docs-code language="ts" highlight="[7]"> import {Directive} from '@angular/core'; import {outputFromObservable} from '@angular/core/rxjs-interop'; @Directive(...) class MyDir { nameChange$ = this.dataService.get(); // Observable<Data> nameChange = outputFromObservable(this.nameChange$); } </docs-code> Angular will forward subscriptions to the observable, but will stop forwarding values when the owning directive is destroyed. In the example above, if `MyDir` is destroyed, `nameChange` will no longer emit values. HELPFUL: Most of the time, using `output()` is sufficient and you can emit values imperatively. ## Converting an output to an observable You can subscribe to outputs by calling `.subscribe` method on `OutputRef`. In other cases, Angular provides a helper function that converts an `OutputRef` to an observable. <docs-code language="ts" highlight="[11]"> import {outputToObservable} from '@angular/core/rxjs-interop'; @Component(...) class MyComp { nameChange = output<string>(); } // Instance reference to `MyComp`. const myComp: MyComp; outputToObservable(this.myComp.instance.nameChange) // Observable<string> .pipe(...) .subscribe(...); </docs-code> ## Why you should use `output()` over decorator-based `@Output()`? The `output()` function provides numerous benefits over decorator-based `@Output` and `EventEmitter`: 1. Simpler mental model and API: <br/>• No concept of error channel, completion channels, or other APIs from RxJS. <br/>• Outputs are simple emitters. You can emit values using the `.emit` function. 2. More accurate types. <br/>• `OutputEmitterRef.emit(value)` is now correctly typed, while `EventEmitter` has broken types and can cause runtime errors.
004636
# Importing and using components Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Angular supports two ways of making a component available to other components: as a standalone component or in an `NgModule`. ## Standalone components A **standalone component** is a component that sets `standalone: true` in its component metadata. Standalone components directly import other components, directives, and pipes used in their templates: <docs-code language="angular-ts" highlight="[2, [8, 9]]"> @Component({ standalone: true, selector: 'profile-photo', }) export class ProfilePhoto { } @Component({ standalone: true, imports: [ProfilePhoto], template: `<profile-photo />` }) export class UserProfile { } </docs-code> Standalone components are directly importable into other standalone components. The Angular team recommends using standalone components for all new development. ## NgModules Angular code that predates standalone components uses `NgModule` as a mechanism for importing and using other components. See the full [`NgModule` guide](guide/ngmodules) for details.
004639
# Component selectors Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. Every component defines a [CSS selector](https://developer.mozilla.org/docs/Web/CSS/CSS_selectors) that determines how the component is used: <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: 'profile-photo', ... }) export class ProfilePhoto { } </docs-code> You use a component by creating a matching HTML element in the templates of _other_ components: <docs-code language="angular-ts" highlight="[3]"> @Component({ template: ` <profile-photo /> <button>Upload a new profile photo</button>`, ..., }) export class UserProfile { } </docs-code> **Angular matches selectors statically at compile-time**. Changing the DOM at run-time, either via Angular bindings or with DOM APIs, does not affect the components rendered. **An element can match exactly one component selector.** If multiple component selectors match a single element, Angular reports an error. **Component selectors are case-sensitive.** ## Types of selectors Angular supports a limited subset of [basic CSS selector types](https://developer.mozilla.org/docs/Web/CSS/CSS_Selectors) in component selectors: | **Selector type** | **Description** | **Examples** | | ------------------ | --------------------------------------------------------------------------------------------------------------- | ----------------------------- | | Type selector | Matches elements based on their HTML tag name, or node name. | `profile-photo` | | Attribute selector | Matches elements based on the presence of an HTML attribute and, optionally, an exact value for that attribute. | `[dropzone]` `[type="reset"]` | | Class selector | Matches elements based on the presence of a CSS class. | `.menu-item` | For attribute values, Angular supports matching an exact attribute value with the equals (`=`) operator. Angular does not support other attribute value operators. Angular component selectors do not support combinators, including the [descendant combinator](https://developer.mozilla.org/docs/Web/CSS/Descendant_combinator) or [child combinator](https://developer.mozilla.org/docs/Web/CSS/Child_combinator). Angular component selectors do not support specifying [namespaces](https://developer.mozilla.org/docs/Web/SVG/Namespaces_Crash_Course). ### The `:not` pseudo-class Angular supports [the `:not` pseudo-class](https://developer.mozilla.org/docs/Web/CSS/:not). You can append this pseudo-class to any other selector to narrow which elements a component's selector matches. For example, you could define a `[dropzone]` attribute selector and prevent matching `textarea` elements: <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: '[dropzone]:not(textarea)', ... }) export class DropZone { } </docs-code> Angular does not support any other pseudo-classes or pseudo-elements in component selectors. ### Combining selectors You can combine multiple selectors by concatenating them. For example, you can match `<button>` elements that specify `type="reset"`: <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: 'button[type="reset"]', ... }) export class ResetButton { } </docs-code> You can also define multiple selectors with a comma-separated list: <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: 'drop-zone, [dropzone]', ... }) export class DropZone { } </docs-code> Angular creates a component for each element that matches _any_ of the selectors in the list. ## Choosing a selector The vast majority of components should use a custom element name as their selector. All custom element names should include a hyphen as described by [the HTML specification](https://html.spec.whatwg.org/multipage/custom-elements.html#valid-custom-element-name). By default, Angular reports an error if it encounters a custom tag name that does not match any available components, preventing bugs due to mistyped component names. See [Advanced component configuration](guide/components/advanced-configuration) for details on using [native custom elements](https://developer.mozilla.org/docs/Web/Web_Components) in Angular templates. ### Selector prefixes The Angular team recommends using a short, consistent prefix for all the custom components defined inside your project. For example, if you were to build YouTube with Angular, you might prefix your components with `yt-`, with components like `yt-menu`, `yt-player`, etc. Namespacing your selectors like this makes it immediately clear where a particular component comes from. By default, the Angular CLI uses `app-`. Angular uses the `ng` selector prefix for its own framework APIs. Never use `ng` as a selector prefix for your own custom components. ### When to use an attribute selector You should consider an attribute selector when you want to create a component on a standard native element. For example, if you want to create a custom button component, you can take advantage of the standard `<button>` element by using an attribute selector: <docs-code language="angular-ts" highlight="[2]"> @Component({ selector: 'button[yt-upload]', ... }) export class YouTubeUploadButton { } </docs-code> This approach allows consumers of the component to directly use all the element's standard APIs without extra work. This is especially valuable for ARIA attributes such as `aria-label`. Angular does not report errors when it encounters custom attributes that don't match an available component. When using components with attribute selectors, consumers may forget to import the component or its NgModule, resulting in the component not rendering. See [Importing and using components](guide/components/importing) for more information. Components that define attribute selectors should use lowercase, dash-case attributes. You can follow the same prefixing recommendation described above.
004642
# Programmatically rendering components Tip: This guide assumes you've already read the [Essentials Guide](essentials). Read that first if you're new to Angular. In addition to using a component directly in a template, you can also dynamically render components. There are two main ways to dynamically render a component: in a template with `NgComponentOutlet`, or in your TypeScript code with `ViewContainerRef`. ## Using NgComponentOutlet `NgComponentOutlet` is a structural directive that dynamically renders a given component in a template. ```angular-ts @Component({ ... }) export class AdminBio { /* ... */ } @Component({ ... }) export class StandardBio { /* ... */ } @Component({ ..., template: ` <p>Profile for {{user.name}}</p> <ng-container *ngComponentOutlet="getBioComponent()" /> ` }) export class CustomDialog { @Input() user: User; getBioComponent() { return this.user.isAdmin ? AdminBio : StandardBio; } } ``` See the [NgComponentOutlet API reference](api/common/NgComponentOutlet) for more information on the directive's capabilities. ## Using ViewContainerRef A **view container** is a node in Angular's component tree that can contain content. Any component or directive can inject `ViewContainerRef` to get a reference to a view container corresponding to that component or directive's location in the DOM. You can use the `createComponent`method on `ViewContainerRef` to dynamically create and render a component. When you create a new component with a `ViewContainerRef`, Angular appends it into the DOM as the next sibling of the component or directive that injected the `ViewContainerRef`. ```angular-ts @Component({ selector: 'leaf-content', template: ` This is the leaf content `, }) export class LeafContent {} @Component({ selector: 'outer-container', template: ` <p>This is the start of the outer container</p> <inner-item /> <p>This is the end of the outer container</p> `, }) export class OuterContainer {} @Component({ selector: 'inner-item', template: ` <button (click)="loadContent()">Load content</button> `, }) export class InnerItem { constructor(private viewContainer: ViewContainerRef) {} loadContent() { this.viewContainer.createComponent(LeafContent); } } ``` In the example above, clicking the "Load content" button results in the following DOM structure ```angular-html <outer-container> <p>This is the start of the outer container</p> <inner-item> <button>Load content</button> </inner-item> <leaf-content>This is the leaf content</leaf-content> <p>This is the end of the outer container</p> </outer-container> ``` ## Lazy-loading components You can use both of the approaches described above, `NgComponentOutlet` and `ViewContainerRef`, to render components that are lazy-loaded with a standard JavaScript [dynamic import](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/import). ```angular-ts @Component({ ..., template: ` <section> <h2>Basic settings</h2> <basic-settings /> </section> <section> <h2>Advanced settings</h2> <button (click)="loadAdvanced()" *ngIf="!advancedSettings"> Load advanced settings </button> <ng-container *ngComponentOutlet="advancedSettings" /> </section> ` }) export class AdminSettings { advancedSettings: {new(): AdminSettings} | undefined; async loadAdvanced() { this.advancedSettings = await import('path/to/advanced_settings.js'); } } ``` The example above loads and displays the `AdvancedSettings` upon receiving a button click.
004644
# Setting up `HttpClient` Before you can use `HttpClient` in your app, you must configure it using [dependency injection](guide/di). ## Providing `HttpClient` through dependency injection `HttpClient` is provided using the `provideHttpClient` helper function, which most apps include in the application `providers` in `app.config.ts`. <docs-code language="ts"> export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), ] }; </docs-code> If your app is using NgModule-based bootstrap instead, you can include `provideHttpClient` in the providers of your app's NgModule: <docs-code language="ts"> @NgModule({ providers: [ provideHttpClient(), ], // ... other application configuration }) export class AppModule {} </docs-code> You can then inject the `HttpClient` service as a dependency of your components, services, or other classes: <docs-code language="ts"> @Injectable({providedIn: 'root'}) export class ConfigService { constructor(private http: HttpClient) { // This service can now make HTTP requests via `this.http`. } } </docs-code> ## Configuring features of `HttpClient` `provideHttpClient` accepts a list of optional feature configurations, to enable or configure the behavior of different aspects of the client. This section details the optional features and their usages. ### `withFetch` <docs-code language="ts"> export const appConfig: ApplicationConfig = { providers: [ provideHttpClient( withFetch(), ), ] }; </docs-code> By default, `HttpClient` uses the [`XMLHttpRequest`](https://developer.mozilla.org/docs/Web/API/XMLHttpRequest) API to make requests. The `withFetch` feature switches the client to use the [`fetch`](https://developer.mozilla.org/docs/Web/API/Fetch_API) API instead. `fetch` is a more modern API and is available in a few environments where `XMLHttpRequest` is not supported. It does have a few limitations, such as not producing upload progress events. ### `withInterceptors(...)` `withInterceptors` configures the set of interceptor functions which will process requests made through `HttpClient`. See the [interceptor guide](guide/http/interceptors) for more information. ### `withInterceptorsFromDi()` `withInterceptorsFromDi` includes the older style of class-based interceptors in the `HttpClient` configuration. See the [interceptor guide](guide/http/interceptors) for more information. HELPFUL: Functional interceptors (through `withInterceptors`) have more predictable ordering and we recommend them over DI-based interceptors. ### `withRequestsMadeViaParent()` By default, when you configure `HttpClient` using `provideHttpClient` within a given injector, this configuration overrides any configuration for `HttpClient` which may be present in the parent injector. When you add `withRequestsMadeViaParent()`, `HttpClient` is configured to instead pass requests up to the `HttpClient` instance in the parent injector, once they've passed through any configured interceptors at this level. This is useful if you want to _add_ interceptors in a child injector, while still sending the request through the parent injector's interceptors as well. CRITICAL: You must configure an instance of `HttpClient` above the current injector, or this option is not valid and you'll get a runtime error when you try to use it. ### `withJsonpSupport()` Including `withJsonpSupport` enables the `.jsonp()` method on `HttpClient`, which makes a GET request via the [JSONP convention](https://en.wikipedia.org/wiki/JSONP) for cross-domain loading of data. HELPFUL: Prefer using [CORS](https://developer.mozilla.org/docs/Web/HTTP/CORS) to make cross-domain requests instead of JSONP when possible. ### `withXsrfConfiguration(...)` Including this option allows for customization of `HttpClient`'s built-in XSRF security functionality. See the [security guide](best-practices/security) for more information. ### `withNoXsrfProtection()` Including this option disables `HttpClient`'s built-in XSRF security functionality. See the [security guide](best-practices/security) for more information. ## `HttpClientModule`-based configuration Some applications may configure `HttpClient` using the older API based on NgModules. This table lists the NgModules available from `@angular/common/http` and how they relate to the provider configuration functions above. | **NgModule** | `provideHttpClient()` equivalent | | --------------------------------------- | --------------------------------------------- | | `HttpClientModule` | `provideHttpClient(withInterceptorsFromDi())` | | `HttpClientJsonpModule` | `withJsonpSupport()` | | `HttpClientXsrfModule.withOptions(...)` | `withXsrfConfiguration(...)` | | `HttpClientXsrfModule.disable()` | `withNoXsrfProtection()` | <docs-callout important title="Use caution when using HttpClientModule in multiple injectors"> When `HttpClientModule` is present in multiple injectors, the behavior of interceptors is poorly defined and depends on the exact options and provider/import ordering. Prefer `provideHttpClient` for multi-injector configurations, as it has more stable behavior. See the `withRequestsMadeViaParent` feature above. </docs-callout>
004645
# Making HTTP requests `HttpClient` has methods corresponding to the different HTTP verbs used to make requests, both to load data and to apply mutations on the server. Each method returns an [RxJS `Observable`](https://rxjs.dev/guide/observable) which, when subscribed, sends the request and then emits the results when the server responds. Note: `Observable`s created by `HttpClient` may be subscribed any number of times and will make a new backend request for each subscription. Through an options object passed to the request method, various properties of the request and the returned response type can be adjusted. ## Fetching JSON data Fetching data from a backend often requires making a GET request using the [`HttpClient.get()`](api/common/http/HttpClient#get) method. This method takes two arguments: the string endpoint URL from which to fetch, and an *optional options* object to configure the request. For example, to fetch configuration data from a hypothetical API using the `HttpClient.get()` method: <docs-code language="ts"> http.get<Config>('/api/config').subscribe(config => { // process the configuration. }); </docs-code> Note the generic type argument which specifies that the data returned by the server will be of type `Config`. This argument is optional, and if you omit it then the returned data will have type `any`. Tip: If the data has an unknown shape, then a safer alternative to `any` is to use the `unknown` type as the response type. CRITICAL: The generic type of request methods is a type **assertion** about the data returned by the server. `HttpClient` does not verify that the actual return data matches this type. ## Fetching other types of data By default, `HttpClient` assumes that servers will return JSON data. When interacting with a non-JSON API, you can tell `HttpClient` what response type to expect and return when making the request. This is done with the `responseType` option. | **`responseType` value** | **Returned response type** | | - | - | | `'json'` (default) | JSON data of the given generic type | | `'text'` | string data | | `'arraybuffer'` | [`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing the raw response bytes | | `'blob'` | [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) instance | For example, you can ask `HttpClient` to download the raw bytes of a `.jpeg` image into an `ArrayBuffer`: <docs-code language="ts"> http.get('/images/dog.jpg', {responseType: 'arraybuffer'}).subscribe(buffer => { console.log('The image is ' + buffer.byteLength + ' bytes large'); }); </docs-code> <docs-callout important title="Literal value for `responseType`"> Because the value of `responseType` affects the type returned by `HttpClient`, it must have a literal type and not a `string` type. This happens automatically if the options object passed to the request method is a literal object, but if you're extracting the request options out into a variable or helper method you might need to explicitly specify it as a literal, such as `responseType: 'text' as const`. </docs-callout> ## Mutating server state Server APIs which perform mutations often require making POST requests with a request body specifying the new state or the change to be made. The [`HttpClient.post()`](api/common/http/HttpClient#post) method behaves similarly to `get()`, and accepts an additional `body` argument before its options: <docs-code language="ts"> http.post<Config>('/api/config', newConfig).subscribe(config => { console.log('Updated config:', config); }); </docs-code> Many different types of values can be provided as the request's `body`, and `HttpClient` will serialize them accordingly: | **`body` type** | **Serialized as** | | - | - | | string | Plain text | | number, boolean, array, or plain object | JSON | | [`ArrayBuffer`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) | raw data from the buffer | | [`Blob`](https://developer.mozilla.org/docs/Web/API/Blob) | raw data with the `Blob`'s content type | | [`FormData`](https://developer.mozilla.org/docs/Web/API/FormData) | `multipart/form-data` encoded data | | [`HttpParams`](api/common/http/HttpParams) or [`URLSearchParams`](https://developer.mozilla.org/docs/Web/API/URLSearchParams) | `application/x-www-form-urlencoded` formatted string | IMPORTANT: Remember to `.subscribe()` to mutation request `Observable`s in order to actually fire the request. ## Setting URL parameters Specify request parameters that should be included in the request URL using the `params` option. Passing an object literal is the simplest way of configuring URL parameters: <docs-code language="ts"> http.get('/api/config', { params: {filter: 'all'}, }).subscribe(config => { // ... }); </docs-code> Alternatively, pass an instance of `HttpParams` if you need more control over the construction or serialization of the parameters. IMPORTANT: Instances of `HttpParams` are _immutable_ and cannot be directly changed. Instead, mutation methods such as `append()` return a new instance of `HttpParams` with the mutation applied. <docs-code language="ts"> const baseParams = new HttpParams().set('filter', 'all'); http.get('/api/config', { params: baseParams.set('details', 'enabled'), }).subscribe(config => { // ... }); </docs-code> You can instantiate `HttpParams` with a custom `HttpParameterCodec` that determines how `HttpClient` will encode the parameters into the URL. ## Setting request headers Specify request headers that should be included in the request using the `headers` option. Passing an object literal is the simplest way of configuring request headers: <docs-code language="ts"> http.get('/api/config', { headers: { 'X-Debug-Level': 'verbose', } }).subscribe(config => { // ... }); </docs-code> Alternatively, pass an instance of `HttpHeaders` if you need more control over the construction of headers IMPORTANT: Instances of `HttpHeaders` are _immutable_ and cannot be directly changed. Instead, mutation methods such as `append()` return a new instance of `HttpHeaders` with the mutation applied. <docs-code language="ts"> const baseHeaders = new HttpHeaders().set('X-Debug-Level', 'minimal'); http.get<Config>('/api/config', { headers: baseHeaders.set('X-Debug-Level', 'verbose'), }).subscribe(config => { // ... }); </docs-code> ## Interacting with the server response events For convenience, `HttpClient` by default returns an `Observable` of the data returned by the server (the response body). Occasionally it's desirable to examine the actual response, for example to retrieve specific response headers. To access the entire response, set the `observe` option to `'response'`: <docs-code language="ts"> http.get<Config>('/api/config', {observe: 'response'}).subscribe(res => { console.log('Response status:', res.status); console.log('Body:', res.body); }); </docs-code> <docs-callout important title="Literal value for `observe`"> Because the value of `observe` affects the type returned by `HttpClient`, it must have a literal type and not a `string` type. This happens automatically if the options object passed to the request method is a literal object, but if you're extracting the request options out into a variable or helper method you might need to explicitly specify it as a literal, such as `observe: 'response' as const`. </docs-callout>
004646
## Receiving raw progress events In addition to the response body or response object, `HttpClient` can also return a stream of raw _events_ corresponding to specific moments in the request lifecycle. These events include when the request is sent, when the response header is returned, and when the body is complete. These events can also include _progress events_ which report upload and download status for large request or response bodies. Progress events are disabled by default (as they have a performance cost) but can be enabled with the `reportProgress` option. Note: The optional `fetch` implementation of `HttpClient` does not report _upload_ progress events. To observe the event stream, set the `observe` option to `'events'`: <docs-code language="ts"> http.post('/api/upload', myData, { reportProgress: true, observe: 'events', }).subscribe(event => { switch (event.type) { case HttpEventType.UploadProgress: console.log('Uploaded ' + event.loaded + ' out of ' + event.total + ' bytes'); break; case HttpEventType.Response: console.log('Finished uploading!'); break; } }); </docs-code> <docs-callout important title="Literal value for `observe`"> Because the value of `observe` affects the type returned by `HttpClient`, it must have a literal type and not a `string` type. This happens automatically if the options object passed to the request method is a literal object, but if you're extracting the request options out into a variable or helper method you might need to explicitly specify it as a literal, such as `observe: 'events' as const`. </docs-callout> Each `HttpEvent` reported in the event stream has a `type` which distinguishes what the event represents: | **`type` value** | **Event meaning** | | - | - | | `HttpEventType.Sent` | The request has been dispatched to the server | | `HttpEventType.UploadProgress` | An `HttpUploadProgressEvent` reporting progress on uploading the request body | | `HttpEventType.ResponseHeader` | The head of the response has been received, including status and headers | | `HttpEventType.DownloadProgress` | An `HttpDownloadProgressEvent` reporting progress on downloading the response body | | `HttpEventType.Response` | The entire response has been received, including the response body | | `HttpEventType.User` | A custom event from an Http interceptor. ## Handling request failure There are two ways an HTTP request can fail: * A network or connection error can prevent the request from reaching the backend server. * The backend can receive the request but fail to process it, and return an error response. `HttpClient` captures both kinds of errors in an `HttpErrorResponse` which it returns through the `Observable`'s error channel. Network errors have a `status` code of `0` and an `error` which is an instance of [`ProgressEvent`](https://developer.mozilla.org/docs/Web/API/ProgressEvent). Backend errors have the failing `status` code returned by the backend, and the error response as the `error`. Inspect the response to identify the error's cause and the appropriate action to handle the error. The [RxJS library](https://rxjs.dev/) offers several operators which can be useful for error handling. You can use the `catchError` operator to transform an error response into a value for the UI. This value can tell the UI to display an error page or value, and capture the error's cause if necessary. Sometimes transient errors such as network interruptions can cause a request to fail unexpectedly, and simply retrying the request will allow it to succeed. RxJS provides several *retry* operators which automatically re-subscribe to a failed `Observable` under certain conditions. For example, the `retry()` operator will automatically attempt to re-subscribe a specified number of times. ## Http `Observable`s Each request method on `HttpClient` constructs and returns an `Observable` of the requested response type. Understanding how these `Observable`s work is important when using `HttpClient`. `HttpClient` produces what RxJS calls "cold" `Observable`s, meaning that no actual request happens until the `Observable` is subscribed. Only then is the request actually dispatched to the server. Subscribing to the same `Observable` multiple times will trigger multiple backend requests. Each subscription is independent. TIP: You can think of `HttpClient` `Observable`s as _blueprints_ for actual server requests. Once subscribed, unsubscribing will abort the in-progress request. This is very useful if the `Observable` is subscribed via the `async` pipe, as it will automatically cancel the request if the user navigates away from the current page. Additionally, if you use the `Observable` with an RxJS combinator like `switchMap`, this cancellation will clean up any stale requests. Once the response returns, `Observable`s from `HttpClient` usually complete (although interceptors can influence this). Because of the automatic completion, there is usually no risk of memory leaks if `HttpClient` subscriptions are not cleaned up. However, as with any async operation, we strongly recommend that you clean up subscriptions when the component using them is destroyed, as the subscription callback may otherwise run and encounter errors when it attempts to interact with the destroyed component. TIP: Using the `async` pipe or the `toSignal` operation to subscribe to `Observable`s ensures that subscriptions are disposed properly. ## Best practices While `HttpClient` can be injected and used directly from components, generally we recommend you create reusable, injectable services which isolate and encapsulate data access logic. For example, this `UserService` encapsulates the logic to request data for a user by their id: <docs-code language="ts"> @Injectable({providedIn: 'root'}) export class UserService { constructor(private http: HttpClient) {} getUser(id: string): Observable<User> { return this.http.get<User>(`/api/user/${id}`); } } </docs-code> Within a component, you can combine `@if` with the `async` pipe to render the UI for the data only after it's finished loading: <docs-code language="ts"> import { AsyncPipe } from '@angular/common'; @Component({ standalone: true, imports: [AsyncPipe], template: ` @if (user$ | async; as user) { <p>Name: {{ user.name }}</p> <p>Biography: {{ user.biography }}</p> } `, }) export class UserProfileComponent { @Input() userId!: string; user$!: Observable<User>; constructor(private userService: UserService) {} ngOnInit(): void { this.user$ = this.userService.getUser(this.userId); } } </docs-code>
004647
# Test requests As for any external dependency, you must mock the HTTP backend so your tests can simulate interaction with a remote server. The `@angular/common/http/testing` library provides tools to capture requests made by the application, make assertions about them, and mock the responses to emulate your backend's behavior. The testing library is designed for a pattern in which the app executes code and makes requests first. The test then expects that certain requests have or have not been made, performs assertions against those requests, and finally provides responses by "flushing" each expected request. At the end, tests can verify that the app made no unexpected requests. ## Setup for testing To begin testing usage of `HttpClient`, configure `TestBed` and include `provideHttpClient()` and `provideHttpClientTesting()` in your test's setup. This configures `HttpClient` to use a test backend instead of the real network. It also provides `HttpTestingController`, which you'll use to interact with the test backend, set expectations about which requests have been made, and flush responses to those requests. `HttpTestingController` can be injected from `TestBed` once configured. Keep in mind to provide `provideHttpClient()` **before** `provideHttpClientTesting()`, as `provideHttpClientTesting()` will overwrite parts of `provideHttpCient()`. Doing it the other way around can potentially break your tests. <docs-code language="ts"> TestBed.configureTestingModule({ providers: [ // ... other test providers provideHttpClient(), provideHttpClientTesting(), ], }); const httpTesting = TestBed.inject(HttpTestingController); </docs-code> Now when your tests make requests, they will hit the testing backend instead of the normal one. You can use `httpTesting` to make assertions about those requests. ## Expecting and answering requests For example, you can write a test that expects a GET request to occur and provides a mock response: <docs-code language="ts"> TestBed.configureTestingModule({ providers: [ ConfigService, provideHttpClient(), provideHttpClientTesting(), ], }); const httpTesting = TestBed.inject(HttpTestingController); // Load `ConfigService` and request the current configuration. const service = TestBed.inject(ConfigService); const config$ = this.configService.getConfig<Config>(); // `firstValueFrom` subscribes to the `Observable`, which makes the HTTP request, // and creates a `Promise` of the response. const configPromise = firstValueFrom(config$); // At this point, the request is pending, and we can assert it was made // via the `HttpTestingController`: const req = httpTesting.expectOne('/api/config', 'Request to load the configuration'); // We can assert various properties of the request if desired. expect(req.request.method).toBe('GET'); // Flushing the request causes it to complete, delivering the result. req.flush(DEFAULT_CONFIG); // We can then assert that the response was successfully delivered by the `ConfigService`: expect(await configPromise).toEqual(DEFAULT_CONFIG); // Finally, we can assert that no other requests were made. httpTesting.verify(); </docs-code> Note: `expectOne` will fail if the test has made more than one request which matches the given criteria. As an alternative to asserting on `req.method`, you could instead use an expanded form of `expectOne` to also match the request method: <docs-code language="ts"> const req = httpTesting.expectOne({ method: 'GET', url: '/api/config', }, 'Request to load the configuration'); </docs-code> HELPFUL: The expectation APIs match against the full URL of requests, including any query parameters. The last step, verifying that no requests remain outstanding, is common enough for you to move it into an `afterEach()` step: <docs-code language="ts"> afterEach(() => { // Verify that none of the tests make any extra HTTP requests. TestBed.inject(HttpTestingController).verify(); }); </docs-code> ## Handling more than one request at once If you need to respond to duplicate requests in your test, use the `match()` API instead of `expectOne()`. It takes the same arguments but returns an array of matching requests. Once returned, these requests are removed from future matching and you are responsible for flushing and verifying them. <docs-code language="ts"> const allGetRequests = httpTesting.match({method: 'GET'}); foreach (const req of allGetRequests) { // Handle responding to each request. } </docs-code> ## Advanced matching All matching functions accept a predicate function for custom matching logic: <docs-code language="ts"> // Look for one request that has a request body. const requestsWithBody = httpTesting.expectOne(req => req.body !== null); </docs-code> The `expectNone` function asserts that no requests match the given criteria. <docs-code language="ts"> // Assert that no mutation requests have been issued. httpTesting.expectNone(req => req.method !== 'GET'); </docs-code> ## Testing error handling You should test your app's responses when HTTP requests fail. ### Backend errors To test handling of backend errors (when the server returns a non-successful status code), flush requests with an error response that emulates what your backend would return when a request fails. <docs-code language="ts"> const req = httpTesting.expectOne('/api/config'); req.flush('Failed!', {status: 500, statusText: 'Internal Server Error'}); // Assert that the application successfully handled the backend error. </docs-code> ### Network errors Requests can also fail due to network errors, which surface as `ProgressEvent` errors. These can be delivered with the `error()` method: <docs-code language="ts"> const req = httpTesting.expectOne('/api/config'); req.error(new ProgressEvent('network error!')); // Assert that the application successfully handled the network error. </docs-code>
004649
# Interceptors `HttpClient` supports a form of middleware known as _interceptors_. TLDR: Interceptors are middleware that allows common patterns around retrying, caching, logging, and authentication to be abstracted away from individual requests. `HttpClient` supports two kinds of interceptors: functional and DI-based. Our recommendation is to use functional interceptors because they have more predictable behavior, especially in complex setups. Our examples in this guide use functional interceptors, and we cover [DI-based interceptors](#di-based-interceptors) in their own section at the end. ## Interceptors Interceptors are generally functions which you can run for each request, and have broad capabilities to affect the contents and overall flow of requests and responses. You can install multiple interceptors, which form an interceptor chain where each interceptor processes the request or response before forwarding it to the next interceptor in the chain. You can use interceptors to implement a variety of common patterns, such as: * Adding authentication headers to outgoing requests to a particular API. * Retrying failed requests with exponential backoff. * Caching responses for a period of time, or until invalidated by mutations. * Customizing the parsing of responses. * Measuring server response times and log them. * Driving UI elements such as a loading spinner while network operations are in progress. * Collecting and batch requests made within a certain timeframe. * Automatically failing requests after a configurable deadline or timeout. * Regularly polling the server and refreshing results. ## Defining an interceptor The basic form of an interceptor is a function which receives the outgoing `HttpRequest` and a `next` function representing the next processing step in the interceptor chain. For example, this `loggingInterceptor` will log the outgoing request URL to `console.log` before forwarding the request: <docs-code language="ts"> export function loggingInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> { console.log(req.url); return next(req); } </docs-code> In order for this interceptor to actually intercept requests, you must configure `HttpClient` to use it. ## Configuring interceptors You declare the set of interceptors to use when configuring `HttpClient` through dependency injection, by using the `withInterceptors` feature: <docs-code language="ts"> bootstrapApplication(AppComponent, {providers: [ provideHttpClient( withInterceptors([loggingInterceptor, cachingInterceptor]), ) ]}); </docs-code> The interceptors you configure are chained together in the order that you've listed them in the providers. In the above example, the `loggingInterceptor` would process the request and then forward it to the `cachingInterceptor`. ### Intercepting response events An interceptor may transform the `Observable` stream of `HttpEvent`s returned by `next` in order to access or manipulate the response. Because this stream includes all response events, inspecting the `.type` of each event may be necessary in order to identify the final response object. <docs-code language="ts"> export function loggingInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> { return next(req).pipe(tap(event => { if (event.type === HttpEventType.Response) { console.log(req.url, 'returned a response with status', event.status); } })); } </docs-code> Tip: Interceptors naturally associate responses with their outgoing requests, because they transform the response stream in a closure that captures the request object. ## Modifying requests Most aspects of `HttpRequest` and `HttpResponse` instances are _immutable_, and interceptors cannot directly modify them. Instead, interceptors apply mutations by cloning these objects using the `.clone()` operation, and specifying which properties should be mutated in the new instance. This might involve performing immutable updates on the value itself (like `HttpHeaders` or `HttpParams`). For example, to add a header to a request: <docs-code language="ts"> const reqWithHeader = req.clone({ headers: req.headers.set('X-New-Header', 'new header value'), }); </docs-code> This immutability allows most interceptors to be idempotent if the same `HttpRequest` is submitted to the interceptor chain multiple times. This can happen for a few reasons, including when a request is retried after failure. CRITICAL: The body of a request or response is **not** protected from deep mutations. If an interceptor must mutate the body, take care to handle running multiple times on the same request. ## Dependency injection in interceptors Interceptors are run in the _injection context_ of the injector which registered them, and can use Angular's `inject` API to retrieve dependencies. For example, suppose an application has a service called `AuthService`, which creates authentication tokens for outgoing requests. An interceptor can inject and use this service: <docs-code language="ts"> export function authInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn) { // Inject the current `AuthService` and use it to get an authentication token: const authToken = inject(AuthService).getAuthToken(); // Clone the request to add the authentication header. const newReq = req.clone({ headers: req.headers.append('X-Authentication-Token', authToken), }); return next(newReq); } </docs-code> ## Request and response metadata Often it's useful to include information in a request that's not sent to the backend, but is specifically meant for interceptors. `HttpRequest`s have a `.context` object which stores this kind of metadata as an instance of `HttpContext`. This object functions as a typed map, with keys of type `HttpContextToken`. To illustrate how this system works, let's use metadata to control whether a caching interceptor is enabled for a given request. ### Defining context tokens To store whether the caching interceptor should cache a particular request in that request's `.context` map, define a new `HttpContextToken` to act as a key: <docs-code language="ts"> export const CACHING_ENABLED = new HttpContextToken<boolean>(() => true); </docs-code> The provided function creates the default value for the token for requests that haven't explicitly set a value for it. Using a function ensures that if the token's value is an object or array, each request gets its own instance. ### Reading the token in an interceptor An interceptor can then read the token and choose to apply caching logic or not based on its value: <docs-code language="ts"> export function cachingInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> { if (req.context.get(CACHING_ENABLED)) { // apply caching logic return ...; } else { // caching has been disabled for this request return next(req); } } </docs-code> ### Setting context tokens when making a request When making a request via the `HttpClient` API, you can provide values for `HttpContextToken`s: <docs-code language="ts"> const data$ = http.get('/sensitive/data', { context: new HttpContext().set(CACHING_ENABLED, false), }); </docs-code> Interceptors can read these values from the `HttpContext` of the request. ### The request context is mutable Unlike other properties of `HttpRequest`s, the associated `HttpContext` is _mutable_. If an interceptor changes the context of a request that is later retried, the same interceptor will observe the context mutation when it runs again. This is useful for passing state across multiple retries if needed. ## Synthetic responses Most interceptors will simply invoke the `next` handler while transforming either the request or the response, but this is not strictly a requirement. This section discusses several of the ways in which an interceptor may incorporate more advanced behavior. Interceptors are not required to invoke `next`. They may instead choose to construct responses through some other mechanism, such as from a cache or by sending the request through an alternate mechanism. Constructing a response is possible using the `HttpResponse` constructor: <docs-code language="ts"> const resp = new HttpResponse({ body: 'response body', }); </docs-code> ## DI-based interceptors `HttpClient` also supports interceptors which are defined as injectable classes and configured through the DI system. The capabilities of DI-based interceptors are identical to those of functional interceptors, but the configuration mechanism is different. A DI-based interceptor is an injectable class which implements the `HttpInterceptor` interface: <docs-code language="ts"> @Injectable() export class LoggingInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, handler: HttpHandler): Observable<HttpEvent<any>> { console.log('Request URL: ' + req.url); return handler.handle(req); } } </docs-code> DI-based interceptors are configured through a dependency injection multi-provider: <docs-code language="ts"> bootstrapApplication(AppComponent, {providers: [ provideHttpClient( // DI-based interceptors must be explicitly enabled. withInterceptorsFromDi(), ), {provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true}, ]}); </docs-code> DI-based interceptors run in the order that their providers are registered. In an app with an extensive and hierarchical DI configuration, this order can be very hard to predict.
004651
# Deferred loading with `@defer` Deferrable views, also known as `@defer` blocks, reduce the initial bundle size of your application by deferring the loading of code that is not strictly necessary for the initial rendering of a page. This often results in a faster initial load and improvement in Core Web Vitals (CWV), primarily Largest Contentful Paint (LCP) and Time to First Byte (TTFB). To use this feature, you can declaratively wrap a section of your template in a @defer block: ```angular-html @defer { <large-component /> } ``` The code for any components, directives, and pipes inside of the `@defer` block is split into a separate JavaScript file and loaded only when necessary, after the rest of the template has been rendered. Deferrable views support a variety of triggers, prefetching options, and sub-blocks for placeholder, loading, and error state management. ## Which dependencies are deferred? Components, directives, pipes, and any component CSS styles can be deferred when loading an application. In order for the dependencies within a `@defer` block to be deferred, they need to meet two conditions: 1. **They must be standalone.** Non-stadalone dependencies cannot be deferred and are still eagerly loaded, even if they are inside of `@defer` blocks. 1. **They cannot be referenced outside of `@defer` blocks within the same file.** If they are referenced outside of the `@defer` block or referenced within ViewChild queries, the dependencies will be eagerly loaded. The _transitive_ dependencies of the components, directives and pipes used in the `@defer` block do not strictly need to be standalone; transitive dependencies can still be declared in an `NgModule` and participate in deferred loading. ## How to manage different stages of deferred loading `@defer` blocks have several sub blocks to allow you to gracefully handle different stages in the deferred loading process. ### `@defer` This is the primary block that defines the section of content that is lazily loaded. It is not rendered initially– deferred content loads and renders once the specified [trigger](/guide/defer#triggers) occurs or the `when` condition is met. By default, a @defer block is triggered when the browser state becomes [idle](/guide/defer#on-idle). ```angular-html @defer { <large-component /> } ``` ### Show placeholder content with `@placeholder` By default, defer blocks do not render any content before they are triggered. The `@placeholder` is an optional block that declares what content to show before the `@defer` block is triggered. ```angular-html @defer { <large-component /> } @placeholder { <p>Placeholder content</p> } ``` While optional, certain triggers may require the presence of either a `@placeholder` or a [template reference variable](/guide/templates/variables#template-reference-variables) to function. See the [Triggers](/guide/defer#triggers) section for more details. Angular replaces placeholder content with the main content once loading is complete. You can use any content in the placeholder section including plain HTML, components, directives, and pipes. Keep in mind the _dependencies of the placeholder block are eagerly loaded_. The `@placeholder` block accepts an optional parameter to specify the `minimum` amount of time that this placeholder should be shown after the placeholder content initially renders. ```angular-html @defer { <large-component /> } @placeholder (minimum 500ms) { <p>Placeholder content</p> } ``` This `minimum` parameter is specified in time increments of milliseconds (ms) or seconds (s). You can use this parameter to prevent fast flickering of placeholder content in the case that the deferred dependencies are fetched quickly. ### Show loading content with `@loading` The `@loading` block is an optional block that allows you to declare content that is shown while deferred dependencies are loading. It replaces the `@placeholder` block once loading is triggered. ```angular-html @defer { <large-component /> } @loading { <img alt="loading..." src="loading.gif" /> } @placeholder { <p>Placeholder content</p> } ``` Its dependencies are eagerly loaded (similar to `@placeholder`). The `@loading` block accepts two optional parameters to help prevent fast flickering of content that may occur when deferred dependencies are fetched quickly,: - `minimum` - the minimum amount of time that this placeholder should be shown - `after` - the amount of time to wait after loading begins before showing the loading template ```angular-html @defer { <large-component /> } @loading (after 100ms; minimum 1s) { <img alt="loading..." src="loading.gif" /> } ``` Both parameters are specified in time increments of milliseconds (ms) or seconds (s). In addition, the timers for both parameters begin immediately after the loading has been triggered. ### Show error state when deferred loading fails with `@error` The `@error` block is an optional block that displays if deferred loading fails. Similar to `@placeholder` and `@loading`, the dependencies of the @error block are eagerly loaded. ```angular-html @defer { <large-component /> } @error { <p>Failed to load large component.</p> } ``` ##
004652
Controlling deferred content loading with triggers You can specify **triggers** that control when Angular loads and displays deferred content. When a `@defer` block is triggered, it replaces placeholder content with lazily loaded content. Multiple event triggers can be defined by separating them with a semicolon, `;` and will be evaluated as OR conditions. There are two types of triggers: `on` and `when`. ### `on` `on` specifies a condition for when the `@defer` block is triggered. The available triggers are as follows: | Trigger | Description | | ----------------------------- | ---------------------------------------------------------------------- | | [`idle`](#idle) | Triggers when the browser is idle. | | [`viewport`](#viewport) | Triggers when specified content enters the viewport | | [`interaction`](#interaction) | Triggers when the user interacts with specified element | | [`hover`](#hover) | Triggers when the mouse hovers over specified area | | [`immediate`](#immediate) | Triggers immediately after non-deferred content has finished rendering | | [`timer`](#timer) | Triggers after a specific duration | #### `idle` The `idle` trigger loads the deferred content once the browser has reached an idle state, based on requestIdleCallback. This is the default behavior with a defer block. ```angular-html <!-- @defer (on idle) --> @defer { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` #### `viewport` The `viewport` trigger loads the deferred content when the specified content enters the viewport using the [Intersection Observer API](https://developer.mozilla.org/docs/Web/API/Intersection_Observer_API). Observed content may be `@placeholder` content or an explicit element reference. By default, the `@defer` watches for the placeholder entering the viewport. Placeholders used this way must have a single root element. ```angular-html @defer (on viewport) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` Alternatively, you can specify a [template reference variable](/guide/templates/variables) in the same template as the `@defer` block as the element that is watched to enter the viewport. This variable is passed in as a parameter on the viewport trigger. ```angular-html <div #greeting>Hello!</div> @defer (on viewport(greeting)) { <greetings-cmp /> } ``` #### `interaction` The `interaction` trigger loads the deferred content when the user interacts with the specified element through `click` or `keydown` events. By default, the placeholder acts as the interaction element. Placeholders used this way must have a single root element. ```angular-html @defer (on interaction) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` Alternatively, you can specify a [template reference variable](/guide/templates/variables) in the same template as the `@defer` block as the element that is watched to enter the viewport. This variable is passed in as a parameter on the viewport trigger.Z ```angular-html <div #greeting>Hello!</div> @defer (on interaction(greeting)) { <greetings-cmp /> } ``` #### `hover` The `hover` trigger loads the deferred content when the mouse has hovered over the triggered area through the `mouseenter` and `focusin` events. By default, the placeholder acts as the interaction element. Placeholders used this way must have a single root element. ```angular-html @defer (on hover) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` Alternatively, you can specify a [template reference variable](/guide/templates/variables) in the same template as the `@defer` block as the element that is watched to enter the viewport. This variable is passed in as a parameter on the viewport trigger. ```angular-html <div #greeting>Hello!</div> @defer (on hover(greeting)) { <greetings-cmp /> } ``` #### `immediate` The `immediate` trigger loads the deferred content immediately. This means that the deferred block loads as soon as all other non-deferred content has finished rendering. ```angular-html @defer (on immediate) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` #### `timer` The `timer` trigger loads the deferred content after a specified duration. ```angular-html @defer (on timer(500ms)) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` The duration parameter must be specified in milliseconds (`ms`) or seconds (`s`). ### `when` The `when` trigger accepts a custom conditional expression and loads the deferred content when the condition becomes truthy. ```angular-html @defer (when condition) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` This is a one-time operation– the `@defer` block does not revert back to the placeholder if the condition changes to a falsy value after becoming truthy. ## Prefetching data with `prefetch` In addition to specifying a condition that determines when deferred content is shown, you can optionally specify a **prefetch trigger**. This trigger lets you load the JavaScript associated with the `@defer` block before the deferred content is shown. Prefetching enables more advanced behaviors, such as letting you start to prefetch resources before a user has actually seen or interacted with a defer block, but might interact with it soon, making the resources available faster. You can specify a prefetch trigger similarly to the block's main trigger, but prefixed with the `prefetch` keyword. The block's main trigger and prefetch trigger are separated with a semi-colon character (`;`). In the example below, the prefetching starts when a browser becomes idle and the contents of the block is rendered only once the user interacts with the placeholder. ```angular-html @defer (on interaction; prefetch on idle) { <large-cmp /> } @placeholder { <div>Large component placeholder</div> } ``` ## Testing `@defer` blocks Angular provides TestBed APIs to simplify the process of testing `@defer` blocks and triggering different states during testing. By default, `@defer` blocks in tests play through like a defer block would behave in a real application. If you want to manually step through states, you can switch the defer block behavior to `Manual` in the TestBed configuration. ```angular-ts it('should render a defer block in different states', async () => { // configures the defer block behavior to start in "paused" state for manual control. TestBed.configureTestingModule({deferBlockBehavior: DeferBlockBehavior.Manual}); @Component({ // ... template: ` @defer { <large-component /> } @placeholder { Placeholder } @loading { Loading... } ` }) class ComponentA {} // Create component fixture. const componentFixture = TestBed.createComponent(ComponentA); // Retrieve the list of all defer block fixtures and get the first block. const deferBlockFixture = (await componentFixture.getDeferBlocks())[0]; // Renders placeholder state by default. expect(componentFixture.nativeElement.innerHTML).toContain('Placeholder'); // Render loading state and verify rendered output. await deferBlockFixture.render(DeferBlockState.Loading); expect(componentFixture.nativeElement.innerHTML).toContain('Loading'); // Render final state and verify the output. await deferBlockFixture.render(DeferBlockState.Complete); expect(componentFixture.nativeElement.innerHTML).toContain('large works!'); }); ``` ## Does `@defer` work with `NgModule`? `@defer` blocks are compatible with both standalone and NgModule-based components, directives and pipes. However, **only standalone components, directives and pipes can be deferred**. NgModule-based dependencies are not deferred and are included in the eagerly loaded bundle. ## How does `@defer` work with server-side rendering (SSR) and static-site generation (SSG)? When rendering an application on the server (either using SSR or SSG), defer blocks always render their `@placeholder` (or nothing if a placeholder is not specified). Triggers are ignored on the server. ## Best practices for deferring views ### Avoid cascading loads with nested `@defer` blocks When you have nested `@defer` blocks, they should have different triggers in order to avoid loading simultaneously, which causes cascading requests and may negatively impact page load performance. ### Avoid layout shifts Avoid deferring components that are visible in the user’s viewport on initial load. Doing this may negatively affect Core Web Vitals by causing an increase in cumulative layout shift (CLS). In the event this is necessary, avoid `immediate`, `timer`, `viewport`, and custom `when` triggers that cause the content to load during the initial page render.
004654
<docs-decorative-header title="Template syntax" imgSrc="adev/src/assets/images/templates.svg"> <!-- markdownlint-disable-line --> In Angular, a template is a chunk of HTML. Use special syntax within a template to leverage many of Angular's features. </docs-decorative-header> Tip: Check out Angular's [Essentials](essentials/rendering-dynamic-templates) before diving into this comprehensive guide. Every Angular component has a **template** that defines the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model) that the component renders onto the page. By using templates, Angular is able to automatically keep your page up-to-date as data changes. Templates are usually found within either the `template` property of a `*.component.ts` file or the `*.component.html` file. To learn more, check out the [in-depth components guide](/guide/components). ## How do templates work? Templates are based on [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) syntax, with additional features such as built-in template functions, data binding, event listening, variables, and more. Angular compiles templates into JavaScript in order to build up an internal understanding of your application. One of the benefits of this are built-in rendering optimizations that Angular applies to your application automatically. ### Differences from standard HTML Some differences between templates and standard HTML syntax include: - Comments in the template source code are not included in the rendered output - Component and directive elements can be self-closed (e.g., `<UserProfile />`) - Attributes with certain characters (i.e., `[]`, `()`, etc.) have special meaning to Angular. See [binding docs](guide/templates/binding) and [adding event listeners docs](guide/templates/event-listeners) for more information. - The `@` character has a special meaning to Angular for adding dynamic behavior, such as [control flow](guide/templates/control-flow), to templates. You can include a literal `@` character by escaping it as an HTML entity code (`&commat;` or `&#64;`). - Angular ignores and collapses unnecessary whitespace characters. See [whitespace in templates](guide/templates/whitespace) for more details. - Angular may add comment nodes to a page as placeholders for dynamic content, but developers can ignore these. In addition, while most HTML syntax is valid template syntax, Angular does not support `<script>` element in templates. For more information, see the [Security](best-practices/security) page. ## What's next? You might also be interested in the following: | Topics | Details | | :-------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- | | [Binding dynamic text, properties, and attributes](guide/templates/binding) | Bind dynamic data to text, properties and attributes. | | [Adding event listeners](guide/templates/event-listeners) | Respond to events in your templates. | | [Two-way binding](guide/templates/two-way-binding) | Simultaneously binds a value and propagate changes. | | [Control flow](guide/templates/control-flow) | Conditionally show, hide and repeat elements. | | [Pipes](guide/templates/pipes) | Transform data declaratively. | | [Slotting child content with ng-content](guide/templates/ng-content) | Control how components render content. | | [Create template fragments with ng-template](guide/templates/ng-template) | Declare a template fragment. | | [Grouping elements with ng-container](guide/templates/ng-container) | Group multiple elements together or mark a location for rendering. | | [Variables in templates](guide/templates/variables) | Learn about variable declarations. | | [Deferred loading with @defer](guide/templates/defer) | Create deferrable views with `@defer`. | | [Expression syntax](guide/templates/expression-syntax) | Learn similarities and differences betwene Angular expressions and standard JavaScript. | | [Whitespace in templates](guide/templates/whitespace) | Learn how Angular handles whitespace. |
004657
# Two-way binding **Two way binding** is a shorthand to simultaneously bind a value into an element, while also giving that element the ability to propagate changes back through this binding. ## Syntax The syntax for two-way binding is a combination of square brackets and parentheses, `[()]`. It combines the syntax from property binding, `[]`, and the syntax from event binding, `()`. The Angular community informally refers to this syntax as "banana-in-a-box". ## Two-way binding with form controls Developers commonly use two-way binding to keep component data in sync with a form control as a user interacts with the control. For example, when a user fills out a text input, it should update the state in the component. The following example dynamically updates the `firstName` attribute on the page: ```angular-ts import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ standalone: true, imports: [FormsModule], template: ` <main> <h2>Hello {{ firstName }}!</h2> <input type="text" [(ngModel)]="firstName" /> </main> ` }) export class AppComponent { firstName = 'Ada'; } ``` To use two-way binding with native form controls, you need to: 1. Import the `FormsModule` from `@angular/forms` 1. Use the `ngModel` directive with the two-way binding syntax (e.g., `[(ngModel)]`) 1. Assign it the state that you want it to update (e.g., `firstName`) Once that is setup, Angular will ensure that any updates in the text input will reflect correctly inside of the component state! Learn more about [`NgModel`](guide/directives#displaying-and-updating-properties-with-ngmodel) in the official docs. ## Two-way binding between components Leveraging two-way binding between a parent and child component requires more configuration compared to form elements. Here is an example where the `AppComponent` is responsible for setting the initial count state, but the logic for updating and rendering the UI for the counter primarily resides inside its child `CounterComponent`. ```angular-ts // ./app.component.ts import { Component } from '@angular/core'; import { CounterComponent } from './counter/counter.component'; @Component({ selector: 'app-root', standalone: true, imports: [CounterComponent], template: ` <main> <h1>Counter: {{ initialCount }}</h1> <app-counter [(count)]="initialCount"></app-counter> </main> `, }) export class AppComponent { initialCount = 18; } ``` ```angular-ts // './counter/counter.component.ts'; import { Component, EventEmitter, Input, Output } from '@angular/core'; @Component({ selector: 'app-counter', standalone: true, template: ` <button (click)="updateCount(-1)">-</button> <span>{{ count }}</span> <button (click)="updateCount(+1)">+</button> `, }) export class CounterComponent { @Input() count: number; @Output() countChange = new EventEmitter<number>(); updateCount(amount: number): void { this.count += amount; this.countChange.emit(this.count); } } ``` ### Enabling two-way binding between components If we break down the example above to its core , each two-way binding for components requires the following: The child component must contain: 1. An `@Input()` property 1. A corresponding `@Output()` event emitter that has the exact same name as the input property plus "Change" at the end. The emitter must also emit the same type as the input property. 1. A method that emits to the event emitter with the updated value of the `@Input()`. Here is a simplified example: ```angular-ts // './counter/counter.component.ts'; import { Component, EventEmitter, Input, Output } from '@angular/core'; @Component({ // Omitted for brevity }) export class CounterComponent { @Input() count: number; @Output() countChange = new EventEmitter<number>(); updateCount(amount: number): void { this.count += amount; this.countChange.emit(this.count); } } ``` The parent component must: 1. Wrap the `@Input()` property name in the two-way binding syntax. 1. Specify the corresponding property to which the updated value is assigned Here is a simplified example: ```angular-ts // ./app.component.ts import { Component } from '@angular/core'; import { CounterComponent } from './counter/counter.component'; @Component({ selector: 'app-root', standalone: true, imports: [CounterComponent], template: ` <main> <app-counter [(count)]="initialCount"></app-counter> </main> `, }) export class AppComponent { initialCount = 18; } ```
004659
# Binding dynamic text, properties and attributes In Angular, a **binding** creates a dynamic connection between a component's template and its data. This connection ensures that changes to the component's data automatically update the rendered template. ## Render dynamic text with text interpolation You can bind dynamic text in templates with double curly braces, which tells Angular that it is responsible for the expression inside and ensuring it is updated correctly. This is called **text interpolation**. ```angular-ts @Component({ template: ` <p>Your color preference is {{ theme }}.</p> `, ... }) export class AppComponent { theme = 'dark'; } ``` In this example, when the snippet is rendered to the page, Angular will replace `{{ theme }}` with `dark`. ```angular-html <!-- Rendered Output --> <p>Your color preference is dark.</p> ``` In addition to evaluating the expression at first render, Angular also updates the rendered content when the expression's value changes. Continuing the theme example, if a user clicks on a button that changes the value of `theme` to `'light'` after the page loads, the page updates accordingly to: ```angular-html <!-- Rendered Output --> <p>Your color preference is light.</p> ``` You can use text interpolation anywhere you would normally write text in HTML. All expression values are converted to a string. Objects and arrays are converted using the value’s `toString` method. ## Binding dynamic properties and attributes Angular supports binding dynamic values into object properties and HTML attributes with square brackets. You can bind to properties on an HTML element's DOM instance, a [component](guide/components) instance, or a [directive](guide/directives) instance. ### Native element properties Every HTML element has a corresponding DOM representation. For example, each `<button>` HTML element corresponds to an instance of `HTMLButtonElement` in the DOM. In Angular, you use property bindings to set values directly to the DOM representation of the element. ```angular-html <!-- Bind the `disabled` property on the button element's DOM object --> <button [disabled]="isFormValid">Save</button> ``` In this example, every time `isFormValid` changes, Angular automatically sets the `disabled` property of the `HTMLButtonElement` instance. ### Component and directive properties When an element is an Angular component, you can use property bindings to set component input properties using the same square bracket syntax. ```angular-html <!-- Bind the `value` property on the `MyListbox` component instance. --> <my-listbox [value]="mySelection" /> ``` In this example, every time `mySelection` changes, Angular automatically sets the `value` property of the `MyListbox` instance. You can bind to directive properties as well. ```angular-html <!-- Bind to the `ngSrc` property of the `NgOptimizedImage` directive --> <img [ngSrc]="profilePhotoUrl" alt="The current user's profile photo"> ``` ### Attributes When you need to set HTML attributes that do not have corresponding DOM properties, such as ARIA attributes or SVG attributes, you can bind attributes to elements in your template with the `attr.` prefix. ```angular-html <!-- Bind the `role` attribute on the `<ul>` element to the component's `listRole` property. --> <ul [attr.role]="listRole"> ``` In this example, every time `listRole` changes, Angular automatically sets the `role` attribute of the `<ul>` element by calling `setAttribute`. If the value of an attribute binding is `null`, Angular removes the attribute by calling `removeAttribute`. ### Text interpolation in properties and attributes You can also use text interpolation syntax in properties and attributes by using the double curly brace syntax instead of square braces around the property or attribute name. When using this syntax, Angular treats the assignment as a property binding. ```angular-html <!-- Binds a value to the `alt` property of the image element's DOM object. --> <img src="profile-photo.jpg" alt="Profile photo of {{ firstName }}" > ``` To bind to an attribute with the text interpolation syntax, prefix the attribute name with `attr.` ```angular-html <button attr.aria-label="Save changes to {{ objectType }}"> ``` ## CSS class and style property bindings Angular supports additional features for binding CSS classes and CSS style properties to elements. ### CSS classes You can create a CSS class binding to conditionally add or remove a CSS class on an element based on whether the bound value is [truthy or falsy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). ```angular-html <!-- When `isExpanded` is truthy, add the `expanded` CSS class. --> <ul [class.expanded]="isExpanded"> ``` You can also bind directly to the `class` property. Angular accepts three types of value: | Description of `class` value | TypeScript type | | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | | A string containing one or more CSS classes separated by spaces | `string` | | An array of CSS class strings | `string[]` | | An object where each property name is a CSS class name and each corresponding value determines whether that class is applied to the element, based on truthiness. | `Record<string, any>` | ```angular-ts @Component({ template: ` <ul [class]="listClasses"> ... </ul> <section [class]="sectionClasses"> ... </section> <button [class]="buttonClasses"> ... </button> `, ... }) export class UserProfile { listClasses = 'full-width outlined'; sectionClasses = ['expandable', 'elevated']; buttonClasses = { highlighted: true, embiggened: false, }; } ``` The above example renders the following DOM: ```angular-html <ul class="full-width outlined"> ... </ul> <section class="expandable elevated"> ... </section> <button class="highlighted"> ... </button> ``` Angular ignores any string values that are not valid CSS class names. When using static CSS classes, directly binding `class`, and binding specific classes, Angular intelligently combines all of the classes in the rendered result. ```angular-ts @Component({ template: `<ul class="list" [class]="listType" [class.expanded]="isExpanded"> ...`, ... }) export class Listbox { listType = 'box'; isExpanded = true; } ``` In the example above, Angular renders the `ul` element with all three CSS classes. ```angular-html <ul class="list box expanded"> ``` Angular does not guarantee any specific order of CSS classes on rendered elements. When binding `class` to an array or an object, Angular compares the previous value to the current value with the triple-equals operator (`===`). You must create a new object or array instance when you modify these values in order to Angular to apply any updates. If an element has multiple bindings for the same CSS class, Angular resolves collisions by following its style precedence order. ### CSS style properties You can also bind to CSS style properties directly on an element. ```angular-html <!-- Set the CSS `display` property based on the `isExpanded` property. --> <section [style.display]="isExpanded ? 'block' : 'none'"> ``` You can further specify units for CSS properties that accept units. ```angular-html <!-- Set the CSS `height` property to a pixel value based on the `sectionHeightInPixels` property. --> <section [style.height.px]="sectionHeightInPixels"> ``` You can also set multiple style values in one binding. Angular accepts the following types of value: | Description of `style` value | TypeScript type | | ------------------------------------------------------------------------------------------------------------------------- | --------------------- | | A string containing zero or more CSS declarations, such as `"display: flex; margin: 8px"`. | `string` | | An object where each property name is a CSS property name and each corresponding value is the value of that CSS property. | `Record<string, any>` | ```angular-ts @Component({ template: ` <ul [style]="listStyles"> ... </ul> <section [style]="sectionStyles"> ... </section> `, ... }) export class UserProfile { listStyles = 'display: flex; padding: 8px'; sectionStyles = { border: '1px solid black', 'font-weight': 'bold', }; } ``` The above example renders the following DOM. ```angular-html <ul style="display: flex; padding: 8px"> ... </ul> <section style="border: 1px solid black; font-weight: bold"> ... </section> ``` When binding `style` to an object, Angular compares the previous value to the current value with the triple-equals operator (`===`). You must create a new object instance when you modify these values in order to Angular to apply any updates. If an element has multiple bindings for the same style property, Angular resolves collisions by following its style precedence order.
004661
# Grouping elements with ng-container `<ng-container>` is a special element in Angular that groups multiple elements together or marks a location in a template without rendering a real element in the DOM. ```angular-html <!-- Component template --> <section> <ng-container> <h3>User bio</h3> <p>Here's some info about the user</p> </ng-container> </section> ``` ```angular-html <!-- Rendered DOM --> <section> <h3>User bio</h3> <p>Here's some info about the user</p> </section> ``` You can apply directives to `<ng-container>` to add behaviors or configuration to a part of your template. Angular ignores all attribute bindings and event listeners applied to `<ng-container>`, including those applied via directive. ## Using `<ng-container>` to display dynamic contents `<ng-container>` can act as a placeholder for rendering dynamic content. ### Rendering components You can use Angular's built-in `NgComponentOutlet` directive to dynamically render a component to the location of the `<ng-container>`. ```angular-ts @Component({ template: ` <h2>Your profile</h2> <ng-container [ngComponentOutlet]="profileComponent()" /> ` }) export class UserProfile { isAdmin = input(false); profileComponent = computed(() => this.isAdmin() ? AdminProfile : BasicUserProfile); } ``` In the example above, the `NgComponentOutlet` directive dynamically renders either `AdminProfile` or `BasicUserProfile` in the location of the `<ng-container>` element. ### Rendering template fragments You can use Angular's built-in `NgTemplateOutlet` directive to dynamically render a template fragment to the location of the `<ng-container>`. ```angular-ts @Component({ template: ` <h2>Your profile</h2> <ng-container [ngTemplateOutlet]="profileTemplate()" /> <ng-template #admin>This is the admin profile</ng-template> <ng-template #basic>This is the basic profile</ng-template> ` }) export class UserProfile { isAdmin = input(false); adminTemplate = viewChild('admin', {read: TemplateRef}); basicTemplate = viewChild('basic', {read: TemplateRef}); profileTemplate = computed(() => this.isAdmin() ? this.adminTemplate() : this.basicTemplate()); } ``` In the example above, the `ngTemplateOutlet` directive dynamically renders one of two template fragments in the location of the `<ng-container>` element. For more information regarding NgTemplateOutlet, see the [NgTemplateOutlets API documentation page](/api/common/NgTemplateOutlet). ## Using `<ng-container>` with structural directives You can also apply structural directives to `<ng-container>` elements. Common examples of this include `ngIf`and `ngFor`. ```angular-html <ng-container *ngIf="permissions == 'admin'"> <h1>Admin Dashboard</h1> <admin-infographic></admin-infographic> </ng-container> <ng-container *ngFor="let item of items; index as i; trackBy: trackByFn"> <h2>{{ item.title }}</h2> <p>{{ item.description }}</p> </ng-container> ``` ## Using `<ng-container>` for injection See the Dependency Injection guide for more information on Angular's dependency injection system. When you apply a directive to `<ng-container>`, descendant elements can inject the directive or anything that the directive provides. Use this when you want to declaratively provide a value to a specific part of your template. ```angular-ts @Directive({ selector: '[theme]', }) export class Theme { // Create an input that accepts 'light' or 'dark`, defaulting to 'light'. mode = input<'light' | 'dark'>('light'); } ``` ```angular-html <ng-container theme="dark"> <profile-pic /> <user-bio /> </ng-container> ``` In the example above, the `ProfilePic` and `UserBio` components can inject the `Theme` directive and apply styles based on its `mode`.
004662
# Create template fragments with ng-template Inspired by the [native `<template>` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template), the `<ng-template>` element lets you declare a **template fragment** – a section of content that you can dynamically or programmatically render. ## Creating a template fragment You can create a template fragment inside of any component template with the `<ng-template>` element: ```angular-html <p>This is a normal element</p> <ng-template> <p>This is a template fragment</p> </ng-template> ``` When the above is rendered, the content of the `<ng-template>` element is not rendered on the page. Instead, you can get a reference to the template fragment and write code to dynamically render it. ### Binding context for fragments Template fragments may contain bindings with dynamic expressions: ```angular-ts @Component({ /* ... */, template: `<ng-template>You've selected {{count}} items.</ng-template>`, }) export class ItemCounter { count: number = 0; } ``` Expressions or statements in a template fragment are evaluated against the component in which the fragment is declared, regardless of where the fragment is rendered. ## Getting a reference to a template fragment You can get a reference to a template fragment in one of three ways: - By declaring a [template reference variable](/guide/templates/variables#template-reference-variables) on the `<ng-template>` element - By querying for the fragment with [a component or directive query](/guide/components/queries) - By injecting the fragment in a directive that's applied directly to an `<ng-template>` element. In all three cases, the fragment is represented by a [TemplateRef](/api/core/TemplateRef) object. ### Referencing a template fragment with a template reference variable You can add a template reference variable to an `<ng-template>` element to reference that template fragment in other parts of the same template file: ```angular-html <p>This is a normal element</p> <ng-template #myFragment> <p>This is a template fragment</p> </ng-template> ``` You can then reference this fragment anywhere else in the template via the `myFragment` variable. ### Referencing a template fragment with queries You can get a reference to a template fragment using any [component or directive query API](/guide/components/queries). For example, if your template has exactly one template fragment, you can query directly for the `TemplateRef` object with a `@ViewChild` query: ```angular-ts @Component({ /* ... */, template: ` <p>This is a normal element</p> <ng-template> <p>This is a template fragment</p> </ng-template> `, }) export class ComponentWithFragment { @ViewChild(TemplateRef) myFragment: TemplateRef<unknown> | undefined; } ``` You can then reference this fragment in your component code or the component's template like any other class member. If a template contains multiple fragments, you can assign a name to each fragment by adding a template reference variable to each `<ng-template>` element and querying for the fragments based on that name: ```angular-ts @Component({ /* ... */, template: ` <p>This is a normal element</p> <ng-template #fragmentOne> <p>This is one template fragment</p> </ng-template> <ng-template #fragmentTwo> <p>This is another template fragment</p> </ng-template> `, }) export class ComponentWithFragment { // When querying by name, you can use the `read` option to specify that you want to get the // TemplateRef object associated with the element. @ViewChild('fragmentOne', {read: TemplateRef}) fragmentOne: TemplateRef<unknown> | undefined; @ViewChild('fragmentTwo', {read: TemplateRef}) fragmentTwo: TemplateRef<unknown> | undefined; } ``` Again, you can then reference these fragments in your component code or the component's template like any other class members. ### Injecting a template fragment A directive can inject a `TemplateRef` if that directive is applied directly to an `<ng-template>` element: ```angular-ts @Directive({ selector: '[myDirective]' }) export class MyDirective { private fragment = inject(TemplateRef); } ``` ```angular-html <ng-template myDirective> <p>This is one template fragment</p> </ng-template> ``` You can then reference this fragment in your directive code like any other class member. ## Rendering a template fragment Once you have a reference to a template fragment's `TemplateRef` object, you can render a fragment in one of two ways: in your template with the `NgTemplateOutlet` directive or in your TypeScript code with `ViewContainerRef`. ### Using `NgTemplateOutlet` The `NgTemplateOutlet` directive from `@angular/common` accepts a `TemplateRef` and renders the fragment as a **sibling** to the element with the outlet. You should generally use `NgTemplateOutlet` on an [`<ng-container>` element](/guide/templates/ng-container). The following example declares a template fragment and renders that fragment to a `<ng-container>` element with `NgTemplateOutlet`: ```angular-html <p>This is a normal element</p> <ng-template #myFragment> <p>This is a fragment</p> </ng-template> <ng-container [ngTemplateOutlet]="myFragment" /> ``` This example produces the following rendered DOM: ```angular-html <p>This is a normal element</p> <p>This is a fragment</p> ``` ### Using `ViewContainerRef` A **view container** is a node in Angular's component tree that can contain content. Any component or directive can inject `ViewContainerRef` to get a reference to a view container corresponding to that component or directive's location in the DOM. You can use the `createEmbeddedView` method on `ViewContainerRef` to dynamically render a template fragment. When you render a fragment with a `ViewContainerRef`, Angular appends it into the DOM as the next sibling of the component or directive that injected the `ViewContainerRef`. The following example shows a component that accepts a reference to a template fragment as an input and renders that fragment into the DOM on a button click. ```angular-ts @Component({ /* ... */, selector: 'component-with-fragment', template: ` <h2>Component with a fragment</h2> <ng-template #myFragment> <p>This is the fragment</p> </ng-template> <my-outlet [fragment]="myFragment" /> `, }) export class ComponentWithFragment { } @Component({ /* ... */, selector: 'my-outlet', template: `<button (click)="showFragment()">Show</button>`, }) export class MyOutlet { private viewContainer = inject(ViewContainerRef); @Input() fragment: TemplateRef<unknown> | undefined; showFragment() { if (this.fragment) { this.viewContainer.createEmbeddedView(this.fragment); } } } ``` In the example above, clicking the "Show" button results in the following output: ```angular-html <component-with-fragment> <h2>Component with a fragment> <my-outlet> <button>Show</button> </my-outlet> <p>This is the fragment</p> </component-with-fragment> ``` ## Passing parameters when rendering a template fragment When declaring a template fragment with `<ng-template>`, you can additionally declare parameters accepted by the fragment. When you render a fragment, you can optimally pass a `context` object corresponding to these parameters. You can use data from this context object in binding expressions and statements, in addition to referencing data from the component in which the fragment is declared. Each parameter is written as an attribute prefixed with `let-` with a value matching a property name in the context object: ```angular-html <ng-template let-pizzaTopping="topping"> <p>You selected: {{pizzaTopping}}</p> </ng-template> ``` ### Using `NgTemplateOutlet` You can bind a context object to the `ngTemplateOutletContext` input: ```angular-html <ng-template #myFragment let-pizzaTopping="topping"> <p>You selected: {{pizzaTopping}}</p> </ng-template> <ng-container [ngTemplateOutlet]="myFragment" [ngTemplateOutletContext]="{topping: 'onion'}" /> ``` ### Using `ViewContainerRef` You can pass a context object as the second argument to `createEmbeddedView`: ```angular-ts this.viewContainer.createEmbeddedView(this.myFragment, {topping: 'onion'}); ``` ##
004664
# Control flow Angular templates support control flow blocks that let you conditionally show, hide, and repeat elements. Note: This was previously accomplished with the *ngIf, *ngFor, and \*ngSwitch directives. ## Conditionally display content with `@if`, `@else-if` and `@else` The `@if` block conditionally displays its content when its condition expression is truthy: ```angular-html @if (a > b) { <p>{{a}} is greater than {{b}}</p> } ``` If you want to display alternative content, you can do so by providing any number of `@else if` blocks and a singular `@else` block. ```angular-html @if (a > b) { {{a}} is greater than {{b}} } @else if (b > a) { {{a}} is less than {{b}} } @else { {{a}} is equal to {{b}} } ``` ### Referencing the conditional expression's result The `@if` conditional supports saving the result of the conditional expression into a variable for reuse inside of the block. ```angular-html @if (user.profile.settings.startDate; as startDate) { {{ startDate }} } ``` This can be useful for referencing longer expressions that would be easier to read and maintain within the template. ## Repeat content with the `@for` block The `@for` block loops through a collection and repeatedly renders the content of a block. The collection can be any JavaScript [iterable](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Iteration_protocols), but Angular has additional performance optimizations for `Array` values. A typical `@for` loop looks like: ```angular-html @for (item of items; track item.id) { {{ item.name }} } ``` ### Why is `track` in `@for` blocks important? The `track` expression allows Angular to maintain a relationship between your data and the DOM nodes on the page. This allows Angular to optimize performance by executing the minimum necessary DOM operations when the data changes. Using track effectively can significantly improve your application's rendering performance when looping over data collections. Select a property that uniquely identifies each item in the `track` expression. If your data model includes a uniquely identifying property, commonly `id` or `uuid`, use this value. If your data does not include a field like this, strongly consider adding one. For static collections that never change, you can use `$index` to tell Angular to track each item by its index in the collection. If no other option is available, you can specify `identity`. This tells Angular to track the item by its reference identity using the triple-equals operator (`===`). Avoid this option whenever possible as it can lead to significantly slower rendering updates, as Angular has no way to map which data item corresponds to which DOM nodes. ### Contextual variables in `@for` blocks Inside `@for` blocks, several implicit variables are always available: | Variable | Meaning | | -------- | --------------------------------------------- | | `$count` | Number of items in a collection iterated over | | `$index` | Index of the current row | | `$first` | Whether the current row is the first row | | `$last` | Whether the current row is the last row | | `$even` | Whether the current row index is even | | `$odd` | Whether the current row index is odd | These variables are always available with these names, but can be aliased via a `let` segment: ```angular-html @for (item of items; track item.id; let idx = $index, e = $even) { <p>Item #{{ idx }}: {{ item.name }}</p> } ``` The aliasing is useful when nesting `@for` blocks, letting you read variables from the outer `@for` block from an inner `@for` block. ### Providing a fallback for `@for` blocks with the `@empty` block You can optionally include an `@empty` section immediately after the `@for` block content. The content of the `@empty` block displays when there are no items: ```angular-html @for (item of items; track item.name) { <li> {{ item.name }}</li> } @empty { <li aria-hidden="true"> There are no items. </li> } ``` ## Conditionally display content with the `@switch` block While the `@if` block is great for most scenarios, the `@switch` block provides an alternate syntax to conditionally render data. Its syntax closely resembles JavaScript's `switch` statement. ```angular-html @switch (userPermissions) { @case ('admin') { <app-admin-dashboard /> } @case ('reviewer') { <app-reviewer-dashboard /> } @case ('editor') { <app-editor-dashboard /> } @default { <app-viewer-dashboard /> } } ``` The value of the conditional expression is compared to the case expression using the triple-equals (`===`) operator. **`@switch` does not have a fallthrough**, so you do not need an equivalent to a `break` or `return` statement in the block. You can optionally include a `@default` block. The content of the `@default` block displays if none of the preceding case expressions match the switch value. If no `@case` matches the expression and there is no `@default` block, nothing is shown.
004666
# Expression Syntax Angular expressions are based on JavaScript, but differ in some key ways. This guide walks through the similarities and differences between Angular expressions and standard JavaScript. ## Value literals Angular supports a subset of [literal values](https://developer.mozilla.org/en-US/docs/Glossary/Literal) from JavaScript. ### Supported value literals | Literal type | Example values | | ------------ | ------------------------------- | | String | `'Hello'`, `"World"` | | Boolean | `true`, `false` | | Number | `123`, `3.14` | | Object | `{name: 'Alice'}` | | Array | `['Onion', 'Cheese', 'Garlic']` | | null | `null` | ### Unsupported literals | Literal type | Example value | | --------------- | --------------------- | | Template string | `` `Hello ${name}` `` | | RegExp | `/\d+/` | ## Globals Angular expressions support the following [globals](https://developer.mozilla.org/en-US/docs/Glossary/Global_object): - [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined) - [$any](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#any) No other JavaScript globals are supported. Common JavaScript globals include `Number`, `Boolean`, `NaN`, `Infinity`, `parseInt`, and more. ## Local variables Angular automatically makes special local variables available for use in expressions in specific contexts. These special variables always start with the dollar sign character (`$`). For example, `@for` blocks make several local variables corresponding to information about the loop, such as `$index`. ## What operators are supported? ### Supported operators Angular supports the following operators from standard JavaScript. | Operator | Example(s) | | --------------------- | ---------------------------------------- | | Add / Concatenate | `1 + 2` | | Subtract | `52 - 3` | | Multiply | `41 * 6` | | Divide | `20 / 4` | | Remainder (Modulo) | `17 % 5` | | Parenthesis | `9 * (8 + 4)` | | Conditional (Ternary) | `a > b ? true : false` | | And (Logical) | `&&` | | Or (Logical) | `\|\|` | | Not (Logical) | `!` | | Nullish Coalescing | `const foo = null ?? 'default'` | | Comparison Operators | `<`, `<=`, `>`, `>=`, `==`, `===`, `!==` | | Unary Negation | `const y = -x` | | Unary Plus | `const x = +y` | | Property Accessor | `person['name'] = 'Mirabel'` | Angular expressions additionally also support the following non-standard operators: | Operator | Example(s) | | ------------------------------- | ------------------------------ | | [Pipe](/guides/templates/pipes) | `{{ total \| currency }}` | | Optional chaining\* | `someObj.someProp?.nestedProp` | | Non-null assertion (TypeScript) | `someObj!.someProp` | \*Note: Optional chaining behaves differently from the standard JavaScript version in that if the left side of Angular’s optional chaining operator is `null` or `undefined`, it returns `null` instead of `undefined`. ### Unsupported operators | Operator | Example(s) | | --------------------- | --------------------------------- | | All bitwise operators | `&`, `&=`, `~`, `\|=`, `^=`, etc. | | Assignment operators | `=` | | Object destructuring | `const { name } = person` | | Array destructuring | `const [firstItem] = items` | | Comma operator | `x = (x++, x)` | | typeof | `typeof 42` | | void | `void 1` | | in | `'model' in car` | | instanceof | `car instanceof Automobile` | | new | `new Car()` | ## Lexical context for expressions Angular expressions are evaluated within the context of the component class as well as any relevant [template variables](/guide/templates/variables), locals, and globals. When referring to class members, `this` is always implied. ## Declarations Generally speaking, declarations are not supported in Angular expressions. This includes, but is not limited to: | Declarations | Example(s) | | --------------- | ------------------------------------------- | | Variables | `let label = 'abc'`, `const item = 'apple'` | | Functions | `function myCustomFunction() { }` | | Arrow Functions | `() => { }` | | Classes | `class Rectangle { }` | # Event listener statements Event handlers are **statements** rather than expressions. While they support all of the same syntax as Angular expressions, the are two key differences: 1. Statements **do support** assignment operators (but not destructing assignments) 1. Statements **do not support** pipes
004670
# Common Routing Tasks This topic describes how to implement many of the common tasks associated with adding the Angular router to your application. ## Generate an application with routing enabled The following command uses the Angular CLI to generate a basic Angular application with application routes. The application name in the following example is `routing-app`. ```shell ng new routing-app ``` ### Adding components for routing To use the Angular router, an application needs to have at least two components so that it can navigate from one to the other. To create a component using the CLI, enter the following at the command line where `first` is the name of your component: ```shell ng generate component first ``` Repeat this step for a second component but give it a different name. Here, the new name is `second`. <docs-code language="shell"> ng generate component second </docs-code> The CLI automatically appends `Component`, so if you were to write `first-component`, your component would be `FirstComponentComponent`. <docs-callout title="`base href`"> This guide works with a CLI-generated Angular application. If you are working manually, make sure that you have `<base href="/">` in the `<head>` of your index.html file. This assumes that the `app` folder is the application root, and uses `"/"`. </docs-callout> ### Importing your new components To use your new components, import them into `app.routes.ts` at the top of the file, as follows: <docs-code language="ts"> import {FirstComponent} from './first/first.component'; import {SecondComponent} from './second/second.component'; </docs-code> ## Defining a basic route There are three fundamental building blocks to creating a route. Import the routes into `app.config.ts` and add it to the `provideRouter` function. The following is the default `ApplicationConfig` using the CLI. <docs-code language="ts"> export const appConfig: ApplicationConfig = { providers: [provideRouter(routes)] }; </docs-code> The Angular CLI performs this step for you. However, if you are creating an application manually or working with an existing, non-CLI application, verify that the imports and configuration are correct. <docs-workflow> <docs-step title="Set up a `Routes` array for your routes"> The Angular CLI performs this step automatically. ```ts import { Routes } from '@angular/router'; export const routes: Routes = []; ``` </docs-step> <docs-step title="Define your routes in your `Routes` array"> Each route in this array is a JavaScript object that contains two properties. The first property, `path`, defines the URL path for the route. The second property, `component`, defines the component Angular should use for the corresponding path. ```ts const routes: Routes = [ { path: 'first-component', component: FirstComponent }, { path: 'second-component', component: SecondComponent }, ]; ``` </docs-step> <docs-step title="Add your routes to your application"> Now that you have defined your routes, add them to your application. First, add links to the two components. Assign the anchor tag that you want to add the route to the `routerLink` attribute. Set the value of the attribute to the component to show when a user clicks on each link. Next, update your component template to include `<router-outlet>`. This element informs Angular to update the application view with the component for the selected route. ```angular-html <h1>Angular Router App</h1> <nav> <ul> <li><a routerLink="/first-component" routerLinkActive="active" ariaCurrentWhenActive="page">First Component</a></li> <li><a routerLink="/second-component" routerLinkActive="active" ariaCurrentWhenActive="page">Second Component</a></li> </ul> </nav> <!-- The routed views render in the <router-outlet>--> <router-outlet></router-outlet> ``` You also need to add the `RouterLink`, `RouterLinkActive`, and `RouterOutlet` to the `imports` array of `AppComponent`. ```ts @Component({ selector: 'app-root', standalone: true, imports: [CommonModule, RouterOutlet, RouterLink, RouterLinkActive], templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'routing-app'; } ``` </docs-step> </docs-workflow> ### Route order The order of routes is important because the `Router` uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. List routes with a static path first, followed by an empty path route, which matches the default route. The [wildcard route](guide/routing/common-router-tasks#setting-up-wildcard-routes) comes last because it matches every URL and the `Router` selects it only if no other routes match first. ## Getting route information Often, as a user navigates your application, you want to pass information from one component to another. For example, consider an application that displays a shopping list of grocery items. Each item in the list has a unique `id`. To edit an item, users click an Edit button, which opens an `EditGroceryItem` component. You want that component to retrieve the `id` for the grocery item so it can display the right information to the user. Use a route to pass this type of information to your application components. To do so, you use the [withComponentInputBinding](api/router/withComponentInputBinding) feature with `provideRouter` or the `bindToComponentInputs` option of `RouterModule.forRoot`. To get information from a route: <docs-workflow> <docs-step title="Add `withComponentInputBinding`"> Add the `withComponentInputBinding` feature to the `provideRouter` method. ```ts providers: [ provideRouter(appRoutes, withComponentInputBinding()), ] ``` </docs-step> <docs-step title="Add an `Input` to the component"> Update the component to have an `Input` matching the name of the parameter. ```ts @Input() set id(heroId: string) { this.hero$ = this.service.getHero(heroId); } ``` NOTE: You can bind all route data with key, value pairs to component inputs: static or resolved route data, path parameters, matrix parameters, and query parameters. If you want to use the parent components route info you will need to set the router `paramsInheritanceStrategy` option: `withRouterConfig({paramsInheritanceStrategy: 'always'})` </docs-step> </docs-workflow> ## Setting up wildcard routes A well-functioning application should gracefully handle when users attempt to navigate to a part of your application that does not exist. To add this functionality to your application, you set up a wildcard route. The Angular router selects this route any time the requested URL doesn't match any router paths. To set up a wildcard route, add the following code to your `routes` definition. <docs-code> { path: '**', component: <component-name> } </docs-code> The two asterisks, `**`, indicate to Angular that this `routes` definition is a wildcard route. For the component property, you can define any component in your application. Common choices include an application-specific `PageNotFoundComponent`, which you can define to [display a 404 page](guide/routing/common-router-tasks#displaying-a-404-page) to your users; or a redirect to your application's main component. A wildcard route is the last route because it matches any URL. For more detail on why order matters for routes, see [Route order](guide/routing/common-router-tasks#route-order). ## Displaying a 404 page To display a 404 page, set up a [wildcard route](guide/routing/common-router-tasks#setting-up-wildcard-routes) with the `component` property set to the component you'd like to use for your 404 page as follows: ```ts const routes: Routes = [ { path: 'first-component', component: FirstComponent }, { path: 'second-component', component: SecondComponent }, { path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page ]; ``` The last route with the `path` of `**` is a wildcard route. The router selects this route if the requested URL doesn't match any of the paths earlier in the list and sends the user to the `PageNotFoundComponent`.
004671
## Setting up redirects To set up a redirect, configure a route with the `path` you want to redirect from, the `component` you want to redirect to, and a `pathMatch` value that tells the router how to match the URL. ```ts const routes: Routes = [ { path: 'first-component', component: FirstComponent }, { path: 'second-component', component: SecondComponent }, { path: '', redirectTo: '/first-component', pathMatch: 'full' }, // redirect to `first-component` { path: '**', component: PageNotFoundComponent }, // Wildcard route for a 404 page ]; ``` In this example, the third route is a redirect so that the router defaults to the `first-component` route. Notice that this redirect precedes the wildcard route. Here, `path: ''` means to use the initial relative URL \(`''`\). Sometimes a redirect is not a simple, static redirect. The `redirectTo` property can also be a function with more complex logic that returns a string or `UrlTree`. ```ts const routes: Routes = [ { path: "first-component", component: FirstComponent }, { path: "old-user-page", redirectTo: ({ queryParams }) => { const errorHandler = inject(ErrorHandler); const userIdParam = queryParams['userId']; if (userIdParam !== undefined) { return `/user/${userIdParam}`; } else { errorHandler.handleError(new Error('Attempted navigation to user page without user ID.')); return `/not-found`; } }, }, { path: "user/:userId", component: OtherComponent }, ]; ``` ## Nesting routes As your application grows more complex, you might want to create routes that are relative to a component other than your root component. These types of nested routes are called child routes. This means you're adding a second `<router-outlet>` to your app, because it is in addition to the `<router-outlet>` in `AppComponent`. In this example, there are two additional child components, `child-a`, and `child-b`. Here, `FirstComponent` has its own `<nav>` and a second `<router-outlet>` in addition to the one in `AppComponent`. ```angular-html <h2>First Component</h2> <nav> <ul> <li><a routerLink="child-a">Child A</a></li> <li><a routerLink="child-b">Child B</a></li> </ul> </nav> <router-outlet></router-outlet> ``` A child route is like any other route, in that it needs both a `path` and a `component`. The one difference is that you place child routes in a `children` array within the parent route. ```ts const routes: Routes = [ { path: 'first-component', component: FirstComponent, // this is the component with the <router-outlet> in the template children: [ { path: 'child-a', // child route path component: ChildAComponent, // child route component that the router renders }, { path: 'child-b', component: ChildBComponent, // another child route component that the router renders }, ], }, ]; ``` ## Setting the page title Each page in your application should have a unique title so that they can be identified in the browser history. The `Router` sets the document's title using the `title` property from the `Route` config. ```ts const routes: Routes = [ { path: 'first-component', title: 'First component', component: FirstComponent, // this is the component with the <router-outlet> in the template children: [ { path: 'child-a', // child route path title: resolvedChildATitle, component: ChildAComponent, // child route component that the router renders }, { path: 'child-b', title: 'child b', component: ChildBComponent, // another child route component that the router renders }, ], }, ]; const resolvedChildATitle: ResolveFn<string> = () => Promise.resolve('child a'); ``` HELPFUL: The `title` property follows the same rules as static route `data` and dynamic values that implement `ResolveFn`. You can also provide a custom title strategy by extending the `TitleStrategy`. ```ts @Injectable({providedIn: 'root'}) export class TemplatePageTitleStrategy extends TitleStrategy { constructor(private readonly title: Title) { super(); } override updateTitle(routerState: RouterStateSnapshot) { const title = this.buildTitle(routerState); if (title !== undefined) { this.title.setTitle(`My Application | ${title}`); } } } export const appConfig: ApplicationConfig = { providers: [ provideRouter(routes), {provide: TitleStrategy, useClass: TemplatePageTitleStrategy}, ] }; ``` ## Using relative paths Relative paths let you define paths that are relative to the current URL segment. The following example shows a relative route to another component, `second-component`. `FirstComponent` and `SecondComponent` are at the same level in the tree, however, the link to `SecondComponent` is situated within the `FirstComponent`, meaning that the router has to go up a level and then into the second directory to find the `SecondComponent`. Rather than writing out the whole path to get to `SecondComponent`, use the `../` notation to go up a level. ```angular-html <h2>First Component</h2> <nav> <ul> <li><a routerLink="../second-component">Relative Route to second component</a></li> </ul> </nav> <router-outlet></router-outlet> ``` In addition to `../`, use `./` or no leading slash to specify the current level. ### Specifying a relative route To specify a relative route, use the `NavigationExtras` `relativeTo` property. In the component class, import `NavigationExtras` from the `@angular/router`. Then use `relativeTo` in your navigation method. After the link parameters array, which here contains `items`, add an object with the `relativeTo` property set to the `ActivatedRoute`, which is `this.route`. ```ts goToItems() { this.router.navigate(['items'], { relativeTo: this.route }); } ``` The `navigate()` arguments configure the router to use the current route as a basis upon which to append `items`. The `goToItems()` method interprets the destination URI as relative to the activated route and navigates to the `items` route. ## Accessing query parameters and fragments Sometimes, a feature of your application requires accessing a part of a route, such as a query parameter or a fragment. In this example, the route contains an `id` parameter we can use to target a specific hero page. ```ts import {ApplicationConfig} from "@angular/core"; import {Routes} from '@angular/router'; import {HeroListComponent} from './hero-list.component'; export const routes: Routes = [ {path: 'hero/:id', component: HeroDetailComponent} ]; export const appConfig: ApplicationConfig = { providers: [provideRouter(routes)], }; ``` First, import the following members in the component you want to navigate from. ```ts import { ActivatedRoute } from '@angular/router'; import { Observable } from 'rxjs'; import { switchMap } from 'rxjs/operators'; ``` Next inject the activated route service: ```ts constructor(private route: ActivatedRoute) {} ``` Configure the class so that you have an observable, `heroes$`, a `selectedId` to hold the `id` number of the hero, and the heroes in the `ngOnInit()`, add the following code to get the `id` of the selected hero. This code snippet assumes that you have a heroes list, a hero service, a function to get your heroes, and the HTML to render your list and details, just as in the Tour of Heroes example. ```ts heroes$: Observable<Hero[]>; selectedId: number; heroes = HEROES; ngOnInit() { this.heroes$ = this.route.paramMap.pipe( switchMap(params => { this.selectedId = Number(params.get('id')); return this.service.getHeroes(); }) ); } ``` Next, in the component that you want to navigate to, import the following members. ```ts import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { Observable } from 'rxjs'; ``` Inject `ActivatedRoute` and `Router` in the constructor of the component class so they are available to this component: ```ts hero$: Observable<Hero>; constructor( private route: ActivatedRoute, private router: Router ) {} ngOnInit() { const heroId = this.route.snapshot.paramMap.get('id'); this.hero$ = this.service.getHero(heroId); } gotoItems(hero: Hero) { const heroId = hero ? hero.id : null; // Pass along the hero id if available // so that the HeroList component can select that item. this.router.navigate(['/heroes', { id: heroId }]); } ```
004672
## Lazy loading You can configure your routes to lazy load modules, which means that Angular only loads modules as needed, rather than loading all modules when the application launches. Additionally, preload parts of your application in the background to improve the user experience. Any route can lazily load its routed, standalone component by using `loadComponent:` <docs-code header="Lazy loading a standalone component" language="typescript"> const routes: Routes = [ { path: 'lazy', loadComponent: () => import('./lazy.component').then(c => c.LazyComponent) } ]; </docs-code> This works as long as the loaded component is standalone. For more information on lazy loading and preloading see the dedicated guide [Lazy loading](guide/ngmodules/lazy-loading). ## Preventing unauthorized access Use route guards to prevent users from navigating to parts of an application without authorization. The following route guards are available in Angular: <docs-pill-row> <docs-pill href="api/router/CanActivateFn" title="`canActivate`"/> <docs-pill href="api/router/CanActivateChildFn" title="`canActivateChild`"/> <docs-pill href="api/router/CanDeactivateFn" title="`canDeactivate`"/> <docs-pill href="api/router/CanMatchFn" title="`canMatch`"/> <docs-pill href="api/router/ResolveFn" title="`resolve`"/> <docs-pill href="api/router/CanLoadFn" title="`canLoad`"/> </docs-pill-row> To use route guards, consider using [component-less routes](api/router/Route#componentless-routes) as this facilitates guarding child routes. Create a file for your guard: ```bash ng generate guard your-guard ``` In your guard file, add the guard functions you want to use. The following example uses `canActivateFn` to guard the route. ```ts export const yourGuardFunction: CanActivateFn = ( next: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { // your logic goes here } ``` In your routing module, use the appropriate property in your `routes` configuration. Here, `canActivate` tells the router to mediate navigation to this particular route. ```ts { path: '/your-path', component: YourComponent, canActivate: [yourGuardFunction], } ``` ## Link parameters array A link parameters array holds the following ingredients for router navigation: - The path of the route to the destination component - Required and optional route parameters that go into the route URL Bind the `RouterLink` directive to such an array like this: ```angular-html <a [routerLink]="['/heroes']">Heroes</a> ``` The following is a two-element array when specifying a route parameter: ```angular-html <a [routerLink]="['/hero', hero.id]"> <span class="badge">{{ hero.id }}</span>{{ hero.name }} </a> ``` Provide optional route parameters in an object, as in `{ foo: 'foo' }`: ```angular-html <a [routerLink]="['/crisis-center', { foo: 'foo' }]">Crisis Center</a> ``` These three examples cover the needs of an application with one level of routing. However, with a child router, such as in the crisis center, you create new link array possibilities. The following minimal `RouterLink` example builds upon a specified default child route for the crisis center. ```angular-html <a [routerLink]="['/crisis-center']">Crisis Center</a> ``` Review the following: - The first item in the array identifies the parent route \(`/crisis-center`\) - There are no parameters for this parent route - There is no default for the child route so you need to pick one - You're navigating to the `CrisisListComponent`, whose route path is `/`, but you don't need to explicitly add the slash Consider the following router link that navigates from the root of the application down to the Dragon Crisis: ```angular-html <a [routerLink]="['/crisis-center', 1]">Dragon Crisis</a> ``` - The first item in the array identifies the parent route \(`/crisis-center`\) - There are no parameters for this parent route - The second item identifies the child route details about a particular crisis \(`/:id`\) - The details child route requires an `id` route parameter - You added the `id` of the Dragon Crisis as the second item in the array \(`1`\) - The resulting path is `/crisis-center/1` You could also redefine the `AppComponent` template with Crisis Center routes exclusively: ```angular-ts @Component({ template: ` <h1 class="title">Angular Router</h1> <nav> <a [routerLink]="['/crisis-center']">Crisis Center</a> <a [routerLink]="['/crisis-center/1', { foo: 'foo' }]">Dragon Crisis</a> <a [routerLink]="['/crisis-center/2']">Shark Crisis</a> </nav> <router-outlet></router-outlet> ` }) export class AppComponent {} ``` In summary, you can write applications with one, two or more levels of routing. The link parameters array affords the flexibility to represent any routing depth and any legal sequence of route paths, \(required\) router parameters, and \(optional\) route parameter objects. ## `LocationStrategy` and browser URL styles When the router navigates to a new component view, it updates the browser's location and history with a URL for that view. Modern HTML5 browsers support [history.pushState](https://developer.mozilla.org/docs/Web/API/History_API/Working_with_the_History_API#adding_and_modifying_history_entries 'HTML5 browser history push-state'), a technique that changes a browser's location and history without triggering a server page request. The router can compose a "natural" URL that is indistinguishable from one that would otherwise require a page load. Here's the Crisis Center URL in this "HTML5 pushState" style: ```text localhost:3002/crisis-center ``` Older browsers send page requests to the server when the location URL changes unless the change occurs after a "#" \(called the "hash"\). Routers can take advantage of this exception by composing in-application route URLs with hashes. Here's a "hash URL" that routes to the Crisis Center. ```text localhost:3002/src/#/crisis-center ``` The router supports both styles with two `LocationStrategy` providers: | Providers | Details | | :--------------------- | :----------------------------------- | | `PathLocationStrategy` | The default "HTML5 pushState" style. | | `HashLocationStrategy` | The "hash URL" style. | The `RouterModule.forRoot()` function sets the `LocationStrategy` to the `PathLocationStrategy`, which makes it the default strategy. You also have the option of switching to the `HashLocationStrategy` with an override during the bootstrapping process. HELPFUL: For more information on providers and the bootstrap process, see [Dependency Injection](guide/di/dependency-injection-providers). ## Choosing a routing strategy You must choose a routing strategy early in the development of your project because once the application is in production, visitors to your site use and depend on application URL references. Almost all Angular projects should use the default HTML5 style. It produces URLs that are easier for users to understand and it preserves the option to do server-side rendering. Rendering critical pages on the server is a technique that can greatly improve perceived responsiveness when the application first loads. An application that would otherwise take ten or more seconds to start could be rendered on the server and delivered to the user's device in less than a second. This option is only available if application URLs look like normal web URLs without hash \(`#`\) characters in the middle.
004673
## `<base href>` The router uses the browser's [history.pushState](https://developer.mozilla.org/docs/Web/API/History_API/Working_with_the_History_API#adding_and_modifying_history_entries 'HTML5 browser history push-state') for navigation. `pushState` lets you customize in-application URL paths; for example, `localhost:4200/crisis-center`. The in-application URLs can be indistinguishable from server URLs. Modern HTML5 browsers were the first to support `pushState` which is why many people refer to these URLs as "HTML5 style" URLs. HELPFUL: HTML5 style navigation is the router default. In the [LocationStrategy and browser URL styles](#locationstrategy-and-browser-url-styles) section, learn why HTML5 style is preferable, how to adjust its behavior, and how to switch to the older hash \(`#`\) style, if necessary. You must add a [`<base href>` element](https://developer.mozilla.org/docs/Web/HTML/Element/base 'base href') to the application's `index.html` for `pushState` routing to work. The browser uses the `<base href>` value to prefix relative URLs when referencing CSS files, scripts, and images. Add the `<base>` element just after the `<head>` tag. If the `app` folder is the application root, as it is for this application, set the `href` value in `index.html` as shown here. <docs-code header="src/index.html (base-href)" path="adev/src/content/examples/router/src/index.html" visibleRegion="base-href"/> ### HTML5 URLs and the `<base href>` The guidelines that follow will refer to different parts of a URL. This diagram outlines what those parts refer to: <docs-code hideCopy language="text"> foo://example.com:8042/over/there?name=ferret#nose \_/ \______________/\_________/ \_________/ \__/ | | | | | scheme authority path query fragment </docs-code> While the router uses the [HTML5 pushState](https://developer.mozilla.org/docs/Web/API/History_API#Adding_and_modifying_history_entries 'Browser history push-state') style by default, you must configure that strategy with a `<base href>`. The preferred way to configure the strategy is to add a [`<base href>` element](https://developer.mozilla.org/docs/Web/HTML/Element/base 'base href') tag in the `<head>` of the `index.html`. ```angular-html <base href="/"> ``` Without that tag, the browser might not be able to load resources \(images, CSS, scripts\) when "deep linking" into the application. Some developers might not be able to add the `<base>` element, perhaps because they don't have access to `<head>` or the `index.html`. Those developers can still use HTML5 URLs by taking the following two steps: 1. Provide the router with an appropriate `APP_BASE_HREF` value. 1. Use root URLs \(URLs with an `authority`\) for all web resources: CSS, images, scripts, and template HTML files. - The `<base href>` `path` should end with a "/", as browsers ignore characters in the `path` that follow the right-most "`/`" - If the `<base href>` includes a `query` part, the `query` is only used if the `path` of a link in the page is empty and has no `query`. This means that a `query` in the `<base href>` is only included when using `HashLocationStrategy`. - If a link in the page is a root URL \(has an `authority`\), the `<base href>` is not used. In this way, an `APP_BASE_HREF` with an authority will cause all links created by Angular to ignore the `<base href>` value. - A fragment in the `<base href>` is _never_ persisted For more complete information on how `<base href>` is used to construct target URIs, see the [RFC](https://tools.ietf.org/html/rfc3986#section-5.2.2) section on transforming references. ### `HashLocationStrategy` Use `HashLocationStrategy` by providing the `useHash: true` in an object as the second argument of the `RouterModule.forRoot()` in the `AppModule`. ```ts providers: [ provideRouter(appRoutes, withHashLocation()) ] ``` When using `RouterModule.forRoot`, this is configured with the `useHash: true` in the second argument: `RouterModule.forRoot(routes, {useHash: true})`.
004674
# Router reference The following sections highlight some core router concepts. ## Router imports The Angular Router is an optional service that presents a particular component view for a given URL. It isn't part of the Angular core and thus is in its own library package, `@angular/router`. Import what you need from it as you would from any other Angular package. ```ts import { provideRouter } from '@angular/router'; ``` HELPFUL: For more on browser URL styles, see [`LocationStrategy` and browser URL styles](guide/routing/common-router-tasks#browser-url-styles). ## Configuration A routed Angular application has one singleton instance of the `Router` service. When the browser's URL changes, that router looks for a corresponding `Route` from which it can determine the component to display. A router has no routes until you configure it. The following example creates five route definitions, configures the router via the `provideRouter` method, and adds the result to the `providers` array of the `ApplicationConfig`'. ```ts const appRoutes: Routes = [ { path: 'crisis-center', component: CrisisListComponent }, { path: 'hero/:id', component: HeroDetailComponent }, { path: 'heroes', component: HeroListComponent, data: { title: 'Heroes List' } }, { path: '', redirectTo: '/heroes', pathMatch: 'full' }, { path: '**', component: PageNotFoundComponent } ]; export const appConfig: ApplicationConfig = { providers: [provideRouter(appRoutes, withDebugTracing())] } ``` The `routes` array of routes describes how to navigate. Pass it to the `provideRouter` method in the `ApplicationConfig` `providers` to configure the router. Each `Route` maps a URL `path` to a component. There are no leading slashes in the path. The router parses and builds the final URL for you, which lets you use both relative and absolute paths when navigating between application views. The `:id` in the second route is a token for a route parameter. In a URL such as `/hero/42`, "42" is the value of the `id` parameter. The corresponding `HeroDetailComponent` uses that value to find and present the hero whose `id` is 42. The `data` property in the third route is a place to store arbitrary data associated with this specific route. The data property is accessible within each activated route. Use it to store items such as page titles, breadcrumb text, and other read-only, static data. Use the resolve guard to retrieve dynamic data. The empty path in the fourth route represents the default path for the application —the place to go when the path in the URL is empty, as it typically is at the start. This default route redirects to the route for the `/heroes` URL and, therefore, displays the `HeroesListComponent`. If you need to see what events are happening during the navigation lifecycle, there is the `withDebugTracing` feature. This outputs each router event that took place during each navigation lifecycle to the browser console. Use `withDebugTracing` only for debugging purposes. You set the `withDebugTracing` option in the object passed as the second argument to the `provideRouter` method. ## Router outlet The `RouterOutlet` is a directive from the router library that is used like a component. It acts as a placeholder that marks the spot in the template where the router should display the components for that outlet. <docs-code language="html"> <router-outlet></router-outlet> <!-- Routed components go here --> </docs-code> Given the preceding configuration, when the browser URL for this application becomes `/heroes`, the router matches that URL to the route path `/heroes` and displays the `HeroListComponent` as a sibling element to the `RouterOutlet` that you've placed in the host component's template. ## Router links To navigate as a result of some user action such as the click of an anchor tag, use `RouterLink`. Consider the following template: <docs-code header="src/app/app.component.html" path="adev/src/content/examples/router/src/app/app.component.1.html"/> The `RouterLink` directives on the anchor tags give the router control over those elements. The navigation paths are fixed, so you can assign a string as a one-time binding to the `routerLink`. Had the navigation path been more dynamic, you could have bound to a template expression that returned an array of route link parameters; that is, the [link parameters array](guide/routing/common-router-tasks#link-parameters-array). The router resolves that array into a complete URL. ## Active router links The `RouterLinkActive` directive toggles CSS classes for active `RouterLink` bindings based on the current `RouterState`. On each anchor tag, you see a [property binding](guide/templates/property-binding) to the `RouterLinkActive` directive that looks like <docs-code hideCopy language="html"> routerLinkActive="..." </docs-code> The template expression to the right of the equal sign, `=`, contains a space-delimited string of CSS classes that the Router adds when this link is active and removes when the link is inactive. You set the `RouterLinkActive` directive to a string of classes such as `routerLinkActive="active fluffy"` or bind it to a component property that returns such a string. For example, <docs-code hideCopy language="typescript"> [routerLinkActive]="someStringProperty" </docs-code> Active route links cascade down through each level of the route tree, so parent and child router links can be active at the same time. To override this behavior, bind to the `[routerLinkActiveOptions]` input binding with the `{ exact: true }` expression. By using `{ exact: true }`, a given `RouterLink` is only active if its URL is an exact match to the current URL. `RouterLinkActive` also allows you to easily apply the `aria-current` attribute to the active element, thus providing a more accessible experience for all users. For more information see the Accessibility Best Practices [Active links identification section](/best-practices/a11y#active-links-identification). ## Router state After the end of each successful navigation lifecycle, the router builds a tree of `ActivatedRoute` objects that make up the current state of the router. You can access the current `RouterState` from anywhere in the application using the `Router` service and the `routerState` property. Each `ActivatedRoute` in the `RouterState` provides methods to traverse up and down the route tree to get information from parent, child, and sibling routes. ## Activated route The route path and parameters are available through an injected router service called the [ActivatedRoute](api/router/ActivatedRoute). It has a great deal of useful information including: | Property | Details | |:--- |:--- | | `url` | An `Observable` of the route paths, represented as an array of strings for each part of the route path. | | `data` | An `Observable` that contains the `data` object provided for the route. Also contains any resolved values from the resolve guard. | | `params` | An `Observable` that contains the required and optional parameters specific to the route. | | `paramMap` | An `Observable` that contains a [map](api/router/ParamMap) of the required and optional parameters specific to the route. The map supports retrieving single and multiple values from the same parameter. | | `queryParamMap` | An `Observable` that contains a [map](api/router/ParamMap) of the query parameters available to all routes. The map supports retrieving single and multiple values from the query parameter. | | `queryParams` | An `Observable` that contains the query parameters available to all routes. | | `fragment` | An `Observable` of the URL fragment available to all routes. | | `outlet` | The name of the `RouterOutlet` used to render the route. For an unnamed outlet, the outlet name is primary. | | `routeConfig` | The route configuration used for the route that contains the origin path. | | `parent` | The route's parent `ActivatedRoute` when this route is a child route. | | `firstChild` | Contains the first `ActivatedRoute` in the list of this route's child routes. | | `children` | Contains all the child routes activated under the current route. | ##
004675
Router events During each navigation, the `Router` emits navigation events through the `Router.events` property. These events are shown in the following table. | Router event | Details | |:--- |:--- | | [`NavigationStart`](api/router/NavigationStart) | Triggered when navigation starts. | | [`RouteConfigLoadStart`](api/router/RouteConfigLoadStart) | Triggered before the `Router` lazy loads a route configuration. | | [`RouteConfigLoadEnd`](api/router/RouteConfigLoadEnd) | Triggered after a route has been lazy loaded. | | [`RoutesRecognized`](api/router/RoutesRecognized) | Triggered when the Router parses the URL and the routes are recognized. | | [`GuardsCheckStart`](api/router/GuardsCheckStart) | Triggered when the Router begins the Guards phase of routing. | | [`ChildActivationStart`](api/router/ChildActivationStart) | Triggered when the Router begins activating a route's children. | | [`ActivationStart`](api/router/ActivationStart) | Triggered when the Router begins activating a route. | | [`GuardsCheckEnd`](api/router/GuardsCheckEnd) | Triggered when the Router finishes the Guards phase of routing successfully. | | [`ResolveStart`](api/router/ResolveStart) | Triggered when the Router begins the Resolve phase of routing. | | [`ResolveEnd`](api/router/ResolveEnd) | Triggered when the Router finishes the Resolve phase of routing successfully. | | [`ChildActivationEnd`](api/router/ChildActivationEnd) | Triggered when the Router finishes activating a route's children. | | [`ActivationEnd`](api/router/ActivationEnd) | Triggered when the Router finishes activating a route. | | [`NavigationEnd`](api/router/NavigationEnd) | Triggered when navigation ends successfully. | | [`NavigationCancel`](api/router/NavigationCancel) | Triggered when navigation is canceled. This can happen when a Route Guard returns false during navigation, or redirects by returning a `UrlTree` or `RedirectCommand`. | | [`NavigationError`](api/router/NavigationError) | Triggered when navigation fails due to an unexpected error. | | [`Scroll`](api/router/Scroll) | Represents a scrolling event. | When you enable the `withDebugTracing` feature, Angular logs these events to the console. ## Router terminology Here are the key `Router` terms and their meanings: | Router part | Details | |:--- |:--- | | `Router` | Displays the application component for the active URL. Manages navigation from one component to the next. | | `provideRouter` | provides the necessary service providers for navigating through application views. | | `RouterModule` | A separate NgModule that provides the necessary service providers and directives for navigating through application views. | | `Routes` | Defines an array of Routes, each mapping a URL path to a component. | | `Route` | Defines how the router should navigate to a component based on a URL pattern. Most routes consist of a path and a component type. | | `RouterOutlet` | The directive \(`<router-outlet>`\) that marks where the router displays a view. | | `RouterLink` | The directive for binding a clickable HTML element to a route. Clicking an element with a `routerLink` directive that's bound to a *string* or a *link parameters array* triggers a navigation. | | `RouterLinkActive` | The directive for adding/removing classes from an HTML element when an associated `routerLink` contained on or inside the element becomes active/inactive. It can also set the `aria-current` of an active link for better accessibility. | | `ActivatedRoute` | A service that's provided to each route component that contains route specific information such as route parameters, static data, resolve data, global query parameters, and the global fragment. | | `RouterState` | The current state of the router including a tree of the currently activated routes together with convenience methods for traversing the route tree. | | Link parameters array | An array that the router interprets as a routing instruction. You can bind that array to a `RouterLink` or pass the array as an argument to the `Router.navigate` method. | | Routing component | An Angular component with a `RouterOutlet` that displays views based on router navigations. |
004678
## Identify the active route While users can navigate your application using the links you added in the previous section, they don't have a straightforward way to identify what the active route is. Add this functionality using Angular's `routerLinkActive` directive. 1. From your code editor, open the `app.component.html` file. 1. Update the anchor tags to include the `routerLinkActive` directive. <docs-code header="src/app/app.component.html" path="adev/src/content/examples/router-tutorial/src/app/app.component.html" visibleRegion="routeractivelink"/> 1. Add the `RouterLinkActive` directive to the `imports` list of `AppComponent` in `app.component.ts`. View your application again. As you click one of the buttons, the style for that button updates automatically, identifying the active component to the user. By adding the `routerLinkActive` directive, you inform your application to apply a specific CSS class to the active route. In this tutorial, that CSS class is `activebutton`, but you could use any class that you want. Note that we are also specifying a value for the `routerLinkActive`'s `ariaCurrentWhenActive`. This makes sure that visually impaired users (which may not perceive the different styling being applied) can also identify the active button. For more information see the Accessibility Best Practices [Active links identification section](/best-practices/a11y#active-links-identification). ## Adding a redirect In this step of the tutorial, you add a route that redirects the user to display the `/heroes-list` component. 1. From your code editor, open the `app.routes.ts` file. 1. Update the `routes` section as follows. ```ts {path: '', redirectTo: '/heroes-list', pathMatch: 'full'}, ``` Notice that this new route uses an empty string as its path. In addition, it replaces the `component` property with two new ones: | Properties | Details | |:--- |:--- | | `redirectTo` | This property instructs Angular to redirect from an empty path to the `heroes-list` path. | | `pathMatch` | This property instructs Angular on how much of the URL to match. For this tutorial, you should set this property to `full`. This strategy is recommended when you have an empty string for a path. For more information about this property, see the [Route API documentation](api/router/Route). | Now when you open your application, it displays the `heroes-list` component by default. ## Adding a 404 page It is possible for a user to try to access a route that you have not defined. To account for this behavior, the best practice is to display a 404 page. In this section, you'll create a 404 page and update your route configuration to show that page for any unspecified routes. 1. From the terminal, create a new component, `PageNotFound`. <docs-code language="shell"> ng generate component page-not-found </docs-code> 1. From your code editor, open the `page-not-found.component.html` file and replace its contents with the following HTML. <docs-code header="src/app/page-not-found/page-not-found.component.html" path="adev/src/content/examples/router-tutorial/src/app/page-not-found/page-not-found.component.html"/> 1. Open the `app.routes.ts` file and add the following route to the routes list: ```ts {path: '**', component: PageNotFoundComponent} ``` The new route uses a path, `**`. This path is how Angular identifies a wildcard route. Any route that does not match an existing route in your configuration will use this route. IMPORTANT: Notice that the wildcard route is placed at the end of the array. The order of your routes is important, as Angular applies routes in order and uses the first match it finds. Try navigating to a non-existing route on your application, such as `http://localhost:4200/powers`. This route doesn't match anything defined in your `app.routes.ts` file. However, because you defined a wildcard route, the application automatically displays your `PageNotFound` component. ## Next steps At this point, you have a basic application that uses Angular's routing feature to change what components the user can see based on the URL address. You have extended these features to include a redirect, as well as a wildcard route to display a custom 404 page. For more information about routing, see the following topics: <docs-pill-row> <docs-pill href="guide/routing/common-router-tasks" title="In-app Routing and Navigation"/> <docs-pill href="api/router/Router" title="Router API"/> </docs-pill-row>
004679
<docs-decorative-header title="Performance" imgSrc="adev/src/assets/images/overview.svg"> <!-- markdownlint-disable-line --> Learn about different ways you can optimize the performance of your application. </docs-decorative-header> One of the top priorities of any developer is ensuring that their application is as performant as possible. These guides are here to help you follow best practices for building performant applications. That said, please note that these best practices will only take the performance of your application so far. At the end of the day, we encourage you to measure performance in order to best understand what custom optimizations are best for your application. | Guides Types | Description | | :---------------------------------------- | :--------------------------------------------------------------------------------------------------------- | | [Deferrable views](/guide/defer) | Defer loading of select dependencies within a template by wrapping corresponding parts in a `@defer` block. | | [Image optimization](/guide/image-optimization) | Use the `NgOptimizedImage` directive to adopt best practices for loading images. | | [Server-side rendering](/guide/ssr) | Learn how to leverage rendering pages on the server to improve load times. | | [Build-time prerendering](/guide/prerendering) | Also known as static-side generation (SSG), is an alternate rendering method to improve load times. | | [Hydration](/guide/hydration) | A process to improve application performance by restoring its state after server-side rendering and reusing existing DOM structure as much as possible. |
004690
# Add the localize package To take advantage of the localization features of Angular, use the [Angular CLI][CliMain] to add the `@angular/localize` package to your project. To add the `@angular/localize` package, use the following command to update the `package.json` and TypeScript configuration files in your project. <docs-code path="adev/src/content/examples/i18n/doc-files/commands.sh" visibleRegion="add-localize"/> It adds `types: ["@angular/localize"]` in the TypeScript configuration files as well as the reference to the type definition of `@angular/localize` at the top of the `main.ts` file. HELPFUL: For more information about `package.json` and `tsconfig.json` files, see [Workspace npm dependencies][GuideNpmPackages] and [TypeScript Configuration][GuideTsConfig]. If `@angular/localize` is not installed and you try to build a localized version of your project (for example, while using the `i18n` attributes in templates), the [Angular CLI][CliMain] will generate an error, which would contain the steps that you can take to enable i18n for your project. ## Options | OPTION | DESCRIPTION | VALUE TYPE | DEFAULT VALUE |:--- |:--- |:------ |:------ | `--project` | The name of the project. | `string` | | `--use-at-runtime` | If set, then `$localize` can be used at runtime. Also `@angular/localize` gets included in the `dependencies` section of `package.json`, rather than `devDependencies`, which is the default. | `boolean` | `false` For more available options, see `ng add` in [Angular CLI][CliMain]. ## What's next <docs-pill-row> <docs-pill href="guide/i18n/locale-id" title="Refer to locales by ID"/> </docs-pill-row> [CliMain]: cli "CLI Overview and Command Reference | Angular" [GuideNpmPackages]: reference/configs/npm-packages "Workspace npm dependencies | Angular" [GuideTsConfig]: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html "TypeScript Configuration"