_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
angular/adev/src/app/editor/terminal/terminal.component.spec.ts_0_1819 | /*!
* @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 {By} from '@angular/platform-browser';
import {Terminal} from './terminal.component';
import {TerminalHandler, TerminalType} from './terminal-handler.service';
import {WINDOW} from '@angular/docs';
import {FakeEventTarget} from '@angular/docs';
describe('Terminal', () => {
let component: Terminal;
let fixture: ComponentFixture<Terminal>;
let terminalHandlerSpy: jasmine.SpyObj<TerminalHandler>;
const fakeWindow = new FakeEventTarget();
beforeEach(async () => {
terminalHandlerSpy = jasmine.createSpyObj('TerminalHandler', [
'registerTerminal',
'resizeToFitParent',
]);
await TestBed.configureTestingModule({
imports: [Terminal],
providers: [
{provide: TerminalHandler, useValue: terminalHandlerSpy},
{
provide: WINDOW,
useValue: fakeWindow,
},
],
}).compileComponents();
fixture = TestBed.createComponent(Terminal);
component = fixture.componentInstance;
component.type = TerminalType.READONLY;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should register the terminal element on afterViewInit', () => {
const terminalDebugElement = fixture.debugElement.query(By.css('.adev-terminal-output'));
component['terminalElementRef'] = terminalDebugElement;
component.ngAfterViewInit();
expect(terminalHandlerSpy.registerTerminal).toHaveBeenCalledWith(
TerminalType.READONLY,
terminalDebugElement.nativeElement,
);
});
});
| {
"end_byte": 1819,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/terminal/terminal.component.spec.ts"
} |
angular/adev/src/app/editor/terminal/terminal.component.scss_0_444 | // Note: disabling the @angular/no-import rule here as it's meant to disable
// SASS imports, here we're importing a CSS asset
//
// stylelint-disable-next-line @angular/no-import
@import '@xterm/xterm/css/xterm.css';
.docs-tutorial-terminal {
display: block;
// adjust height for terminal tabs
height: calc(100% - 49px);
overflow: hidden;
}
.docs-tutorial-terminal-only {
height: 100%;
}
.adev-terminal-output {
height: 100%;
}
| {
"end_byte": 444,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/terminal/terminal.component.scss"
} |
angular/adev/src/app/editor/terminal/terminal.component.html_0_57 | <div #terminalOutput class="adev-terminal-output"></div>
| {
"end_byte": 57,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/terminal/terminal.component.html"
} |
angular/adev/src/app/editor/preview/preview-error.component.scss_0_695 | :host {
margin: 5% auto;
}
.adev-preview-error {
border: 1px solid var(--senary-contrast);
border-radius: 0.25rem;
padding: 1rem;
p {
display: flex;
gap: 0.5rem;
font-weight: 600;
margin-top: 0;
&::before {
content: 'error';
font-family: var(--icons);
color: var(--orange-red);
font-size: 1.5rem;
font-weight: 500;
}
}
code {
&:not(pre *) {
white-space: pre-wrap;
background: linear-gradient(90deg, var(--hot-red) 0%, var(--orange-red) 100%);
background-clip: text;
-webkit-background-clip: text;
color: transparent;
&::before {
background: transparent;
}
}
}
}
| {
"end_byte": 695,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/preview/preview-error.component.scss"
} |
angular/adev/src/app/editor/preview/preview-error.component.ts_0_884 | /*!
* @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} from '@angular/core';
import {isFirefox, isIos} from '@angular/docs';
import {ErrorType, NodeRuntimeState} from '../node-runtime-state.service';
@Component({
standalone: true,
selector: 'docs-tutorial-preview-error',
templateUrl: './preview-error.component.html',
styleUrls: ['./preview-error.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
})
export class PreviewError {
private readonly nodeRuntimeState = inject(NodeRuntimeState);
readonly isIos = isIos;
readonly isFirefox = isFirefox;
readonly error = this.nodeRuntimeState.error;
readonly ErrorType = ErrorType;
}
| {
"end_byte": 884,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/preview/preview-error.component.ts"
} |
angular/adev/src/app/editor/preview/preview-error.component.html_0_1113 | <div class="adev-preview-error docs-light-mode docs-mini-scroll-track">
@switch (true) {
@case (error()?.type === ErrorType.UNSUPPORTED_BROWSER_ENVIRONMENT) {
@if(isIos) {
<p>Open angular.dev on desktop to code in your browser.</p>
} @else if(isFirefox) {
<p>
We're currently working on supporting Firefox with our development server. Meanwhile, try
running the page using a different browser.
</p>
}
}
@case (error()?.type === ErrorType.COOKIES || error()?.type === ErrorType.UNKNOWN) {
<p>
We couldn't start the tutorial app. Please ensure third party cookies are enabled for this
site.
</p>
}
@case (error()?.type === ErrorType.OUT_OF_MEMORY) {
<p>
We couldn't start the tutorial app because your browser is out of memory. To free up memory,
close angular.dev tutorials in other tabs or windows, and refresh the page.
</p>
}
}
@if (error()?.message) {
<small>
The error message is:
<code>{{ error()!.message }}</code>
</small>
}
</div>
| {
"end_byte": 1113,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/preview/preview-error.component.html"
} |
angular/adev/src/app/editor/preview/preview-error.component.spec.ts_0_639 | /*!
* @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 {PreviewError} from './preview-error.component';
describe('PreviewError', () => {
let fixture: ComponentFixture<PreviewError>;
let component: PreviewError;
beforeEach(() => {
fixture = TestBed.createComponent(PreviewError);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| {
"end_byte": 639,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/preview/preview-error.component.spec.ts"
} |
angular/adev/src/app/editor/preview/preview.component.scss_0_918 | :host {
display: block;
.docs-dark-mode & {
.adev-embedded-editor-preview-container {
background: var(--gray-100);
}
}
// account for tabs height
height: calc(100% - 50px);
// If preview has error, make it scrollable
&:has(.adev-preview-error) {
.adev-embedded-editor-preview-container {
overflow-y: auto;
}
}
}
.adev-embedded-editor-preview-container {
display: flex;
width: 100%;
height: 100%;
position: relative;
color: black;
background: white;
transition: background 0.3s ease;
box-sizing: border-box;
iframe {
width: 100%;
height: 100%;
border: 0;
}
.adev-embedded-editor-preview-loading {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 0.5rem;
position: absolute;
inset: 0;
margin: auto;
width: 100%;
height: 100%;
background: white;
}
}
| {
"end_byte": 918,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/preview/preview.component.scss"
} |
angular/adev/src/app/editor/preview/preview.component.spec.ts_0_4974 | /*!
* @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 {TestBed} from '@angular/core/testing';
import {DebugElement, signal} from '@angular/core';
import {By} from '@angular/platform-browser';
import {of} from 'rxjs';
import {NodeRuntimeSandbox} from '../node-runtime-sandbox.service';
import {Preview} from './preview.component';
import {LoadingStep} from '../enums/loading-steps';
import {NodeRuntimeError, NodeRuntimeState} from '../node-runtime-state.service';
import {PreviewError} from './preview-error.component';
describe('Preview', () => {
// Before each is used as a callable function to prevent conflicts between tests
const beforeEach = () => {
const PREVIEW_URL = 'https://angular.dev/';
const fakeNodeRuntimeSandbox: Partial<NodeRuntimeSandbox> = {
previewUrl$: of(PREVIEW_URL),
};
const fakeNodeRuntimeState = {
loadingStep: signal(LoadingStep.NOT_STARTED),
error: signal<NodeRuntimeError | undefined>(undefined),
};
TestBed.configureTestingModule({
imports: [Preview],
providers: [
{
provide: NodeRuntimeSandbox,
useValue: fakeNodeRuntimeSandbox,
},
{
provide: NodeRuntimeState,
useValue: fakeNodeRuntimeState,
},
],
}).compileComponents();
const fixture = TestBed.createComponent(Preview);
const component = fixture.componentInstance;
const iframeElement = fixture.debugElement.query(By.css('iframe'));
fixture.detectChanges();
return {
fixture,
component,
iframeElement,
PREVIEW_URL,
fakeNodeRuntimeState,
fakeNodeRuntimeSandbox,
getLoadingElementsWrapper: () =>
fixture.debugElement.query(By.css('adev-embedded-editor-preview-loading')),
};
};
it('should set iframe src on init', async () => {
const {component, PREVIEW_URL} = beforeEach();
component.ngAfterViewInit();
await new Promise((resolve) => setTimeout(resolve, 100));
expect(component.previewIframe?.nativeElement).toBeTruthy();
expect(component.previewIframe?.nativeElement?.src).toBe(PREVIEW_URL);
});
it('should not render loading elements if the loadingStep is READY or ERROR', () => {
const {fixture, fakeNodeRuntimeState, getLoadingElementsWrapper} = beforeEach();
fakeNodeRuntimeState.loadingStep.set(LoadingStep.READY);
fixture.detectChanges();
expect(getLoadingElementsWrapper()).toBeNull();
fakeNodeRuntimeState.loadingStep.set(LoadingStep.ERROR);
fixture.detectChanges();
expect(getLoadingElementsWrapper()).toBeNull();
});
it('should render the correct loading element based on loadingStep', () => {
const {fixture, fakeNodeRuntimeState} = beforeEach();
function getDebugElements(): Record<number, DebugElement | null> {
return {
[LoadingStep.NOT_STARTED]: fixture.debugElement.query(
By.css('.adev-embedded-editor-preview-loading-starting'),
),
[LoadingStep.BOOT]: fixture.debugElement.query(
By.css('.adev-embedded-editor-preview-loading-boot'),
),
[LoadingStep.LOAD_FILES]: fixture.debugElement.query(
By.css('.adev-embedded-editor-preview-loading-load-files'),
),
[LoadingStep.INSTALL]: fixture.debugElement.query(
By.css('.adev-embedded-editor-preview-loading-install'),
),
[LoadingStep.START_DEV_SERVER]: fixture.debugElement.query(
By.css('.adev-embedded-editor-preview-loading-start-dev-server'),
),
};
}
for (
let componentLoadingStep = 0;
componentLoadingStep < LoadingStep.READY;
componentLoadingStep++
) {
fakeNodeRuntimeState.loadingStep.set(componentLoadingStep);
fixture.detectChanges();
const loadingElements = getDebugElements();
for (
let elementLoadingStep = 0;
elementLoadingStep < LoadingStep.READY;
elementLoadingStep++
) {
if (elementLoadingStep === componentLoadingStep) {
expect(loadingElements[elementLoadingStep]).toBeDefined();
} else {
expect(loadingElements[elementLoadingStep]).toBeNull();
}
}
}
});
it('should render the error component and hide the iframe and loading element if loadingStep is ERROR', async () => {
const {fixture, fakeNodeRuntimeState, iframeElement, getLoadingElementsWrapper} = beforeEach();
fakeNodeRuntimeState.loadingStep.set(LoadingStep.ERROR);
fakeNodeRuntimeState.error.set({message: 'Error message', type: undefined});
fixture.detectChanges();
await fixture.whenStable();
expect(fixture.debugElement.query(By.directive(PreviewError))).toBeDefined();
expect(getLoadingElementsWrapper()).toBeNull();
expect(iframeElement).toBeNull();
});
});
| {
"end_byte": 4974,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/preview/preview.component.spec.ts"
} |
angular/adev/src/app/editor/preview/preview.component.ts_0_2631 | /*!
* @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 {NgComponentOutlet} from '@angular/common';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
DestroyRef,
ElementRef,
ViewChild,
effect,
inject,
} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {delay, filter, map} from 'rxjs';
import {LoadingStep} from '../enums/loading-steps';
import {NodeRuntimeSandbox} from '../node-runtime-sandbox.service';
import {NodeRuntimeState} from '../node-runtime-state.service';
import type {PreviewError} from './preview-error.component';
type PreviewUrlEmittedValue = {
url: string | null;
previewIframe: ElementRef<HTMLIFrameElement>;
};
@Component({
standalone: true,
selector: 'docs-tutorial-preview',
templateUrl: './preview.component.html',
styleUrls: ['./preview.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [NgComponentOutlet],
})
export class Preview implements AfterViewInit {
@ViewChild('preview') previewIframe: ElementRef<HTMLIFrameElement> | undefined;
private readonly changeDetectorRef = inject(ChangeDetectorRef);
private readonly destroyRef = inject(DestroyRef);
private readonly nodeRuntimeSandbox = inject(NodeRuntimeSandbox);
private readonly nodeRuntimeState = inject(NodeRuntimeState);
loadingProgressValue = this.nodeRuntimeState.loadingStep;
loadingEnum = LoadingStep;
previewErrorComponent: typeof PreviewError | undefined;
constructor() {
effect(async () => {
if (this.nodeRuntimeState.loadingStep() === LoadingStep.ERROR) {
const {PreviewError} = await import('./preview-error.component');
this.previewErrorComponent = PreviewError;
this.changeDetectorRef.markForCheck();
}
});
}
ngAfterViewInit() {
this.nodeRuntimeSandbox.previewUrl$
.pipe(
map((url) => ({url, previewIframe: this.previewIframe})),
filter((value): value is PreviewUrlEmittedValue => !!value.previewIframe),
// Note: The delay is being used here to workaround the flickering issue
// while switching tutorials
delay(100),
takeUntilDestroyed(this.destroyRef),
)
.subscribe(({url, previewIframe}) => {
// Known issue - Binding to the src of an iframe causes the iframe to flicker: https://github.com/angular/angular/issues/16994
previewIframe.nativeElement.src = url ?? '';
});
}
}
| {
"end_byte": 2631,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/preview/preview.component.ts"
} |
angular/adev/src/app/editor/preview/preview.component.html_0_1343 | <div class="adev-embedded-editor-preview-container">
@if (loadingProgressValue() !== loadingEnum.ERROR) {
<iframe
#preview
class="adev-embedded-editor-preview"
allow="cross-origin-isolated"
title="Editor preview"
></iframe>
} @if (previewErrorComponent) {
<ng-container
*ngComponentOutlet="previewErrorComponent"
/>
} @if (loadingProgressValue() < loadingEnum.READY && loadingProgressValue() !== loadingEnum.ERROR)
{
<div class="adev-embedded-editor-preview-loading">
@switch (loadingProgressValue()) { @case (loadingEnum.NOT_STARTED) {
<span class="adev-embedded-editor-preview-loading-starting">Starting</span>
} @case (loadingEnum.BOOT) {
<span class="adev-embedded-editor-preview-loading-boot">Booting</span>
} @case (loadingEnum.LOAD_FILES) {
<span class="adev-embedded-editor-preview-loading-load-files">Creating project</span>
} @case (loadingEnum.INSTALL) {
<span class="adev-embedded-editor-preview-loading-install">Installing packages</span>
} @case (loadingEnum.START_DEV_SERVER) {
<span class="adev-embedded-editor-preview-loading-start-dev-server">
Initializing dev server
</span>
} }
<progress
title="Preview progress"
[value]="loadingProgressValue()"
[max]="loadingEnum.READY"
></progress>
</div>
}
</div>
| {
"end_byte": 1343,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/app/editor/preview/preview.component.html"
} |
angular/adev/src/content/kitchen-sink.md_0_6543 | <docs-decorative-header title="Kitchen sink" imgSrc="assets/images/components.svg"> <!-- markdownlint-disable-line -->
This is a visual list of all custom components and styles for Angular.dev.
</docs-decorative-header>
As a design system, this page contains visual and Markdown authoring guidance for:
* Custom Angular docs elements: [`docs-card`](#cards), [`docs-callout`](#callouts), [`docs-pill`](#pills), and [`docs-steps`](#workflow)
* Custom text elements: [alerts](#alerts)
* Code examples: [`docs-code`](#code)
* Built-in Markdown styled elements: links, lists, [headers](#headers), [horizontal lines](#horizontal-line-divider), [tables](#tables)
* and more!
Get ready to:
1. Write...
2. great...
3. docs!
## Headers (h2)
### Smaller headers (h3)
#### Even smaller (h4)
##### Even more smaller (h5)
###### The smallest! (h6)
## Cards
<docs-card-container>
<docs-card title="What is Angular?" link="Platform Overview" href="tutorials/first-app">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ornare ligula nisi
</docs-card>
<docs-card title="Second Card" link="Try It Now" href="essentials/what-is-angular">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ornare ligula nisi
</docs-card>
<docs-card title="No Link Card">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ornare ligula nisi
</docs-card>
</docs-card-container>
### `<docs-card>` Attributes
| Attributes | Details |
|:--- |:--- |
| `<docs-card-container>` | All cards must be nested inside a container |
| `title` | Card title |
| card body contents | Anything between `<docs-card>` and `</docs-card>` |
| `link` | (Optional) Call to Action link text |
| `href` | (Optional) Call to Action link href |
## Callouts
<docs-callout title="Title of a callout that is helpful">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus metus blandit semper faucibus. Sed blandit diam quis tellus maximus, ac scelerisque ex egestas. Ut euismod lobortis mauris pretium iaculis. Quisque ullamcorper, elit ut lacinia blandit, magna sem finibus urna, vel suscipit tortor dolor id risus.
</docs-callout>
<docs-callout critical title="Title of a callout that is critical">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus metus blandit semper faucibus. Sed blandit diam quis tellus maximus, ac scelerisque ex egestas. Ut euismod lobortis mauris pretium iaculis. Quisque ullamcorper, elit ut lacinia blandit, magna sem finibus urna, vel suscipit tortor dolor id risus.
</docs-callout>
<docs-callout important title="Title of a callout that is important">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla luctus metus blandit semper faucibus. Sed blandit diam quis tellus maximus, ac scelerisque ex egestas. Ut euismod lobortis mauris pretium iaculis. Quisque ullamcorper, elit ut lacinia blandit, magna sem finibus urna, vel suscipit tortor dolor id risus.
</docs-callout>
### `<docs-callout>` Attributes
| Attributes | Details |
|:--- |:--- |
| `title` | Callout title |
| card body contents | Anything between `<docs-callout>` and `</docs-callout>` |
| `helpful` (default) \| `critical` \| `important` | (Optional) Adds styling and icons based on severity level |
## Pills
Pill rows are helpful as a sort of navigation with links to helpful resources.
<docs-pill-row>
<docs-pill href="#pill-row" title="Link"/>
<docs-pill href="#pill-row" title="Link"/>
<docs-pill href="#pill-row" title="Link"/>
<docs-pill href="#pill-row" title="Link"/>
<docs-pill href="#pill-row" title="Link"/>
<docs-pill href="#pill-row" title="Link"/>
</docs-pill-row>
### `<docs-pill>` Attributes
| Attributes | Details |
|:--- |:--- |
| `<docs-pill-row` | All pills must be nested inside a pill row |
| `title` | Pill text |
| `href` | Pill href |
Pills may also be used inline by themselves, but we haven't built that out yet.
## Alerts
Alerts are just special paragraphs. They are helpful to call out (not to be confused with call-out) something that's a bit more urgent. They gain font size from context and are available in many levels. Try not to use alerts to render too much content, but rather to enhance and call attention to surrounding content.
Style alerts starting on a new line in Markdown using the format `SEVERITY_LEVEL` + `:` + `ALERT_TEXT`.
Note: Use Note for ancillary/additional information that's not _essential_ to the main text.
Tip: Use Tip to call out a specific task/action users can perform, or a fact that plays directly into a task/action.
TODO: Use TODO for incomplete documentation that you plan to expand soon. You can also assign the TODO, e.g. TODO(emmatwersky): Text.
QUESTION: Use Question to pose a question to the reader, kind of like a mini-quiz that they should be able to answer.
Summary: Use Summary to provide a two- or three-sentence synopsis of the page or section content, so readers can figure out whether this is the right place for them.
TLDR: Use TL;DR (or TLDR) if you can provide the essential information about a page or section in a sentence or two. For example, TLDR: Rhubarb is a cat.
CRITICAL: Use Critical to call out potential bad stuff or alert the reader they ought to be careful before doing something. For example, Warning: Running `rm` with the `-f` option will delete write-protected files or directories without prompting you.
IMPORTANT: Use Important for information that's crucial to comprehending the text or to completing some task.
HELPFUL: Use Best practice to call out practices that are known to be successful or better than alternatives.
Note: Heads up `developers`! Alerts _can_ have a [link](#alerts) and other nested styles (but try to **use this sparingly**)!.
| {
"end_byte": 6543,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/kitchen-sink.md"
} |
angular/adev/src/content/kitchen-sink.md_6543_14644 | ## Code
You can display `code` using the built in triple backtick:
```ts
example code
```
Or using the `<docs-code>` element.
<docs-code header="Your first example" language="ts" linenums>
import { Component } from '@angular/core';
@Component({
selector: 'example-code',
template: '<h1>Hello World!</h1>',
})
export class ComponentOverviewComponent {}
</docs-code>
### Styling the example
Here's a code example fully styled:
<docs-code
path="hello-world/src/app/app.component-old.ts"
header="A styled code example"
language='ts'
linenums
highlight="[[14,19], 27]"
diff="hello-world/src/app/app.component.ts"
preview
visibleLines="[13,28]">
</docs-code>
We also have styling for the terminal, just set the language as `shell`:
<docs-code language="shell">
npm install @angular/material --save
</docs-code>
#### `<docs-code>` Attributes
| Attributes | Type | Details |
|:--- |:--- |:--- |
| code | `string` | Anything between tags is treated as code |
| `path` | `string` | Path to code example (root: `content/examples/`) |
| `header` | `string` | Title of the example (default: `file-name`) |
| `language` | `string` | code language |
| `linenums` | `boolean` | (False) displays line numbers |
| `highlight` | `string of number[]` | lines highlighted |
| `diff` | `string` | path to changed code |
| `visibleLines` | `string of number[]` | range of lines for collapse mode |
| `visibleRegion` | `string` | **DEPRECATED** FOR `visibleLines` |
| `preview` | `boolean` | (False) display preview |
### Multifile examples
You can create multifile examples by wrapping the examples inside a `<docs-code-multifile>`.
<docs-code-multifile
path="hello-world/src/app/app.component.ts"
preview>
<docs-code
path="hello-world/src/app/app.component-old.ts"
diff="hello-world/src/app/app.component.ts"
visibleLines="[11, [13, 31]]"/>
<docs-code
path="hello-world/src/app/app.component.html"
visibleLines="[1, 2]"
linenums/>
<docs-code
path="hello-world/src/app/app.component.css"
highlight="[2]"/>
</docs-code-multifile>
#### `<docs-code-multifile>` Attributes
| Attributes | Type | Details |
|:--- |:--- |:--- |
| body contents | `string` | nested tabs of `docs-code` examples |
| `path` | `string` | Path to code example for preview and external link |
| `preview` | `boolean` | (False) display preview |
### Adding `preview` to your code example
Adding the `preview` flag builds a running example of the code below the code snippet. This also automatically adds a button to open the running example in Stackblitz.
Note: `preview` only works with standalone.
#### built-in-template-functions
<docs-code-multifile
path="built-in-template-functions/src/app/app.component.ts"
preview>
<docs-code
path="built-in-template-functions/src/app/app.component.ts" linenums/>
<docs-code
path="built-in-template-functions/src/app/app.component.html"
linenums/>
</docs-code-multifile>
#### user-input
<docs-code-multifile
path="user-input/src/app/app.component.ts"
preview>
<docs-code
path="user-input/src/app/app.component.ts" linenums/>
<docs-code
path="user-input/src/app/app.component.html"
visibleLines="[10, 19]"
linenums/>
<docs-code
path="user-input/src/app/click-me.component.ts" linenums/>
<docs-code
path="user-input/src/app/click-me2.component.ts" linenums/>
</docs-code-multifile>
## Workflow
Style numbered steps using `<docs-step>`. Numbering is created using CSS (handy!).
### `<docs-workflow>` and `<docs-step>` Attributes
| Attributes | Details |
|:--- |:--- |
| `<docs-workflow>` | All steps must be nested inside a workflow |
| `title` | Step title |
| step body contents | Anything between `<docs-step>` and `</docs-step>` |
Steps must start on a new line, and can contain `docs-code`s and other nested elements and styles.
<docs-workflow>
<docs-step title="Install the Angular CLI">
You use the Angular CLI to create projects, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment.
To install the Angular CLI, open a terminal window and run the following command:
<docs-code language="shell">
npm install -g @angular/cli
</docs-code>
</docs-step>
<docs-step title="Create a workspace and initial application">
You develop apps in the context of an Angular workspace.
To create a new workspace and initial starter app:
* Run the CLI command `ng new` and provide the name `my-app`, as shown here:
<docs-code language="shell">
ng new my-app
</docs-code>
* The ng new command prompts you for information about features to include in the initial app. Accept the defaults by pressing the Enter or Return key.
The Angular CLI installs the necessary Angular npm packages and other dependencies. This can take a few minutes.
The CLI creates a new workspace and a simple Welcome app, ready to run.
</docs-step>
<docs-step title="Run the application">
The Angular CLI includes a server, for you to build and serve your app locally.
1. Navigate to the workspace folder, such as `my-app`.
2. Run the following command:
<docs-code language="shell">
cd my-app
ng serve --open
</docs-code>
The `ng serve` command launches the server, watches your files, and rebuilds the app as you make changes to those files.
The `--open` (or just `-o`) option automatically opens your browser to <http://localhost:4200/>.
If your installation and setup was successful, you should see a page similar to the following.
</docs-step>
<docs-step title="Final step">
That's all the docs components! Now:
<docs-pill-row>
<docs-pill href="#pill-row" title="Go"/>
<docs-pill href="#pill-row" title="write"/>
<docs-pill href="#pill-row" title="great"/>
<docs-pill href="#pill-row" title="docs!"/>
</docs-pill-row>
</docs-step>
</docs-workflow>
## Images and video
You can add images using the semantic Markdown image:

### Add `#small` and `#medium` to change the image size


Embedded videos are created with `docs-video` and just need a `src` and `alt`:
<docs-video src="https://www.youtube.com/embed/O47uUnJjbJc" alt=""/>
## Charts & Graphs
Write diagrams and charts using [Mermaid](http://mermaid.js.org/) by setting the code language to `mermaid`, all theming is built-in.
```mermaid
graph TD;
A-->B;
A-->C;
B-->D;
C-->D;
```
```mermaid
sequenceDiagram
Alice->>+John: Hello John, how are you?
Alice->>+John: John, can you hear me?
John-->>-Alice: Hi Alice, I can hear you!
John-->>-Alice: I feel great!
```
```mermaid
pie title Pets adopted by volunteers
"Dogs" : 386
"Cats" : 85
"Rats" : 15
```
## Horizontal Line Divider
This can be used to separate page sections, like we're about to do below. These styles will be added by default, nothing custom needed.
<hr/>
The end!
| {
"end_byte": 14644,
"start_byte": 6543,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/kitchen-sink.md"
} |
angular/adev/src/content/error.md_0_168 | # Page Not Found 🙃
If you think this is a mistake, please [open an issue](https://github.com/angular/angular/issues/new?template=3-docs-bug.yaml) so we can fix it.
| {
"end_byte": 168,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/error.md"
} |
angular/adev/src/content/BUILD.bazel_0_198 | load("//adev/shared-docs:index.bzl", "generate_guides")
generate_guides(
name = "content",
srcs = [
"error.md",
],
data = [],
visibility = ["//adev:__subpackages__"],
)
| {
"end_byte": 198,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/BUILD.bazel"
} |
angular/adev/src/content/guide/defer.md_0_5433 | # 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>
}
```
| {
"end_byte": 5433,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/defer.md"
} |
angular/adev/src/content/guide/defer.md_5433_14304 | ## 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.
| {
"end_byte": 14304,
"start_byte": 5433,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/defer.md"
} |
angular/adev/src/content/guide/hydration.md_0_9206 | # 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.
| {
"end_byte": 9206,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/hydration.md"
} |
angular/adev/src/content/guide/hydration.md_9206_12659 | ## Errors
There are several hydration related errors you may encounter ranging from node mismatches to cases when the `ngSkipHydration` was used on an invalid host node. The most common error case that may occur is due to direct DOM manipulation using native APIs that results in hydration being unable to find or match the expected DOM tree structure on the client that was rendered by the server. The other case you may encounter this type of error was mentioned in the [Valid HTML structure](#valid-html-structure) section earlier. So, make sure the HTML in your templates are using valid structure, and you'll avoid that error case.
For a full reference on hydration related errors, visit the [Errors Reference Guide](/errors).
## How to skip hydration for particular components
Some components may not work properly with hydration enabled due to some of the aforementioned issues, like [Direct DOM Manipulation](#direct-dom-manipulation). As a workaround, you can add the `ngSkipHydration` attribute to a component's tag in order to skip hydrating the entire component.
```angular-html
<app-example ngSkipHydration />
```
Alternatively you can set `ngSkipHydration` as a host binding.
```typescript
@Component({
...
host: {ngSkipHydration: 'true'},
})
class ExampleComponent {}
```
The `ngSkipHydration` attribute will force Angular to skip hydrating the entire component and its children. Using this attribute means that the component will behave as if hydration is not enabled, meaning it will destroy and re-render itself.
HELPFUL: This will fix rendering issues, but it means that for this component (and its children), you don't get the benefits of hydration. You will need to adjust your component's implementation to avoid hydration-breaking patterns (i.e. Direct DOM Manipulation) to be able to remove the skip hydration annotation.
The `ngSkipHydration` attribute can only be used on component host nodes. Angular throws an error if this attribute is added to other nodes.
Keep in mind that adding the `ngSkipHydration` attribute to your root application component would effectively disable hydration for your entire application. Be careful and thoughtful about using this attribute. It is intended as a last resort workaround. Components that break hydration should be considered bugs that need to be fixed.
## I18N
HELPFUL: Support for internationalization with hydration is currently in [developer preview](/reference/releases#developer-preview). By default, Angular will skip hydration for components that use i18n blocks, effectively re-rendering those components from scratch.
To enable hydration for i18n blocks, you can add [`withI18nSupport`](/api/platform-browser/withI18nSupport) to your `provideClientHydration` call.
```typescript
import {
bootstrapApplication,
provideClientHydration,
withI18nSupport,
} from '@angular/platform-browser';
...
bootstrapApplication(AppComponent, {
providers: [provideClientHydration(withI18nSupport())]
});
```
## Third Party Libraries with DOM Manipulation
There are a number of third party libraries that depend on DOM manipulation to be able to render. D3 charts is a prime example. These libraries worked without hydration, but they may cause DOM mismatch errors when hydration is enabled. For now, if you encounter DOM mismatch errors using one of these libraries, you can add the `ngSkipHydration` attribute to the component that renders using that library.
| {
"end_byte": 12659,
"start_byte": 9206,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/hydration.md"
} |
angular/adev/src/content/guide/prerendering.md_0_3886 | # 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.
| {
"end_byte": 3886,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/prerendering.md"
} |
angular/adev/src/content/guide/image-optimization.md_0_7202 | # 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 | {
"end_byte": 7202,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/image-optimization.md"
} |
angular/adev/src/content/guide/image-optimization.md_7202_10892 | sing placeholders
### Automatic placeholders
NgOptimizedImage can display an automatic low-resolution placeholder for your image if you're using a CDN or image host that provides automatic image resizing. Take advantage of this feature by adding the `placeholder` attribute to your image:
<docs-code format="typescript" language="angular-html">
<img ngSrc="cat.jpg" width="400" height="200" placeholder>
</docs-code>
Adding this attribute automatically requests a second, smaller version of the image using your specified image loader. This small image will be applied as a `background-image` style with a CSS blur while your image loads. If no image loader is provided, no placeholder image can be generated and an error will be thrown.
The default size for generated placeholders is 30px wide. You can change this size by specifying a pixel value in the `IMAGE_CONFIG` provider, as seen below:
<docs-code format="typescript" language="typescript">
providers: [
{
provide: IMAGE_CONFIG,
useValue: {
placeholderResolution: 40
}
},
],
</docs-code>
If you want sharp edges around your blurred placeholder, you can wrap your image in a containing `<div>` with the `overflow: hidden` style. As long as the `<div>` is the same size as the image (such as by using the `width: fit-content` style), the "fuzzy edges" of the placeholder will be hidden.
### Data URL placeholders
You can also specify a placeholder using a base64 [data URL](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URLs) without an image loader. The data url format is `data:image/[imagetype];[data]`, where `[imagetype]` is the image format, just as `png`, and `[data]` is a base64 encoding of the image. That encoding can be done using the command line or in JavaScript. For specific commands, see [the MDN documentation](https://developer.mozilla.org/docs/Web/HTTP/Basics_of_HTTP/Data_URLs#encoding_data_into_base64_format). An example of a data URL placeholder with truncated data is shown below:
<docs-code language="angular-html">
<img
ngSrc="cat.jpg"
width="400"
height="200"
placeholder=""
/>
</docs-code>
However, large data URLs increase the size of your Angular bundles and slow down page load. If you cannot use an image loader, the Angular team recommends keeping base64 placeholder images smaller than 4KB and using them exclusively on critical images. In addition to decreasing placeholder dimensions, consider changing image formats or parameters used when saving images. At very low resolutions, these parameters can have a large effect on file size.
### Non-blurred placeholders
By default, NgOptimizedImage applies a CSS blur effect to image placeholders. To render a placeholder without blur, provide a `placeholderConfig` argument with an object that includes the `blur` property, set to false. For example:
<docs-code language="angular-html">
<img
ngSrc="cat.jpg"
width="400"
height="200"
placeholder
[placeholderConfig]="{blur: false}"
/>
</docs-code>
## Adjusting image styling
Depending on the image's styling, adding `width` and `height` attributes may cause the image to render differently. `NgOptimizedImage` warns you if your image styling renders the image at a distorted aspect ratio.
You can typically fix this by adding `height: auto` or `width: auto` to your image styles. For more information, see the [web.dev article on the `<img>` tag](https://web.dev/patterns/web-vitals-patterns/images/img-tag).
If the `width` and `height` attribute on the image are preventing you from sizing the image the way you want with CSS, consider using `fill` mode instead, and styling the image's parent element.
## P | {
"end_byte": 10892,
"start_byte": 7202,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/image-optimization.md"
} |
angular/adev/src/content/guide/image-optimization.md_10892_17057 | erformance Features
NgOptimizedImage includes a number of features designed to improve loading performance in your app. These features are described in this section.
### Add resource hints
A [`preconnect` resource hint](https://web.dev/preconnect-and-dns-prefetch) for your image origin ensures that the LCP image loads as quickly as possible.
Preconnect links are automatically generated for domains provided as an argument to a [loader](#optional-set-up-a-loader). If an image origin cannot be automatically identified, and no preconnect link is detected for the LCP image, `NgOptimizedImage` will warn during development. In that case, you should manually add a resource hint to `index.html`. Within the `<head>` of the document, add a `link` tag with `rel="preconnect"`, as shown below:
<docs-code language="html">
<link rel="preconnect" href="https://my.cdn.origin" />
</docs-code>
To disable preconnect warnings, inject the `PRECONNECT_CHECK_BLOCKLIST` token:
<docs-code language="typescript">
providers: [
{provide: PRECONNECT_CHECK_BLOCKLIST, useValue: 'https://your-domain.com'}
],
</docs-code>
See more information on automatic preconnect generation [here](#why-is-a-preconnect-element-not-being-generated-for-my-image-domain).
### Request images at the correct size with automatic `srcset`
Defining a [`srcset` attribute](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/srcset) ensures that the browser requests an image at the right size for your user's viewport, so it doesn't waste time downloading an image that's too large. `NgOptimizedImage` generates an appropriate `srcset` for the image, based on the presence and value of the [`sizes` attribute](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/sizes) on the image tag.
#### Fixed-size images
If your image should be "fixed" in size (i.e. the same size across devices, except for [pixel density](https://web.dev/codelab-density-descriptors/)), there is no need to set a `sizes` attribute. A `srcset` can be generated automatically from the image's width and height attributes with no further input required.
Example srcset generated:
```angular-html
<img ... srcset="image-400w.jpg 1x, image-800w.jpg 2x">
```
#### Responsive images
If your image should be responsive (i.e. grow and shrink according to viewport size), then you will need to define a [`sizes` attribute](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/sizes) to generate the `srcset`.
If you haven't used `sizes` before, a good place to start is to set it based on viewport width. For example, if your CSS causes the image to fill 100% of viewport width, set `sizes` to `100vw` and the browser will select the image in the `srcset` that is closest to the viewport width (after accounting for pixel density). If your image is only likely to take up half the screen (ex: in a sidebar), set `sizes` to `50vw` to ensure the browser selects a smaller image. And so on.
If you find that the above does not cover your desired image behavior, see the documentation on [advanced sizes values](#advanced-sizes-values).
Note that `NgOptimizedImage` automatically prepends `"auto"` to the provided `sizes` value. This is an optimization that increases the accuracy of srcset selection on browsers which support `sizes="auto"`, and is ignored by browsers which do not.
By default, the responsive breakpoints are:
`[16, 32, 48, 64, 96, 128, 256, 384, 640, 750, 828, 1080, 1200, 1920, 2048, 3840]`
If you would like to customize these breakpoints, you can do so using the `IMAGE_CONFIG` provider:
<docs-code language="typescript">
providers: [
{
provide: IMAGE_CONFIG,
useValue: {
breakpoints: [16, 48, 96, 128, 384, 640, 750, 828, 1080, 1200, 1920]
}
},
],
</docs-code>
If you would like to manually define a `srcset` attribute, you can provide your own using the `ngSrcset` attribute:
<docs-code language="angular-html">
<img ngSrc="hero.jpg" ngSrcset="100w, 200w, 300w">
</docs-code>
If the `ngSrcset` attribute is present, `NgOptimizedImage` generates and sets the `srcset` based on the sizes included. Do not include image file names in `ngSrcset` - the directive infers this information from `ngSrc`. The directive supports both width descriptors (e.g. `100w`) and density descriptors (e.g. `1x`).
<docs-code language="angular-html">
<img ngSrc="hero.jpg" ngSrcset="100w, 200w, 300w" sizes="50vw">
</docs-code>
### Disabling automatic srcset generation
To disable srcset generation for a single image, you can add the `disableOptimizedSrcset` attribute on the image:
<docs-code language="angular-html">
<img ngSrc="about.jpg" disableOptimizedSrcset>
</docs-code>
### Disabling image lazy loading
By default, `NgOptimizedImage` sets `loading=lazy` for all images that are not marked `priority`. You can disable this behavior for non-priority images by setting the `loading` attribute. This attribute accepts values: `eager`, `auto`, and `lazy`. [See the documentation for the standard image `loading` attribute for details](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/loading#value).
<docs-code language="angular-html">
<img ngSrc="cat.jpg" width="400" height="200" loading="eager">
</docs-code>
### Advanced 'sizes' values
You may want to have images displayed at varying widths on differently-sized screens. A common example of this pattern is a grid- or column-based layout that renders a single column on mobile devices, and two columns on larger devices. You can capture this behavior in the `sizes` attribute, using a "media query" syntax, such as the following:
<docs-code language="angular-html">
<img ngSrc="cat.jpg" width="400" height="200" sizes="(max-width: 768px) 100vw, 50vw">
</docs-code>
The `sizes` attribute in the above example says "I expect this image to be 100 percent of the screen width on devices under 768px wide. Otherwise, I expect it to be 50 percent of the screen width.
For additional information about the `sizes` attribute, see [web.dev](https://web.dev/learn/design/responsive-images/#sizes) or [mdn](https://developer.mozilla.org/docs/Web/API/HTMLImageElement/sizes).
## C | {
"end_byte": 17057,
"start_byte": 10892,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/image-optimization.md"
} |
angular/adev/src/content/guide/image-optimization.md_17057_25896 | onfiguring an image loader for `NgOptimizedImage`
A "loader" is a function that generates an [image transformation URL](https://web.dev/image-cdns/#how-image-cdns-use-urls-to-indicate-optimization-options) for a given image file. When appropriate, `NgOptimizedImage` sets the size, format, and image quality transformations for an image.
`NgOptimizedImage` provides both a generic loader that applies no transformations, as well as loaders for various third-party image services. It also supports writing your own custom loader.
| Loader type| Behavior |
|:--- |:--- |
| Generic loader | The URL returned by the generic loader will always match the value of `src`. In other words, this loader applies no transformations. Sites that use Angular to serve images are the primary intended use case for this loader.|
| Loaders for third-party image services | The URL returned by the loaders for third-party image services will follow API conventions used by that particular image service. |
| Custom loaders | A custom loader's behavior is defined by its developer. You should use a custom loader if your image service isn't supported by the loaders that come preconfigured with `NgOptimizedImage`.|
Based on the image services commonly used with Angular applications, `NgOptimizedImage` provides loaders preconfigured to work with the following image services:
| Image Service | Angular API | Documentation |
|:--- |:--- |:--- |
| Cloudflare Image Resizing | `provideCloudflareLoader` | [Documentation](https://developers.cloudflare.com/images/image-resizing/) |
| Cloudinary | `provideCloudinaryLoader` | [Documentation](https://cloudinary.com/documentation/resizing_and_cropping) |
| ImageKit | `provideImageKitLoader` | [Documentation](https://docs.imagekit.io/) |
| Imgix | `provideImgixLoader` | [Documentation](https://docs.imgix.com/) |
| Netlify | `provideNetlifyLoader` | [Documentation](https://docs.netlify.com/image-cdn/overview/) |
To use the **generic loader** no additional code changes are necessary. This is the default behavior.
### Built-in Loaders
To use an existing loader for a **third-party image service**, add the provider factory for your chosen service to the `providers` array. In the example below, the Imgix loader is used:
<docs-code language="typescript">
providers: [
provideImgixLoader('https://my.base.url/'),
],
</docs-code>
The base URL for your image assets should be passed to the provider factory as an argument. For most sites, this base URL should match one of the following patterns:
* <https://yoursite.yourcdn.com>
* <https://subdomain.yoursite.com>
* <https://subdomain.yourcdn.com/yoursite>
You can learn more about the base URL structure in the docs of a corresponding CDN provider.
### Custom Loaders
To use a **custom loader**, provide your loader function as a value for the `IMAGE_LOADER` DI token. In the example below, the custom loader function returns a URL starting with `https://example.com` that includes `src` and `width` as URL parameters.
<docs-code language="typescript">
providers: [
{
provide: IMAGE_LOADER,
useValue: (config: ImageLoaderConfig) => {
return `https://example.com/images?src=${config.src}&width=${config.width}`;
},
},
],
</docs-code>
A loader function for the `NgOptimizedImage` directive takes an object with the `ImageLoaderConfig` type (from `@angular/common`) as its argument and returns the absolute URL of the image asset. The `ImageLoaderConfig` object contains the `src` property, and optional `width` and `loaderParams` properties.
Note: even though the `width` property may not always be present, a custom loader must use it to support requesting images at various widths in order for `ngSrcset` to work properly.
### The `loaderParams` Property
There is an additional attribute supported by the `NgOptimizedImage` directive, called `loaderParams`, which is specifically designed to support the use of custom loaders. The `loaderParams` attribute takes an object with any properties as a value, and does not do anything on its own. The data in `loaderParams` is added to the `ImageLoaderConfig` object passed to your custom loader, and can be used to control the behavior of the loader.
A common use for `loaderParams` is controlling advanced image CDN features.
### Example custom loader
The following shows an example of a custom loader function. This example function concatenates `src` and `width`, and uses `loaderParams` to control a custom CDN feature for rounded corners:
<docs-code language="typescript">
const myCustomLoader = (config: ImageLoaderConfig) => {
let url = `https://example.com/images/${config.src}?`;
let queryParams = [];
if (config.width) {
queryParams.push(`w=${config.width}`);
}
if (config.loaderParams?.roundedCorners) {
queryParams.push('mask=corners&corner-radius=5');
}
return url + queryParams.join('&');
};
</docs-code>
Note that in the above example, we've invented the 'roundedCorners' property name to control a feature of our custom loader. We could then use this feature when creating an image, as follows:
<docs-code language="angular-html">
<img ngSrc="profile.jpg" width="300" height="300" [loaderParams]="{roundedCorners: true}">
</docs-code>
## Frequently Asked Questions
### Does NgOptimizedImage support the `background-image` css property?
The NgOptimizedImage does not directly support the `background-image` css property, but it is designed to easily accommodate the use case of having an image as the background of another element.
For a step-by-step process for migration from `background-image` to `NgOptimizedImage`, see the [How to migrate your background image](#how-to-migrate-your-background-image) section above.
### Why can't I use `src` with `NgOptimizedImage`?
The `ngSrc` attribute was chosen as the trigger for NgOptimizedImage due to technical considerations around how images are loaded by the browser. NgOptimizedImage makes programmatic changes to the `loading` attribute -- if the browser sees the `src` attribute before those changes are made, it will begin eagerly downloading the image file, and the loading changes will be ignored.
### Why is a preconnect element not being generated for my image domain?
Preconnect generation is performed based on static analysis of your application. That means that the image domain must be directly included in the loader parameter, as in the following example:
<docs-code language="typescript">
providers: [
provideImgixLoader('https://my.base.url/'),
],
</docs-code>
If you use a variable to pass the domain string to the loader, or you're not using a loader, the static analysis will not be able to identify the domain, and no preconnect link will be generated. In this case you should manually add a preconnect link to the document head, as [described above](#add-resource-hints).
### Can I use two different image domains in the same page?
The [image loaders](#configuring-an-image-loader-for-ngoptimizedimage) provider pattern is designed to be as simple as possible for the common use case of having only a single image CDN used within a component. However, it's still very possible to manage multiple image CDNs using a single provider.
To do this, we recommend writing a [custom image loader](#custom-loaders) which uses the [`loaderParams` property](#the-loaderparams-property) to pass a flag that specifies which image CDN should be used, and then invokes the appropriate loader based on that flag.
### Can you add a new built-in loader for my preferred CDN?
For maintenance reasons, we don't currently plan to support additional built-in loaders in the Angular repository. Instead, we encourage developers to publish any additional image loaders as third-party packages.
### Can I use this with the `<picture>` tag
No, but this is on our roadmap, so stay tuned.
If you're waiting on this feature, please upvote the Github issue [here](https://github.com/angular/angular/issues/56594).
### How do I find my LCP image with Chrome DevTools?
1. Using the performance tab of the Chrome DevTools, click on the "start profiling and reload page" button on the top left. It looks like a page refresh icon.
2. This will trigger a profiling snapshot of your Angular application.
3. Once the profiling result is available, select "LCP" in the timings section.
4. A summary entry should appear in the panel at the bottom. You can find the LCP element in the row for "related node". Clicking on it will reveal the element in the Elements panel.
<img alt="LCP in the Chrome DevTools" src="assets/images/guide/image-optimization/devtools-lcp.png">
NOTE: This only identifies the LCP element within the viewport of the page you are testing. It is also recommended to use mobile emulation to identify the LCP element for smaller screens.
| {
"end_byte": 25896,
"start_byte": 17057,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/image-optimization.md"
} |
angular/adev/src/content/guide/ssr.md_0_7166 | # 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.
| {
"end_byte": 7166,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ssr.md"
} |
angular/adev/src/content/guide/BUILD.bazel_0_827 | load("//adev/shared-docs:index.bzl", "generate_guides")
generate_guides(
name = "guide",
srcs = glob([
"*.md",
]),
data = [
"//adev/src/content/examples/elements:src/app/app.component.ts",
"//adev/src/content/examples/elements:src/app/popup.component.ts",
"//adev/src/content/examples/elements:src/app/popup.service.ts",
"//adev/src/content/examples/security:src/app/bypass-security.component.html",
"//adev/src/content/examples/security:src/app/bypass-security.component.ts",
"//adev/src/content/examples/security:src/app/inner-html-binding.component.html",
"//adev/src/content/examples/security:src/app/inner-html-binding.component.ts",
"//adev/src/content/examples/ssr:server.ts",
],
visibility = ["//adev:__subpackages__"],
)
| {
"end_byte": 827,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/BUILD.bazel"
} |
angular/adev/src/content/guide/elements.md_0_7626 | # Angular elements overview
_Angular elements_ are Angular components packaged as _custom elements_ \(also called Web Components\), a web standard for defining new HTML elements in a framework-agnostic way.
[Custom elements](https://developer.mozilla.org/docs/Web/Web_Components/Using_custom_elements) are a Web Platform feature available on all browsers supported by Angular.
A custom element extends HTML by allowing you to define a tag whose content is created and controlled by JavaScript code.
The browser maintains a `CustomElementRegistry` of defined custom elements, which maps an instantiable JavaScript class to an HTML tag.
The `@angular/elements` package exports a `createCustomElement()` API that provides a bridge from Angular's component interface and change detection functionality to the built-in DOM API.
Transforming a component to a custom element makes all the required Angular infrastructure available to the browser.
Creating a custom element is simple and straightforward, and automatically connects your component-defined view with change detection and data binding, mapping Angular functionality to the corresponding built-in HTML equivalents.
## Using custom elements
Custom elements bootstrap themselves - they start when they are added to the DOM, and are destroyed when removed from the DOM.
Once a custom element is added to the DOM for any page, it looks and behaves like any other HTML element, and does not require any special knowledge of Angular terms or usage conventions.
To add the `@angular/elements` package to your workspace, run the following command:
<docs-code language="shell">
npm install @angular/elements --save
</docs-code>
### How it works
The `createCustomElement()` function converts a component into a class that can be registered with the browser as a custom element.
After you register your configured class with the browser's custom-element registry, use the new element just like a built-in HTML element in content that you add directly into the DOM:
<docs-code language="html">
<my-popup message="Use Angular!"></my-popup>
</docs-code>
When your custom element is placed on a page, the browser creates an instance of the registered class and adds it to the DOM.
The content is provided by the component's template, which uses Angular template syntax, and is rendered using the component and DOM data.
Input properties in the component correspond to input attributes for the element.
## Transforming components to custom elements
Angular provides the `createCustomElement()` function for converting an Angular component, together with its dependencies, to a custom element.
The conversion process implements the `NgElementConstructor` interface, and creates a
constructor class that is configured to produce a self-bootstrapping instance of your component.
Use the browser's native [`customElements.define()`](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry/define) function to register the configured constructor and its associated custom-element tag with the browser's [`CustomElementRegistry`](https://developer.mozilla.org/docs/Web/API/CustomElementRegistry).
When the browser encounters the tag for the registered element, it uses the constructor to create a custom-element instance.
IMPORTANT: Avoid using the component's selector as the custom element tag name.
This can lead to unexpected behavior, due to Angular creating two component instances for a single DOM element:
One regular Angular component and a second one using the custom element.
### Mapping
A custom element _hosts_ an Angular component, providing a bridge between the data and logic defined in the component and standard DOM APIs.
Component properties and logic maps directly into HTML attributes and the browser's event system.
* The creation API parses the component looking for input properties, and defines corresponding attributes for the custom element.
It transforms the property names to make them compatible with custom elements, which do not recognize case distinctions.
The resulting attribute names use dash-separated lowercase.
For example, for a component with `@Input('myInputProp') inputProp`, the corresponding custom element defines an attribute `my-input-prop`.
* Component outputs are dispatched as HTML [Custom Events](https://developer.mozilla.org/docs/Web/API/CustomEvent), with the name of the custom event matching the output name.
For example, for a component with `@Output() valueChanged = new EventEmitter()`, the corresponding custom element dispatches events with the name "valueChanged", and the emitted data is stored on the event's `detail` property.
If you provide an alias, that value is used; for example, `@Output('myClick') clicks = new EventEmitter<string>();` results in dispatch events with the name "myClick".
For more information, see Web Component documentation for [Creating custom events](https://developer.mozilla.org/docs/Web/Guide/Events/Creating_and_triggering_events#Creating_custom_events).
## Example: A Popup Service
Previously, when you wanted to add a component to an application at runtime, you had to define a _dynamic component_, and then you would have to load it, attach it to an element in the DOM, and wire up all of the dependencies, change detection, and event handling.
Using an Angular custom element makes the process simpler and more transparent, by providing all the infrastructure and framework automatically —all you have to do is define the kind of event handling you want.
\(You do still have to exclude the component from compilation, if you are not going to use it in your application.\)
The following Popup Service example application defines a component that you can either load dynamically or convert to a custom element.
| Files | Details |
| :------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `popup.component.ts` | Defines a simple pop-up element that displays an input message, with some animation and styling. |
| `popup.service.ts` | Creates an injectable service that provides two different ways to invoke the `PopupComponent`; as a dynamic component, or as a custom element. Notice how much more setup is required for the dynamic-loading method. | |
| `app.component.ts` | Defines the application's root component, which uses the `PopupService` to add the pop-up to the DOM at run time. When the application runs, the root component's constructor converts `PopupComponent` to a custom element. |
For comparison, the demo shows both methods.
One button adds the popup using the dynamic-loading method, and the other uses the custom element.
The result is the same, but the preparation is different.
<docs-code-multifile>
<docs-code header="popup.component.ts" path="adev/src/content/examples/elements/src/app/popup.component.ts"/>
<docs-code header="popup.service.ts" path="adev/src/content/examples/elements/src/app/popup.service.ts"/>
<docs-code header="app.component.ts" path="adev/src/content/examples/elements/src/app/app.component.ts"/>
</docs-code-multifile>
## | {
"end_byte": 7626,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/elements.md"
} |
angular/adev/src/content/guide/elements.md_7626_10776 | Typings for custom elements
Generic DOM APIs, such as `document.createElement()` or `document.querySelector()`, return an element type that is appropriate for the specified arguments.
For example, calling `document.createElement('a')` returns an `HTMLAnchorElement`, which TypeScript knows has an `href` property.
Similarly, `document.createElement('div')` returns an `HTMLDivElement`, which TypeScript knows has no `href` property.
When called with unknown elements, such as a custom element name \(`popup-element` in our example\), the methods return a generic type, such as `HTMLElement`, because TypeScript can't infer the correct type of the returned element.
Custom elements created with Angular extend `NgElement` \(which in turn extends `HTMLElement`\).
Additionally, these custom elements will have a property for each input of the corresponding component.
For example, our `popup-element` has a `message` property of type `string`.
There are a few options if you want to get correct types for your custom elements.
Assume you create a `my-dialog` custom element based on the following component:
<docs-code language="typescript">
@Component(…)
class MyDialog {
@Input() content: string;
}
</docs-code>
The most straightforward way to get accurate typings is to cast the return value of the relevant DOM methods to the correct type.
For that, use the `NgElement` and `WithProperties` types \(both exported from `@angular/elements`\):
<docs-code language="typescript">
const aDialog = document.createElement('my-dialog') as NgElement & WithProperties<{content: string}>;
aDialog.content = 'Hello, world!';
aDialog.content = 123; // <-- ERROR: TypeScript knows this should be a string.
aDialog.body = 'News'; // <-- ERROR: TypeScript knows there is no `body` property on `aDialog`.
</docs-code>
This is a good way to quickly get TypeScript features, such as type checking and autocomplete support, for your custom element.
But it can get cumbersome if you need it in several places, because you have to cast the return type on every occurrence.
An alternative way, that only requires defining each custom element's type once, is augmenting the `HTMLElementTagNameMap`, which TypeScript uses to infer the type of a returned element based on its tag name \(for DOM methods such as `document.createElement()`, `document.querySelector()`, etc.\):
<docs-code language="typescript">
declare global {
interface HTMLElementTagNameMap {
'my-dialog': NgElement & WithProperties<{content: string}>;
'my-other-element': NgElement & WithProperties<{foo: 'bar'}>;
…
}
}
</docs-code>
Now, TypeScript can infer the correct type the same way it does for built-in elements:
<docs-code language="typescript">
document.createElement('div') //--> HTMLDivElement (built-in element)
document.querySelector('foo') //--> Element (unknown element)
document.createElement('my-dialog') //--> NgElement & WithProperties<{content: string}> (custom element)
document.querySelector('my-other-element') //--> NgElement & WithProperties<{foo: 'bar'}> (custom element)
</docs-code>
| {
"end_byte": 10776,
"start_byte": 7626,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/elements.md"
} |
angular/adev/src/content/guide/security.md_0_1872 | # Security
This topic describes Angular's built-in protections against common web-application vulnerabilities and attacks such as cross-site scripting attacks.
It doesn't cover application-level security, such as authentication and authorization.
For more information about the attacks and mitigations described below, see the [Open Web Application Security Project (OWASP) Guide](https://www.owasp.org/index.php/Category:OWASP_Guide_Project).
<a id="report-issues"></a>
<docs-callout title="Reporting vulnerabilities">
Angular is part of Google [Open Source Software Vulnerability Reward Program](https://bughunters.google.com/about/rules/6521337925468160/google-open-source-software-vulnerability-reward-program-rules). [For vulnerabilities in Angular, please submit your report at https://bughunters.google.com](https://bughunters.google.com/report).
For more information about how Google handles security issues, see [Google's security philosophy](https://www.google.com/about/appsecurity).
</docs-callout>
## Best practices
These are some best practices to ensure that your Angular application is secure.
1. **Keep current with the latest Angular library releases** - The Angular libraries get regular updates, and these updates might fix security defects discovered in previous versions. Check the Angular [change log](https://github.com/angular/angular/blob/main/CHANGELOG.md) for security-related updates.
2. **Don't alter your copy of Angular** - Private, customized versions of Angular tend to fall behind the current version and might not include important security fixes and enhancements. Instead, share your Angular improvements with the community and make a pull request.
3. **Avoid Angular APIs marked in the documentation as "_Security Risk_"** - For more information, see the [Trusting safe values](#trusting-safe-values) section of this page.
| {
"end_byte": 1872,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/security.md"
} |
angular/adev/src/content/guide/security.md_1872_10120 | ## Preventing cross-site scripting (XSS)
[Cross-site scripting (XSS)](https://en.wikipedia.org/wiki/Cross-site_scripting) enables attackers to inject malicious code into web pages.
Such code can then, for example, steal user and login data, or perform actions that impersonate the user.
This is one of the most common attacks on the web.
To block XSS attacks, you must prevent malicious code from entering the Document Object Model (DOM).
For example, if attackers can trick you into inserting a `<script>` tag in the DOM, they can run arbitrary code on your website.
The attack isn't limited to `<script>` tags —many elements and properties in the DOM allow code execution, for example, `<img alt="" onerror="...">` and `<a href="javascript:...">`.
If attacker-controlled data enters the DOM, expect security vulnerabilities.
### Angular's cross-site scripting security model
To systematically block XSS bugs, Angular treats all values as untrusted by default.
When a value is inserted into the DOM from a template binding, or interpolation, Angular sanitizes and escapes untrusted values.
If a value was already sanitized outside of Angular and is considered safe, communicate this to Angular by marking the [value as trusted](#trusting-safe-values).
Unlike values to be used for rendering, Angular templates are considered trusted by default, and should be treated as executable code.
Never create templates by concatenating user input and template syntax.
Doing this would enable attackers to [inject arbitrary code](https://en.wikipedia.org/wiki/Code_injection) into your application.
To prevent these vulnerabilities, always use the default [Ahead-Of-Time (AOT) template compiler](#use-the-aot-template-compiler) in production deployments.
An extra layer of protection can be provided through the use of Content security policy and Trusted Types.
These web platform features operate at the DOM level which is the most effective place to prevent XSS issues. Here they can't be bypassed using other, lower-level APIs.
For this reason, it is strongly encouraged to take advantage of these features. To do this, configure the [content security policy](#content-security-policy) for the application and enable [trusted types enforcement](#enforcing-trusted-types).
### Sanitization and security contexts
*Sanitization* is the inspection of an untrusted value, turning it into a value that's safe to insert into the DOM.
In many cases, sanitization doesn't change a value at all.
Sanitization depends on context:
A value that's harmless in CSS is potentially dangerous in a URL.
Angular defines the following security contexts:
| Security contexts | Details |
| :---------------- | :-------------------------------------------------------------------------------- |
| HTML | Used when interpreting a value as HTML, for example, when binding to `innerHtml`. |
| Style | Used when binding CSS into the `style` property. |
| URL | Used for URL properties, such as `<a href>`. |
| Resource URL | A URL that is loaded and executed as code, for example, in `<script src>`. |
Angular sanitizes untrusted values for HTML and URLs. Sanitizing resource URLs isn't possible because they contain arbitrary code.
In development mode, Angular prints a console warning when it has to change a value during sanitization.
### Sanitization example
The following template binds the value of `htmlSnippet`. Once by interpolating it into an element's content, and once by binding it to the `innerHTML` property of an element:
<docs-code header="src/app/inner-html-binding.component.html" path="adev/src/content/examples/security/src/app/inner-html-binding.component.html"/>
Interpolated content is always escaped —the HTML isn't interpreted and the browser displays angle brackets in the element's text content.
For the HTML to be interpreted, bind it to an HTML property such as `innerHTML`.
Be aware that binding a value that an attacker might control into `innerHTML` normally causes an XSS vulnerability.
For example, one could run JavaScript in a following way:
<docs-code header="src/app/inner-html-binding.component.ts (class)" path="adev/src/content/examples/security/src/app/inner-html-binding.component.ts" visibleRegion="class"/>
Angular recognizes the value as unsafe and automatically sanitizes it, which removes the `script` element but keeps safe content such as the `<b>` element.
<img alt="A screenshot showing interpolated and bound HTML values" src="assets/images/guide/security/binding-inner-html.png#small">
### Direct use of the DOM APIs and explicit sanitization calls
Unless you enforce Trusted Types, the built-in browser DOM APIs don't automatically protect you from security vulnerabilities.
For example, `document`, the node available through `ElementRef`, and many third-party APIs contain unsafe methods.
Likewise, if you interact with other libraries that manipulate the DOM, you likely won't have the same automatic sanitization as with Angular interpolations.
Avoid directly interacting with the DOM and instead use Angular templates where possible.
For cases where this is unavoidable, use the built-in Angular sanitization functions.
Sanitize untrusted values with the [DomSanitizer.sanitize](api/platform-browser/DomSanitizer#sanitize) method and the appropriate `SecurityContext`.
That function also accepts values that were marked as trusted using the `bypassSecurityTrust` … functions, and does not sanitize them, as [described below](#trusting-safe-values).
### Trusting safe values
Sometimes applications genuinely need to include executable code, display an `<iframe>` from some URL, or construct potentially dangerous URLs.
To prevent automatic sanitization in these situations, tell Angular that you inspected a value, checked how it was created, and made sure it is secure.
Do _be careful_.
If you trust a value that might be malicious, you are introducing a security vulnerability into your application.
If in doubt, find a professional security reviewer.
To mark a value as trusted, inject `DomSanitizer` and call one of the following methods:
* `bypassSecurityTrustHtml`
* `bypassSecurityTrustScript`
* `bypassSecurityTrustStyle`
* `bypassSecurityTrustUrl`
* `bypassSecurityTrustResourceUrl`
Remember, whether a value is safe depends on context, so choose the right context for your intended use of the value.
Imagine that the following template needs to bind a URL to a `javascript:alert(...)` call:
<docs-code header="src/app/bypass-security.component.html (URL)" path="adev/src/content/examples/security/src/app/bypass-security.component.html" visibleRegion="URL"/>
Normally, Angular automatically sanitizes the URL, disables the dangerous code, and in development mode, logs this action to the console.
To prevent this, mark the URL value as a trusted URL using the `bypassSecurityTrustUrl` call:
<docs-code header="src/app/bypass-security.component.ts (trust-url)" path="adev/src/content/examples/security/src/app/bypass-security.component.ts" visibleRegion="trust-url"/>
<img alt="A screenshot showing an alert box created from a trusted URL" src="assets/images/guide/security/bypass-security-component.png#medium">
If you need to convert user input into a trusted value, use a component method.
The following template lets users enter a YouTube video ID and load the corresponding video in an `<iframe>`.
The `<iframe src>` attribute is a resource URL security context, because an untrusted source can, for example, smuggle in file downloads that unsuspecting users could run.
To prevent this, call a method on the component to construct a trusted video URL, which causes Angular to let binding into `<iframe src>`:
<docs-code header="src/app/bypass-security.component.html (iframe)" path="adev/src/content/examples/security/src/app/bypass-security.component.html" visibleRegion="iframe"/>
<docs-code header="src/app/bypass-security.component.ts (trust-video-url)" path="adev/src/content/examples/security/src/app/bypass-security.component.ts" visibleRegion="trust-video-url"/>
### Co | {
"end_byte": 10120,
"start_byte": 1872,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/security.md"
} |
angular/adev/src/content/guide/security.md_10120_19973 | ntent security policy
Content Security Policy \(CSP\) is a defense-in-depth technique to prevent XSS.
To enable CSP, configure your web server to return an appropriate `Content-Security-Policy` HTTP header.
Read more about content security policy at the [Web Fundamentals guide](https://developers.google.com/web/fundamentals/security/csp) on the Google Developers website.
The minimal policy required for a brand-new Angular application is:
<docs-code language="text">
default-src 'self'; style-src 'self' 'nonce-randomNonceGoesHere'; script-src 'self' 'nonce-randomNonceGoesHere';
</docs-code>
When serving your Angular application, the server should include a randomly-generated nonce in the HTTP header for each request.
You must provide this nonce to Angular so that the framework can render `<style>` elements.
You can set the nonce for Angular in one of two ways:
1. Set the `ngCspNonce` attribute on the root application element as `<app ngCspNonce="randomNonceGoesHere"></app>`. Use this approach if you have access to server-side templating that can add the nonce both to the header and the `index.html` when constructing the response.
2. Provide the nonce using the `CSP_NONCE` injection token. Use this approach if you have access to the nonce at runtime and you want to be able to cache the `index.html`.
<docs-code language="typescript">
import {bootstrapApplication, CSP_NONCE} from '@angular/core';
import {AppComponent} from './app/app.component';
bootstrapApplication(AppComponent, {
providers: [{
provide: CSP_NONCE,
useValue: globalThis.myRandomNonceValue
}]
});
</docs-code>
<docs-callout title="Unique nonces">
Always ensure that the nonces you provide are <strong>unique per request</strong> and that they are not predictable or guessable.
If an attacker can predict future nonces, they can circumvent the protections offered by CSP.
</docs-callout>
If you cannot generate nonces in your project, you can allow inline styles by adding `'unsafe-inline'` to the `style-src` section of the CSP header.
| Sections | Details |
| :----------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `default-src 'self';` | Allows the page to load all its required resources from the same origin. |
| `style-src 'self' 'nonce-randomNonceGoesHere';` | Allows the page to load global styles from the same origin \(`'self'`\) and styles inserted by Angular with the `nonce-randomNonceGoesHere`. |
| `script-src 'self' 'nonce-randomNonceGoesHere';` | Allows the page to load JavaScript from the same origin \(`'self'`\) and scripts inserted by the Angular CLI with the `nonce-randomNonceGoesHere`. This is only required if you're using critical CSS inlining. |
Angular itself requires only these settings to function correctly.
As your project grows, you may need to expand your CSP settings to accommodate extra features specific to your application.
### Enforcing Trusted Types
It is recommended that you use [Trusted Types](https://w3c.github.io/trusted-types/dist/spec/) as a way to help secure your applications from cross-site scripting attacks.
Trusted Types is a [web platform](https://en.wikipedia.org/wiki/Web_platform) feature that can help you prevent cross-site scripting attacks by enforcing safer coding practices.
Trusted Types can also help simplify the auditing of application code.
<docs-callout title="Trusted types">
Trusted Types might not yet be available in all browsers your application targets.
In the case your Trusted-Types-enabled application runs in a browser that doesn't support Trusted Types, the features of the application are preserved. Your application is guarded against XSS by way of Angular's DomSanitizer.
See [caniuse.com/trusted-types](https://caniuse.com/trusted-types) for the current browser support.
</docs-callout>
To enforce Trusted Types for your application, you must configure your application's web server to emit HTTP headers with one of the following Angular policies:
| Policies | Detail |
| :----------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `angular` | This policy is used in security-reviewed code that is internal to Angular, and is required for Angular to function when Trusted Types are enforced. Any inline template values or content sanitized by Angular is treated as safe by this policy. |
| `angular#bundler` | This policy is used by the Angular CLI bundler when creating lazy chunk files. |
| `angular#unsafe-bypass` | This policy is used for applications that use any of the methods in Angular's [DomSanitizer](api/platform-browser/DomSanitizer) that bypass security, such as `bypassSecurityTrustHtml`. Any application that uses these methods must enable this policy. |
| `angular#unsafe-jit` | This policy is used by the [Just-In-Time (JIT) compiler](api/core/Compiler). You must enable this policy if your application interacts directly with the JIT compiler or is running in JIT mode using the [platform browser dynamic](api/platform-browser-dynamic/platformBrowserDynamic). |
| `angular#unsafe-upgrade` | This policy is used by the [@angular/upgrade](api/upgrade/static/UpgradeModule) package. You must enable this policy if your application is an AngularJS hybrid. |
You should configure the HTTP headers for Trusted Types in the following locations:
* Production serving infrastructure
* Angular CLI \(`ng serve`\), using the `headers` property in the `angular.json` file, for local development and end-to-end testing
* Karma \(`ng test`\), using the `customHeaders` property in the `karma.config.js` file, for unit testing
The following is an example of a header specifically configured for Trusted Types and Angular:
<docs-code language="html">
Content-Security-Policy: trusted-types angular; require-trusted-types-for 'script';
</docs-code>
An example of a header specifically configured for Trusted Types and Angular applications that use any of Angular's methods in [DomSanitizer](api/platform-browser/DomSanitizer) that bypasses security:
<docs-code language="html">
Content-Security-Policy: trusted-types angular angular#unsafe-bypass; require-trusted-types-for 'script';
</docs-code>
The following is an example of a header specifically configured for Trusted Types and Angular applications using JIT:
<docs-code language="html">
Content-Security-Policy: trusted-types angular angular#unsafe-jit; require-trusted-types-for 'script';
</docs-code>
The following is an example of a header specifically configured for Trusted Types and Angular applications that use lazy loading of modules:
<docs-code language="html">
Content-Security-Policy: trusted-types angular angular#bundler; require-trusted-types-for 'script';
</docs-code>
<docs-callout title="Community contributions">
To learn more about troubleshooting Trusted Type configurations, the following resource might be helpful:
[Prevent DOM-based cross-site scripting vulnerabilities with Trusted Types](https://web.dev/trusted-types/#how-to-use-trusted-types)
</docs-callout>
### Use the AOT template compiler
The AOT template compiler prevents a whole class of vulnerabilities called template injection, and greatly improves application performance.
The AOT template compiler is the default compiler used by Angular CLI applications, and you should use it in all production deployments.
An alternative to the AOT compiler is the JIT compiler which compiles templates to executable template code within the browser at runtime.
Angular trusts template code, so dynamically generating templates and compiling them, in particular templates containing user data, circumvents Angular's built-in protections. This is a security anti-pattern.
For information about dynamically constructing forms in a safe way, see the [Dynamic Forms](guide/forms/dynamic-forms) guide.
### Server-side XSS protection
HTML constructed on the server is vulnerable to injection attacks.
Injecting template code into an Angular application is the same as injecting executable code into the application:
It gives the attacker full control over the application.
To prevent this, use a templating language that automatically escapes values to prevent XSS vulnerabilities on the server.
Don't create Angular templates on the server side using a templating language. This carries a high risk of introducing template-injection vulnerabilities.
## HTT | {
"end_byte": 19973,
"start_byte": 10120,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/security.md"
} |
angular/adev/src/content/guide/security.md_19973_26995 | P-level vulnerabilities
Angular has built-in support to help prevent two common HTTP vulnerabilities, cross-site request forgery \(CSRF or XSRF\) and cross-site script inclusion \(XSSI\).
Both of these must be mitigated primarily on the server side, but Angular provides helpers to make integration on the client side easier.
### Cross-site request forgery
In a cross-site request forgery \(CSRF or XSRF\), an attacker tricks the user into visiting a different web page \(such as `evil.com`\) with malignant code. This web page secretly sends a malicious request to the application's web server \(such as `example-bank.com`\).
Assume the user is logged into the application at `example-bank.com`.
The user opens an email and clicks a link to `evil.com`, which opens in a new tab.
The `evil.com` page immediately sends a malicious request to `example-bank.com`.
Perhaps it's a request to transfer money from the user's account to the attacker's account.
The browser automatically sends the `example-bank.com` cookies, including the authentication cookie, with this request.
If the `example-bank.com` server lacks XSRF protection, it can't tell the difference between a legitimate request from the application and the forged request from `evil.com`.
To prevent this, the application must ensure that a user request originates from the real application, not from a different site.
The server and client must cooperate to thwart this attack.
In a common anti-XSRF technique, the application server sends a randomly created authentication token in a cookie.
The client code reads the cookie and adds a custom request header with the token in all following requests.
The server compares the received cookie value to the request header value and rejects the request if the values are missing or don't match.
This technique is effective because all browsers implement the _same origin policy_.
Only code from the website on which cookies are set can read the cookies from that site and set custom headers on requests to that site.
That means only your application can read this cookie token and set the custom header.
The malicious code on `evil.com` can't.
### `HttpClient` XSRF/CSRF security
`HttpClient` supports a [common mechanism](https://en.wikipedia.org/wiki/Cross-site_request_forgery#Cookie-to-header_token) used to prevent XSRF attacks. When performing HTTP requests, an interceptor reads a token from a cookie, by default `XSRF-TOKEN`, and sets it as an HTTP header, `X-XSRF-TOKEN`. Because only code that runs on your domain could read the cookie, the backend can be certain that the HTTP request came from your client application and not an attacker.
By default, an interceptor sends this header on all mutating requests (such as `POST`) to relative URLs, but not on GET/HEAD requests or on requests with an absolute URL.
<docs-callout helpful title="Why not protect GET requests?">
CSRF protection is only needed for requests that can change state on the backend. By their nature, CSRF attacks cross domain boundaries, and the web's [same-origin policy](https://developer.mozilla.org/docs/Web/Security/Same-origin_policy) will prevent an attacking page from retrieving the results of authenticated GET requests.
</docs-callout>
To take advantage of this, your server needs to set a token in a JavaScript readable session cookie called `XSRF-TOKEN` on either the page load or the first GET request. On subsequent requests the server can verify that the cookie matches the `X-XSRF-TOKEN` HTTP header, and therefore be sure that only code running on your domain could have sent the request. The token must be unique for each user and must be verifiable by the server; this prevents the client from making up its own tokens. Set the token to a digest of your site's authentication cookie with a salt for added security.
To prevent collisions in environments where multiple Angular apps share the same domain or subdomain, give each application a unique cookie name.
<docs-callout important title="HttpClient supports only the client half of the XSRF protection scheme">
Your backend service must be configured to set the cookie for your page, and to verify that the header is present on all eligible requests. Failing to do so renders Angular's default protection ineffective.
</docs-callout>
### Configure custom cookie/header names
If your backend service uses different names for the XSRF token cookie or header, use `withXsrfConfiguration` to override the defaults.
Add it to the `provideHttpClient` call as follows:
<docs-code language="ts">
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withXsrfConfiguration({
cookieName: 'CUSTOM_XSRF_TOKEN',
headerName: 'X-Custom-Xsrf-Header',
}),
),
]
};
</docs-code>
### Disabling XSRF protection
If the built-in XSRF protection mechanism doesn't work for your application, you can disable it using the `withNoXsrfProtection` feature:
<docs-code language="ts">
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withNoXsrfProtection(),
),
]
};
</docs-code>
For information about CSRF at the Open Web Application Security Project \(OWASP\), see [Cross-Site Request Forgery (CSRF)](https://owasp.org/www-community/attacks/csrf) and [Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html).
The Stanford University paper [Robust Defenses for Cross-Site Request Forgery](https://seclab.stanford.edu/websec/csrf/csrf.pdf) is a rich source of detail.
See also Dave Smith's [talk on XSRF at AngularConnect 2016](https://www.youtube.com/watch?v=9inczw6qtpY "Cross Site Request Funkery Securing Your Angular Apps From Evil Doers").
### Cross-site script inclusion (XSSI)
Cross-site script inclusion, also known as JSON vulnerability, can allow an attacker's website to read data from a JSON API.
The attack works on older browsers by overriding built-in JavaScript object constructors, and then including an API URL using a `<script>` tag.
This attack is only successful if the returned JSON is executable as JavaScript.
Servers can prevent an attack by prefixing all JSON responses to make them non-executable, by convention, using the well-known string `")]}',\n"`.
Angular's `HttpClient` library recognizes this convention and automatically strips the string `")]}',\n"` from all responses before further parsing.
For more information, see the XSSI section of this [Google web security blog post](https://security.googleblog.com/2011/05/website-security-for-webmasters.html).
## Auditing Angular applications
Angular applications must follow the same security principles as regular web applications, and must be audited as such.
Angular-specific APIs that should be audited in a security review, such as the [_bypassSecurityTrust_](#trusting-safe-values) methods, are marked in the documentation as security sensitive.
| {
"end_byte": 26995,
"start_byte": 19973,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/security.md"
} |
angular/adev/src/content/guide/zoneless.md_0_7604 | # 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.
| {
"end_byte": 7604,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/zoneless.md"
} |
angular/adev/src/content/guide/directives/attribute-directives.md_0_9164 | # Attribute directives
Change the appearance or behavior of DOM elements and Angular components with attribute directives.
## Building an attribute directive
This section walks you through creating a highlight directive that sets the background color of the host element to yellow.
1. To create a directive, use the CLI command [`ng generate directive`](tools/cli/schematics).
<docs-code language="shell">
ng generate directive highlight
</docs-code>
The CLI creates `src/app/highlight.directive.ts`, a corresponding test file `src/app/highlight.directive.spec.ts`.
<docs-code header="src/app/highlight.directive.ts" path="adev/src/content/examples/attribute-directives/src/app/highlight.directive.0.ts"/>
The `@Directive()` decorator's configuration property specifies the directive's CSS attribute selector, `[appHighlight]`.
1. Import `ElementRef` from `@angular/core`.
`ElementRef` grants direct access to the host DOM element through its `nativeElement` property.
1. Add `ElementRef` in the directive's `constructor()` to [inject](guide/di) a reference to the host DOM element, the element to which you apply `appHighlight`.
1. Add logic to the `HighlightDirective` class that sets the background to yellow.
<docs-code header="src/app/highlight.directive.ts" path="adev/src/content/examples/attribute-directives/src/app/highlight.directive.1.ts"/>
HELPFUL: Directives *do not* support namespaces.
<docs-code header="src/app/app.component.avoid.html (unsupported)" path="adev/src/content/examples/attribute-directives/src/app/app.component.avoid.html" visibleRegion="unsupported"/>
## Applying an attribute directive
1. To use the `HighlightDirective`, add a `<p>` element to the HTML template with the directive as an attribute.
<docs-code header="src/app/app.component.html" path="adev/src/content/examples/attribute-directives/src/app/app.component.1.html" visibleRegion="applied"/>
Angular creates an instance of the `HighlightDirective` class and injects a reference to the `<p>` element into the directive's constructor, which sets the `<p>` element's background style to yellow.
## Handling user events
This section shows you how to detect when a user mouses into or out of the element and to respond by setting or clearing the highlight color.
1. Import `HostListener` from '@angular/core'.
<docs-code header="src/app/highlight.directive.ts (imports)" path="adev/src/content/examples/attribute-directives/src/app/highlight.directive.2.ts" visibleRegion="imports"/>
1. Add two event handlers that respond when the mouse enters or leaves, each with the `@HostListener()` decorator.
<docs-code header="src/app/highlight.directive.ts (mouse-methods)" path="adev/src/content/examples/attribute-directives/src/app/highlight.directive.2.ts" visibleRegion="mouse-methods"/>
Subscribe to events of the DOM element that hosts an attribute directive, the `<p>` in this case, with the `@HostListener()` decorator.
HELPFUL: The handlers delegate to a helper method, `highlight()`, that sets the color on the host DOM element, `el`.
The complete directive is as follows:
<docs-code header="src/app/highlight.directive.ts" path="adev/src/content/examples/attribute-directives/src/app/highlight.directive.2.ts"/>
The background color appears when the pointer hovers over the paragraph element and disappears as the pointer moves out.
<img alt="Second Highlight" src="assets/images/guide/attribute-directives/highlight-directive-anim.gif">
## Passing values into an attribute directive
This section walks you through setting the highlight color while applying the `HighlightDirective`.
1. In `highlight.directive.ts`, import `Input` from `@angular/core`.
<docs-code header="src/app/highlight.directive.ts (imports)" path="adev/src/content/examples/attribute-directives/src/app/highlight.directive.3.ts" visibleRegion="imports"/>
1. Add an `appHighlight` `@Input()` property.
<docs-code header="src/app/highlight.directive.ts" path="adev/src/content/examples/attribute-directives/src/app/highlight.directive.3.ts" visibleRegion="input"/>
The `@Input()` decorator adds metadata to the class that makes the directive's `appHighlight` property available for binding.
1. In `app.component.ts`, add a `color` property to the `AppComponent`.
<docs-code header="src/app/app.component.ts (class)" path="adev/src/content/examples/attribute-directives/src/app/app.component.1.ts" visibleRegion="class"/>
1. To simultaneously apply the directive and the color, use property binding with the `appHighlight` directive selector, setting it equal to `color`.
<docs-code header="src/app/app.component.html (color)" path="adev/src/content/examples/attribute-directives/src/app/app.component.html" visibleRegion="color"/>
The `[appHighlight]` attribute binding performs two tasks:
* Applies the highlighting directive to the `<p>` element
* Sets the directive's highlight color with a property binding
### Setting the value with user input
This section guides you through adding radio buttons to bind your color choice to the `appHighlight` directive.
1. Add markup to `app.component.html` for choosing a color as follows:
<docs-code header="src/app/app.component.html (v2)" path="adev/src/content/examples/attribute-directives/src/app/app.component.html" visibleRegion="v2"/>
1. Revise the `AppComponent.color` so that it has no initial value.
<docs-code header="src/app/app.component.ts (class)" path="adev/src/content/examples/attribute-directives/src/app/app.component.ts" visibleRegion="class"/>
1. In `highlight.directive.ts`, revise `onMouseEnter` method so that it first tries to highlight with `appHighlight` and falls back to `red` if `appHighlight` is `undefined`.
<docs-code header="src/app/highlight.directive.ts (mouse-enter)" path="adev/src/content/examples/attribute-directives/src/app/highlight.directive.3.ts" visibleRegion="mouse-enter"/>
1. Serve your application to verify that the user can choose the color with the radio buttons.
<img alt="Animated gif of the refactored highlight directive changing color according to the radio button the user selects" src="assets/images/guide/attribute-directives/highlight-directive-v2-anim.gif">
## Binding to a second property
This section guides you through configuring your application so the developer can set the default color.
1. Add a second `Input()` property to `HighlightDirective` called `defaultColor`.
<docs-code header="src/app/highlight.directive.ts (defaultColor)" path="adev/src/content/examples/attribute-directives/src/app/highlight.directive.ts" visibleRegion="defaultColor"/>
1. Revise the directive's `onMouseEnter` so that it first tries to highlight with the `appHighlight`, then with the `defaultColor`, and falls back to `red` if both properties are `undefined`.
<docs-code header="src/app/highlight.directive.ts (mouse-enter)" path="adev/src/content/examples/attribute-directives/src/app/highlight.directive.ts" visibleRegion="mouse-enter"/>
1. To bind to the `AppComponent.color` and fall back to "violet" as the default color, add the following HTML.
In this case, the `defaultColor` binding doesn't use square brackets, `[]`, because it is static.
<docs-code header="src/app/app.component.html (defaultColor)" path="adev/src/content/examples/attribute-directives/src/app/app.component.html" visibleRegion="defaultColor"/>
As with components, you can add multiple directive property bindings to a host element.
The default color is red if there is no default color binding.
When the user chooses a color the selected color becomes the active highlight color.
<img alt="Animated gif of final highlight directive that shows red color with no binding and violet with the default color set. When user selects color, the selection takes precedence." src="assets/images/guide/attribute-directives/highlight-directive-final-anim.gif">
## Deactivating Angular processing with `NgNonBindable`
To prevent expression evaluation in the browser, add `ngNonBindable` to the host element.
`ngNonBindable` deactivates interpolation, directives, and binding in templates.
In the following example, the expression `{{ 1 + 1 }}` renders just as it does in your code editor, and does not display `2`.
<docs-code header="src/app/app.component.html" path="adev/src/content/examples/attribute-directives/src/app/app.component.html" visibleRegion="ngNonBindable"/>
Applying `ngNonBindable` to an element stops binding for that element's child elements.
However, `ngNonBindable` still lets directives work on the element where you apply `ngNonBindable`.
In the following example, the `appHighlight` directive is still active but Angular does not evaluate the expression `{{ 1 + 1 }}`.
<docs-code header="src/app/app.component.html" path="adev/src/content/examples/attribute-directives/src/app/app.component.html" visibleRegion="ngNonBindable-with-directive"/>
If you apply `ngNonBindable` to a parent element, Angular disables interpolation and binding of any sort, such as property binding or event binding, for the element's children.
| {
"end_byte": 9164,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/directives/attribute-directives.md"
} |
angular/adev/src/content/guide/directives/overview.md_0_8931 | <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).
| {
"end_byte": 8931,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/directives/overview.md"
} |
angular/adev/src/content/guide/directives/overview.md_8931_16862 | ## 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">
| {
"end_byte": 16862,
"start_byte": 8931,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/directives/overview.md"
} |
angular/adev/src/content/guide/directives/overview.md_16862_20393 | ## Switching cases with `NgSwitch`
Like the JavaScript `switch` statement, `NgSwitch` displays one element from among several possible elements, based on a switch condition.
Angular puts only the selected element into the DOM.
<!--todo: API Flagged -->
`NgSwitch` is a set of three directives:
| `NgSwitch` directives | Details |
| :-------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `NgSwitch` | An attribute directive that changes the behavior of its companion directives. |
| `NgSwitchCase` | Structural directive that adds its element to the DOM when its bound value equals the switch value and removes its bound value when it doesn't equal the switch value. |
| `NgSwitchDefault` | Structural directive that adds its element to the DOM when there is no selected `NgSwitchCase`. |
To use the directives, add the `NgSwitch`, `NgSwitchCase` and `NgSwitchDefault` to the component's `imports` list.
<docs-code header="src/app/app.component.ts (NgSwitch imports)" path="adev/src/content/examples/built-in-directives/src/app/app.component.ts" visibleRegion="import-ng-switch"/>
### Using `NgSwitch`
1. On an element, such as a `<div>`, add `[ngSwitch]` bound to an expression that returns the switch value, such as `feature`.
Though the `feature` value in this example is a string, the switch value can be of any type.
1. Bind to `*ngSwitchCase` and `*ngSwitchDefault` on the elements for the cases.
<docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgSwitch"/>
1. In the parent component, define `currentItem`, to use it in the `[ngSwitch]` expression.
<docs-code header="src/app/app.component.ts" path="adev/src/content/examples/built-in-directives/src/app/app.component.ts" visibleRegion="item"/>
1. In each child component, add an `item` [input property](guide/components/inputs) which is bound to the `currentItem` of the parent component.
The following two snippets show the parent component and one of the child components.
The other child components are identical to `StoutItemComponent`.
<docs-code header="In each child component, here StoutItemComponent" path="adev/src/content/examples/built-in-directives/src/app/item-switch.component.ts" visibleRegion="input"/>
<img alt="Animation of NgSwitch" src="assets/images/guide/built-in-directives/ngswitch.gif">
Switch directives also work with built-in HTML elements and web components.
For example, you could replace the `<app-best-item>` switch case with a `<div>` as follows.
<docs-code header="src/app/app.component.html" path="adev/src/content/examples/built-in-directives/src/app/app.component.html" visibleRegion="NgSwitch-div"/>
## What's next
<docs-pill-row>
<docs-pill href="guide/directives/attribute-directives" title="Attribute Directives"/>
<docs-pill href="guide/directives/structural-directives" title="Structural Directives"/>
<docs-pill href="guide/directives/directive-composition-api" title="Directive composition API"/>
</docs-pill-row>
| {
"end_byte": 20393,
"start_byte": 16862,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/directives/overview.md"
} |
angular/adev/src/content/guide/directives/directive-composition-api.md_0_6051 | # Directive composition API
Angular directives offer a great way to encapsulate reusable behaviors— directives can apply
attributes, CSS classes, and event listeners to an element.
The *directive composition API* lets you apply directives to a component's host element from
*within* the component TypeScript class.
## Adding directives to a component
You apply directives to a component by adding a `hostDirectives` property to a component's
decorator. We call such directives *host directives*.
In this example, we apply the directive `MenuBehavior` to the host element of `AdminMenu`. This
works similarly to applying the `MenuBehavior` to the `<admin-menu>` element in a template.
```typescript
@Component({
standalone: true,
selector: 'admin-menu',
template: 'admin-menu.html',
hostDirectives: [MenuBehavior],
})
export class AdminMenu { }
```
When the framework renders a component, Angular also creates an instance of each host directive. The
directives' host bindings apply to the component's host element. By default, host directive inputs
and outputs are not exposed as part of the component's public API. See
[Including inputs and outputs](#including-inputs-and-outputs) below for more information.
**Angular applies host directives statically at compile time.** You cannot dynamically add
directives at runtime.
**Directives used in `hostDirectives` must be `standalone: true`.**
**Angular ignores the `selector` of directives applied in the `hostDirectives` property.**
## Including inputs and outputs
When you apply `hostDirectives` to your component, the inputs and outputs from the host directives
are not included in your component's API by default. You can explicitly include inputs and outputs
in your component's API by expanding the entry in `hostDirectives`:
```typescript
@Component({
standalone: true,
selector: 'admin-menu',
template: 'admin-menu.html',
hostDirectives: [{
directive: MenuBehavior,
inputs: ['menuId'],
outputs: ['menuClosed'],
}],
})
export class AdminMenu { }
```
By explicitly specifying the inputs and outputs, consumers of the component with `hostDirective` can
bind them in a template:
```angular-html
<admin-menu menuId="top-menu" (menuClosed)="logMenuClosed()">
```
Furthermore, you can alias inputs and outputs from `hostDirective` to customize the API of your
component:
```typescript
@Component({
standalone: true,
selector: 'admin-menu',
template: 'admin-menu.html',
hostDirectives: [{
directive: MenuBehavior,
inputs: ['menuId: id'],
outputs: ['menuClosed: closed'],
}],
})
export class AdminMenu { }
```
```angular-html
<admin-menu id="top-menu" (closed)="logMenuClosed()">
```
## Adding directives to another directive
You can also add `hostDirectives` to other directives, in addition to components. This enables the
transitive aggregation of multiple behaviors.
In the following example, we define two directives, `Menu` and `Tooltip`. We then compose the behavior
of these two directives in `MenuWithTooltip`. Finally, we apply `MenuWithTooltip`
to `SpecializedMenuWithTooltip`.
When `SpecializedMenuWithTooltip` is used in a template, it creates instances of all of `Menu`
, `Tooltip`, and `MenuWithTooltip`. Each of these directives' host bindings apply to the host
element of `SpecializedMenuWithTooltip`.
```typescript
@Directive({...})
export class Menu { }
@Directive({...})
export class Tooltip { }
// MenuWithTooltip can compose behaviors from multiple other directives
@Directive({
standalone: true,
hostDirectives: [Tooltip, Menu],
})
export class MenuWithTooltip { }
// CustomWidget can apply the already-composed behaviors from MenuWithTooltip
@Directive({
standalone: true,
hostDirectives: [MenuWithTooltip],
})
export class SpecializedMenuWithTooltip { }
```
## Host directive semantics
### Directive execution order
Host directives go through the same lifecycle as components and directives used directly in a
template. However, host directives always execute their constructor, lifecycle hooks, and bindings _before_ the component or directive on which they are applied.
The following example shows minimal use of a host directive:
```typescript
@Component({
standalone: true,
selector: 'admin-menu',
template: 'admin-menu.html',
hostDirectives: [MenuBehavior],
})
export class AdminMenu { }
```
The order of execution here is:
1. `MenuBehavior` instantiated
2. `AdminMenu` instantiated
3. `MenuBehavior` receives inputs (`ngOnInit`)
4. `AdminMenu` receives inputs (`ngOnInit`)
5. `MenuBehavior` applies host bindings
6. `AdminMenu` applies host bindings
This order of operations means that components with `hostDirectives` can override any host bindings
specified by a host directive.
This order of operations extends to nested chains of host directives, as shown in the following
example.
```typescript
@Directive({...})
export class Tooltip { }
@Directive({
standalone: true,
hostDirectives: [Tooltip],
})
export class CustomTooltip { }
@Directive({
standalone: true,
hostDirectives: [CustomTooltip],
})
export class EvenMoreCustomTooltip { }
```
In the example above, the order of execution is:
1. `Tooltip` instantiated
2. `CustomTooltip` instantiated
3. `EvenMoreCustomTooltip` instantiated
4. `Tooltip` receives inputs (`ngOnInit`)
5. `CustomTooltip` receives inputs (`ngOnInit`)
6. `EvenMoreCustomTooltip` receives inputs (`ngOnInit`)
7. `Tooltip` applies host bindings
8. `CustomTooltip` applies host bindings
9. `EvenMoreCustomTooltip` applies host bindings
### Dependency injection
A component or directive that specifies `hostDirectives` can inject the instances of those host
directives and vice versa.
When applying host directives to a component, both the component and host directives can define
providers.
If a component or directive with `hostDirectives` and those host directives both provide the same
injection token, the providers defined by class with `hostDirectives` take precedence over providers
defined by the host directives.
| {
"end_byte": 6051,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/directives/directive-composition-api.md"
} |
angular/adev/src/content/guide/directives/BUILD.bazel_0_1513 | load("//adev/shared-docs:index.bzl", "generate_guides")
generate_guides(
name = "directives",
srcs = glob([
"*.md",
]),
data = [
"//adev/src/assets/images:directives.svg",
"//adev/src/content/examples/attribute-directives:src/app/app.component.1.html",
"//adev/src/content/examples/attribute-directives:src/app/app.component.1.ts",
"//adev/src/content/examples/attribute-directives:src/app/app.component.avoid.html",
"//adev/src/content/examples/attribute-directives:src/app/app.component.html",
"//adev/src/content/examples/attribute-directives:src/app/app.component.ts",
"//adev/src/content/examples/attribute-directives:src/app/highlight.directive.0.ts",
"//adev/src/content/examples/attribute-directives:src/app/highlight.directive.1.ts",
"//adev/src/content/examples/attribute-directives:src/app/highlight.directive.2.ts",
"//adev/src/content/examples/attribute-directives:src/app/highlight.directive.3.ts",
"//adev/src/content/examples/attribute-directives:src/app/highlight.directive.ts",
"//adev/src/content/examples/built-in-directives:src/app/app.component.html",
"//adev/src/content/examples/built-in-directives:src/app/app.component.ts",
"//adev/src/content/examples/built-in-directives:src/app/item-switch.component.ts",
"//adev/src/content/examples/structural-directives:src/app/app.component.html",
],
visibility = ["//adev:__subpackages__"],
)
| {
"end_byte": 1513,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/directives/BUILD.bazel"
} |
angular/adev/src/content/guide/directives/structural-directives.md_0_7819 | # 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">` |
| {
"end_byte": 7819,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/directives/structural-directives.md"
} |
angular/adev/src/content/guide/directives/structural-directives.md_7819_11474 | ## Improving template type checking for custom directives
You can improve template type checking for custom directives by adding template guards to your directive definition.
These guards help the Angular template type checker find mistakes in the template at compile time, which can avoid runtime errors.
Two different types of guards are possible:
* `ngTemplateGuard_(input)` lets you control how an input expression should be narrowed based on the type of a specific input.
* `ngTemplateContextGuard` is used to determine the type of the context object for the template, based on the type of the directive itself.
This section provides examples of both kinds of guards.
For more information, see [Template type checking](tools/cli/template-typecheck "Template type-checking guide").
### Type narrowing with template guards
A structural directive in a template controls whether that template is rendered at run time. Some structural directives want to perform type narrowing based on the type of input expression.
There are two narrowings which are possible with input guards:
* Narrowing the input expression based on a TypeScript type assertion function.
* Narrowing the input expression based on its truthiness.
To narrow the input expression by defining a type assertion function:
```ts
// This directive only renders its template if the actor is a user.
// You want to assert that within the template, the type of the `actor`
// expression is narrowed to `User`.
@Directive(...)
class ActorIsUser {
@Input() actor: User|Robot;
static ngTemplateGuard_actor(dir: ActorIsUser, expr: User|Robot): expr is User {
// The return statement is unnecessary in practice, but included to
// prevent TypeScript errors.
return true;
}
}
```
Type-checking will behave within the template as if the `ngTemplateGuard_actor` has been asserted on the expression bound to the input.
Some directives only render their templates when an input is truthy. It's not possible to capture the full semantics of truthiness in a type assertion function, so instead a literal type of `'binding'` can be used to signal to the template type-checker that the binding expression itself should be used as the guard:
```ts
@Directive(...)
class CustomIf {
@Input() condition!: any;
static ngTemplateGuard_condition: 'binding';
}
```
The template type-checker will behave as if the expression bound to `condition` was asserted to be truthy within the template.
### Typing the directive's context
If your structural directive provides a context to the instantiated template, you can properly type it inside the template by providing a static `ngTemplateContextGuard` type assertion function. This function can use the type of the directive to derive the type of the context, which is useful when the type of the directive is generic.
For the `SelectDirective` described above, you can implement an `ngTemplateContextGuard` to correctly specify the data type, even if the data source is generic.
```ts
// Declare an interface for the template context:
export interface SelectTemplateContext<T> {
$implicit: T;
}
@Directive(...)
export class SelectDirective<T> {
// The directive's generic type `T` will be inferred from the `DataSource` type
// passed to the input.
@Input({required: true}) selectFrom!: DataSource<T>;
// Narrow the type of the context using the generic type of the directive.
static ngTemplateContextGuard<T>(dir: SelectDirective<T>, ctx: any): ctx is SelectTemplateContext<T> {
// As before the guard body is not used at runtime, and included only to avoid
// TypeScript errors.
return true;
}
}
```
| {
"end_byte": 11474,
"start_byte": 7819,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/directives/structural-directives.md"
} |
angular/adev/src/content/guide/ngmodules/singleton-services.md_0_8368 | # 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>
| {
"end_byte": 8368,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/singleton-services.md"
} |
angular/adev/src/content/guide/ngmodules/lazy-loading.md_0_1562 | # Lazy-loading feature modules
By default, NgModules are eagerly loaded. This means that as soon as the application loads, so do all the NgModules, whether they are immediately necessary or not.
For large applications with lots of routes, consider lazy loading —a design pattern that loads NgModules as needed.
Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.
<!-- For the final sample application with two lazy-loaded modules that this page describes: -->
<!-- TODO: link to GitHub -->
<!-- <docs-code live/> -->
## Lazy loading basics
This section introduces the basic procedure for configuring a lazy-loaded route.
For a step-by-step example, see the [step-by-step setup](#step-by-step-setup) section on this page.
To lazy load Angular modules, use `loadChildren` (instead of `component`) in your `AppRoutingModule` `routes` configuration as follows.
<docs-code header="AppRoutingModule (excerpt)" language="typescript">
const routes: Routes = [
{
path: 'items',
loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
}
];
</docs-code>
In the lazy-loaded module's routing module, add a route for the component.
<docs-code header="Routing module for lazy loaded module (excerpt)" language="typescript">
const routes: Routes = [
{
path: '',
component: ItemsComponent
}
];
</docs-code>
Also be sure to remove the `ItemsModule` from the `AppModule`.
For step-by-step instructions on lazy loading modules, continue with the following sections of this page.
## | {
"end_byte": 1562,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/lazy-loading.md"
} |
angular/adev/src/content/guide/ngmodules/lazy-loading.md_1562_9982 | 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>
## | {
"end_byte": 9982,
"start_byte": 1562,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/lazy-loading.md"
} |
angular/adev/src/content/guide/ngmodules/lazy-loading.md_9982_17247 | # 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)
| {
"end_byte": 17247,
"start_byte": 9982,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/lazy-loading.md"
} |
angular/adev/src/content/guide/ngmodules/vs-jsmodule.md_0_5009 | # JavaScript modules vs. NgModules
JavaScript modules and NgModules can help you modularize your code, but they are very different.
Angular applications rely on both kinds of modules.
## JavaScript modules: Files exposing code
A [JavaScript module](https://javascript.info/modules "JavaScript.Info - Modules") is an individual file with JavaScript code, usually containing a class or a library of functions for a specific purpose within your application.
JavaScript modules let you spread your work across multiple files.
HELPFUL: To learn more about JavaScript modules, see [ES6 In Depth: Modules](https://hacks.mozilla.org/2015/08/es6-in-depth-modules).
For the module specification, see the [6th Edition of the ECMAScript standard](https://www.ecma-international.org/ecma-262/6.0/#sec-modules).
To make the code in a JavaScript module available to other modules, use an `export` statement at the end of the relevant code in the module, such as the following:
<docs-code language="typescript">
export class AppComponent { … }
</docs-code>
When you need that module's code in another module, use an `import` statement as follows:
<docs-code language="typescript">
import { AppComponent } from './app.component';
</docs-code>
Each module has its own top-level scope.
In other words, top-level variables and functions in a module are not seen in other scripts or modules.
## NgModules: Classes with metadata for compiling
An NgModule is a class marked by the `@NgModule` decorator with a metadata object that describes how that particular part of the application fits together with the other parts.
NgModules are specific to Angular.
While classes with an `@NgModule` decorator are by convention kept in their own files, they differ from JavaScript modules because they include this metadata.
The `@NgModule` metadata plays an important role in guiding the Angular compilation process that converts the application code you write into highly performant JavaScript code.
The metadata describes how to compile a component's template and how to create an injector at runtime.
It identifies the NgModule's components, directives, and pipes"),
and makes some of them public through the `exports` property so that external components can use them.
You can also use an NgModule to add providers for services, so that the services are available elsewhere in your application.
Rather than defining all member classes in one giant file as a JavaScript module, declare which components, directives, and pipes belong to the NgModule in the `@NgModule.declarations` list.
These classes are called declarables.
An NgModule can export only the declarable classes it owns or imports from other NgModules.
It doesn't declare or export any other kind of class.
Declarables are the only classes that matter to the Angular compilation process.
For a complete description of the NgModule metadata properties, see [Using the NgModule metadata](guide/ngmodules/api "Using the NgModule metadata").
## An example that uses both
The root NgModule `AppModule` generated by the [Angular CLI](/tools/cli) (when using the `--no-standalone` option) for a new application project demonstrates how you use both kinds of modules:
<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>
The root NgModule starts with `import` statements to import JavaScript modules.
It then configures the `@NgModule` with the following arrays:
* `declarations`: The components, directives, and pipes that belong to the NgModule.
A new application project's root NgModule has only one component, called `AppComponent`.
* `imports`: Other NgModules you are using, so that you can use their declarables.
The newly generated root NgModule imports [`BrowserModule`](api/platform-browser/BrowserModule "BrowserModule NgModule") in order to use browser-specific services such as [DOM](https://www.w3.org/TR/DOM-Level-2-Core/introduction.html "Definition of Document Object Model") rendering, sanitization, and location.
* `providers`: Providers of services that components in other NgModules can use.
There are no providers in a newly generated root NgModule.
* `bootstrap`: The component that Angular creates and inserts into the `index.html` host web page, thereby bootstrapping the application.
This component, `AppComponent`, appears in both the `declarations` and the `bootstrap` arrays.
## Next steps
* To learn more about the root NgModule, see [Launching an app with a root NgModule](guide/ngmodules/bootstrapping "Launching an app with a root NgModule").
* To learn about frequently used Angular NgModules and how to import them into your app, see [Frequently-used modules](guide/ngmodules/frequent "Frequently-used modules").
| {
"end_byte": 5009,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/vs-jsmodule.md"
} |
angular/adev/src/content/guide/ngmodules/overview.md_0_3537 | # 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>
| {
"end_byte": 3537,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/overview.md"
} |
angular/adev/src/content/guide/ngmodules/providers.md_0_6962 | # 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>
| {
"end_byte": 6962,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/providers.md"
} |
angular/adev/src/content/guide/ngmodules/api.md_0_7768 | # 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>
| {
"end_byte": 7768,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/api.md"
} |
angular/adev/src/content/guide/ngmodules/bootstrapping.md_0_6601 | # 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.
| {
"end_byte": 6601,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/bootstrapping.md"
} |
angular/adev/src/content/guide/ngmodules/faq.md_0_7754 | # 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 | {
"end_byte": 7754,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/faq.md"
} |
angular/adev/src/content/guide/ngmodules/faq.md_7754_16931 | 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 | {
"end_byte": 16931,
"start_byte": 7754,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/faq.md"
} |
angular/adev/src/content/guide/ngmodules/faq.md_16931_25341 | 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.
| {
"end_byte": 25341,
"start_byte": 16931,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/faq.md"
} |
angular/adev/src/content/guide/ngmodules/module-types.md_0_7172 | # 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")
| {
"end_byte": 7172,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/module-types.md"
} |
angular/adev/src/content/guide/ngmodules/frequent.md_0_2816 | # 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.
| {
"end_byte": 2816,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/frequent.md"
} |
angular/adev/src/content/guide/ngmodules/feature-modules.md_0_6824 | # 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>
| {
"end_byte": 6824,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/feature-modules.md"
} |
angular/adev/src/content/guide/ngmodules/BUILD.bazel_0_207 | load("//adev/shared-docs:index.bzl", "generate_guides")
generate_guides(
name = "ngmodules",
srcs = glob([
"*.md",
]),
data = [
],
visibility = ["//adev:__subpackages__"],
)
| {
"end_byte": 207,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/BUILD.bazel"
} |
angular/adev/src/content/guide/ngmodules/sharing.md_0_2012 | # 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>
| {
"end_byte": 2012,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/ngmodules/sharing.md"
} |
angular/adev/src/content/guide/di/overview.md_0_2493 | <docs-decorative-header title="Dependency injection in Angular" imgSrc="adev/src/assets/images/dependency_injection.svg"> <!-- markdownlint-disable-line -->
"DI" is a design pattern and mechanism for creating and delivering some parts of an app to other parts of an app that require them.
</docs-decorative-header>
Tip: Check out Angular's [Essentials](essentials/sharing-logic) before diving into this comprehensive guide.
When you develop a smaller part of your system, like a module or a class, you may need to use features from other classes. For example, you may need an HTTP service to make backend calls. Dependency Injection, or DI, is a design pattern and mechanism for creating and delivering some parts of an application to other parts of an application that require them. Angular supports this design pattern and you can use it in your applications to increase flexibility and modularity.
In Angular, dependencies are typically services, but they also can be values, such as strings or functions. An injector for an application (created automatically during bootstrap) instantiates dependencies when needed, using a configured provider of the service or value.
## Learn about Angular dependency injection
<docs-card-container>
<docs-card title="Understanding dependency injection" href="/guide/di/dependency-injection">
Learn basic principles of dependency injection in Angular.
</docs-card>
<docs-card title="Creating and injecting service" href="/guide/di/creating-injectable-service">
Describes how to create a service and inject it in other services and components.
</docs-card>
<docs-card title="Configuring dependency providers" href="/guide/di/dependency-injection-providers">
Describes how to configure dependencies using the providers field on the @Component and @NgModule decorators. Also describes how to use InjectionToken to provide and inject values in DI, which can be helpful when you want to use a value other than classes as dependencies.
</docs-card>
<docs-card title="Injection context" href="/guide/di/dependency-injection-context">
Describes what an injection context is and how to use the DI system where you need it.
</docs-card>
<docs-card title="Hierarchical injectors" href="/guide/di/hierarchical-dependency-injection">
Hierarchical DI enables you to share dependencies between different parts of the application only when and if you need to. This is an advanced topic.
</docs-card>
</docs-card-container>
| {
"end_byte": 2493,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/overview.md"
} |
angular/adev/src/content/guide/di/creating-injectable-service.md_0_5554 | # 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>
| {
"end_byte": 5554,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/creating-injectable-service.md"
} |
angular/adev/src/content/guide/di/dependency-injection-providers.md_0_9565 | # 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>
| {
"end_byte": 9565,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/dependency-injection-providers.md"
} |
angular/adev/src/content/guide/di/di-in-action.md_0_3131 | # DI in action
This guide explores additional features of dependency injection in Angular.
## Custom providers with `@Inject`
Using a custom provider allows you to provide a concrete implementation for implicit dependencies, such as built-in browser APIs.
The following example uses an `InjectionToken` to provide the [localStorage](https://developer.mozilla.org/docs/Web/API/Window/localStorage) browser API as a dependency in the `BrowserStorageService`:
<docs-code header="src/app/storage.service.ts" language="typescript"
highlight="[[3,6],[12]]">
import { Inject, Injectable, InjectionToken } from '@angular/core';
export const BROWSER_STORAGE = new InjectionToken<Storage>('Browser Storage', {
providedIn: 'root',
factory: () => localStorage
});
@Injectable({
providedIn: 'root'
})
export class BrowserStorageService {
constructor(@Inject(BROWSER_STORAGE) public storage: Storage) {}
get(key: string) {
return this.storage.getItem(key);
}
set(key: string, value: string) {
this.storage.setItem(key, value);
}
}
</docs-code>
The `factory` function returns the `localStorage` property that is attached to the browser's window object.
The `Inject` decorator is applied to the `storage` constructor parameter and specifies a custom provider of the dependency.
This custom provider can now be overridden during testing with a mock API of `localStorage` instead of interacting with real browser APIs.
## Inject the component's DOM element
Although developers strive to avoid it, some visual effects and third-party tools require direct DOM access.
As a result, you might need to access a component's DOM element.
Angular exposes the underlying element of a `@Component` or `@Directive` via injection using the `ElementRef` injection token:
<docs-code language="typescript" highlight="[7]">
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private element: ElementRef) {}
update() {
this.element.nativeElement.style.color = 'red';
}
}
</docs-code>
## Resolve circular dependencies with a forward reference
The order of class declaration matters in TypeScript.
You can't refer directly to a class until it's been defined.
This isn't usually a problem, especially if you adhere to the recommended *one class per file* rule.
But sometimes circular references are unavoidable.
For example, when class 'A' refers to class 'B' and 'B' refers to 'A', one of them has to be defined first.
The Angular `forwardRef()` function creates an *indirect* reference that Angular can resolve later.
You face a similar problem when a class makes *a reference to itself*.
For example, in its `providers` array.
The `providers` array is a property of the `@Component()` decorator function, which must appear before the class definition.
You can break such circular references by using `forwardRef`.
<docs-code header="app.component.ts" language="typescript" highlight="[4]">
providers: [
{
provide: PARENT_MENU_ITEM,
useExisting: forwardRef(() => MenuItem),
},
],
</docs-code>
| {
"end_byte": 3131,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/di-in-action.md"
} |
angular/adev/src/content/guide/di/dependency-injection.md_0_6519 | # 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>
| {
"end_byte": 6519,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/dependency-injection.md"
} |
angular/adev/src/content/guide/di/dependency-injection-context.md_0_3004 | # 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).
| {
"end_byte": 3004,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/dependency-injection-context.md"
} |
angular/adev/src/content/guide/di/hierarchical-dependency-injection.md_0_8882 | # 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.
## | {
"end_byte": 8882,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/hierarchical-dependency-injection.md"
} |
angular/adev/src/content/guide/di/hierarchical-dependency-injection.md_8882_16119 | Resolution rules
When resolving a token for a component/directive, Angular resolves it in two phases:
1. Against its parents in the `ElementInjector` hierarchy.
2. Against its parents in the `EnvironmentInjector` hierarchy.
When a component declares a dependency, Angular tries to satisfy that dependency with its own `ElementInjector`.
If the component's injector lacks the provider, it passes the request up to its parent component's `ElementInjector`.
The requests keep forwarding up until Angular finds an injector that can handle the request or runs out of ancestor `ElementInjector` hierarchies.
If Angular doesn't find the provider in any `ElementInjector` hierarchies, it goes back to the element where the request originated and looks in the `EnvironmentInjector` hierarchy.
If Angular still doesn't find the provider, it throws an error.
If you have registered a provider for the same DI token at different levels, the first one Angular encounters is the one it uses to resolve the dependency.
If, for example, a provider is registered locally in the component that needs a service,
Angular doesn't look for another provider of the same service.
HELPFUL: For `NgModule` based applications, Angular will search the `ModuleInjector` hierarchy if it cannot find a provider in the `ElementInjector` hierarchies.
## Resolution modifiers
Angular's resolution behavior can be modified with `@Optional()`, `@Self()`, `@SkipSelf()` and `@Host()`.
Import each of them from `@angular/core` and use each in the component class constructor or in the `inject` configuration when you inject your service.
### Types of modifiers
Resolution modifiers fall into three categories:
* What to do if Angular doesn't find what you're looking for, that is `@Optional()`
* Where to start looking, that is `@SkipSelf()`
* Where to stop looking, `@Host()` and `@Self()`
By default, Angular always starts at the current `Injector` and keeps searching all the way up.
Modifiers allow you to change the starting, or _self_, location and the ending location.
Additionally, you can combine all of the modifiers except:
* `@Host()` and `@Self()`
* `@SkipSelf()` and `@Self()`.
### `@Optional()`
`@Optional()` allows Angular to consider a service you inject to be optional.
This way, if it can't be resolved at runtime, Angular resolves the service as `null`, rather than throwing an error.
In the following example, the service, `OptionalService`, isn't provided in the service, `ApplicationConfig`, `@NgModule()`, or component class, so it isn't available anywhere in the app.
<docs-code header="src/app/optional/optional.component.ts" language="typescript">
export class OptionalComponent {
constructor(@Optional() public optional?: OptionalService) {}
}
</docs-code>
### `@Self()`
Use `@Self()` so that Angular will only look at the `ElementInjector` for the current component or directive.
A good use case for `@Self()` is to inject a service but only if it is available on the current host element.
To avoid errors in this situation, combine `@Self()` with `@Optional()`.
For example, in the following `SelfNoDataComponent`, notice the injected `LeafService` in the constructor.
<docs-code header="src/app/self-no-data/self-no-data.component.ts" language="typescript"
highlight="[7]">
@Component({
selector: 'app-self-no-data',
templateUrl: './self-no-data.component.html',
styleUrls: ['./self-no-data.component.css']
})
export class SelfNoDataComponent {
constructor(@Self() @Optional() public leaf?: LeafService) { }
}
</docs-code>
In this example, there is a parent provider and injecting the service will return the value, however, injecting the service with `@Self()` and `@Optional()` will return `null` because `@Self()` tells the injector to stop searching in the current host element.
Another example shows the component class with a provider for `FlowerService`.
In this case, the injector looks no further than the current `ElementInjector` because it finds the `FlowerService` and returns the tulip <code>🌷</code>.
<docs-code header="src/app/self/self.component.ts" path="adev/src/content/examples/resolution-modifiers/src/app/self/self.component.ts" visibleRegion="self-component"/>
### `@SkipSelf()`
`@SkipSelf()` is the opposite of `@Self()`.
With `@SkipSelf()`, Angular starts its search for a service in the parent `ElementInjector`, rather than in the current one.
So if the parent `ElementInjector` were using the fern <code>🌿</code> value for `emoji`, but you had maple leaf <code>🍁</code> in the component's `providers` array, Angular would ignore maple leaf <code>🍁</code> and use fern <code>🌿</code>.
To see this in code, assume that the following value for `emoji` is what the parent component were using, as in this service:
<docs-code header="src/app/leaf.service.ts" language="typescript">
export class LeafService {
emoji = '🌿';
}
</docs-code>
Imagine that in the child component, you had a different value, maple leaf <code>🍁</code> but you wanted to use the parent's value instead.
This is when you'd use `@SkipSelf()`:
<docs-code header="src/app/skipself/skipself.component.ts" language="typescript"
highlight="[[6],[10]]">
@Component({
selector: 'app-skipself',
templateUrl: './skipself.component.html',
styleUrls: ['./skipself.component.css'],
// Angular would ignore this LeafService instance
providers: [{ provide: LeafService, useValue: { emoji: '🍁' } }]
})
export class SkipselfComponent {
// Use @SkipSelf() in the constructor
constructor(@SkipSelf() public leaf: LeafService) { }
}
</docs-code>
In this case, the value you'd get for `emoji` would be fern <code>🌿</code>, not maple leaf <code>🍁</code>.
#### `@SkipSelf()` with `@Optional()`
Use `@SkipSelf()` with `@Optional()` to prevent an error if the value is `null`.
In the following example, the `Person` service is injected in the constructor.
`@SkipSelf()` tells Angular to skip the current injector and `@Optional()` will prevent an error should the `Person` service be `null`.
<docs-code language="typescript">
class Person {
constructor(@Optional() @SkipSelf() parent?: Person) {}
}
</docs-code>
### `@Host()`
<!-- TODO: Remove ambiguity between @Host and @Self. -->
`@Host()` lets you designate a component as the last stop in the injector tree when searching for providers.
Even if there is a service instance further up the tree, Angular won't continue looking.
Use `@Host()` as follows:
<docs-code header="src/app/host/host.component.ts" language="typescript"
highlight="[[6],[10]]">
@Component({
selector: 'app-host',
templateUrl: './host.component.html',
styleUrls: ['./host.component.css'],
// provide the service
providers: [{ provide: FlowerService, useValue: { emoji: '🌷' } }]
})
export class HostComponent {
// use @Host() in the constructor when injecting the service
constructor(@Host() @Optional() public flower?: FlowerService) { }
}
</docs-code>
Since `HostComponent` has `@Host()` in its constructor, no matter what the parent of `HostComponent` might have as a `flower.emoji` value, the `HostComponent` will use tulip <code>🌷</code>.
## Logical | {
"end_byte": 16119,
"start_byte": 8882,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/hierarchical-dependency-injection.md"
} |
angular/adev/src/content/guide/di/hierarchical-dependency-injection.md_16119_17607 | structure of the template
When you provide services in the component class, services are visible within the `ElementInjector` tree relative to where and how you provide those services.
Understanding the underlying logical structure of the Angular template will give you a foundation for configuring services and in turn control their visibility.
Components are used in your templates, as in the following example:
<docs-code language="html">
<app-root>
<app-child></app-child>;
</app-root>
</docs-code>
HELPFUL: Usually, you declare the components and their templates in separate files.
For the purposes of understanding how the injection system works, it is useful to look at them from the point of view of a combined logical tree.
The term _logical_ distinguishes it from the render tree, which is your application's DOM tree.
To mark the locations of where the component templates are located, this guide uses the `<#VIEW>` pseudo-element, which doesn't actually exist in the render tree and is present for mental model purposes only.
The following is an example of how the `<app-root>` and `<app-child>` view trees are combined into a single logical tree:
<docs-code language="html">
<app-root>
<#VIEW>
<app-child>
<#VIEW>
…content goes here…
</#VIEW>
</app-child>
</#VIEW>
</app-root>
</docs-code>
Understanding the idea of the `<#VIEW>` demarcation is especially significant when you configure services in the component class.
## Example: Pro | {
"end_byte": 17607,
"start_byte": 16119,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/hierarchical-dependency-injection.md"
} |
angular/adev/src/content/guide/di/hierarchical-dependency-injection.md_17607_25301 | viding services in `@Component()`
How you provide services using a `@Component()` (or `@Directive()`) decorator determines their visibility.
The following sections demonstrate `providers` and `viewProviders` along with ways to modify service visibility with `@SkipSelf()` and `@Host()`.
A component class can provide services in two ways:
| Arrays | Details |
|:--- |:--- |
| With a `providers` array | `@Component({ providers: [SomeService] })` |
| With a `viewProviders` array | `@Component({ viewProviders: [SomeService] })` |
In the examples below, you will see the logical tree of an Angular application.
To illustrate how the injector works in the context of templates, the logical tree will represent the HTML structure of the application.
For example, the logical tree will show that `<child-component>` is a direct children of `<parent-component>`.
In the logical tree, you will see special attributes: `@Provide`, `@Inject`, and `@ApplicationConfig`.
These aren't real attributes but are here to demonstrate what is going on under the hood.
| Angular service attribute | Details |
|:--- |:--- |
| `@Inject(Token)=>Value` | If `Token` is injected at this location in the logical tree, its value would be `Value`. |
| `@Provide(Token=Value)` | Indicates that `Token` is provided with `Value` at this location in the logical tree. |
| `@ApplicationConfig` | Demonstrates that a fallback `EnvironmentInjector` should be used at this location. |
### Example app structure
The example application has a `FlowerService` provided in `root` with an `emoji` value of red hibiscus <code>🌺</code>.
<docs-code header="src/app/flower.service.ts" language="typescript">
@Injectable({
providedIn: 'root'
})
export class FlowerService {
emoji = '🌺';
}
</docs-code>
Consider an application with only an `AppComponent` and a `ChildComponent`.
The most basic rendered view would look like nested HTML elements such as the following:
<docs-code language="html">
<app-root> <!-- AppComponent selector -->
<app-child> <!-- ChildComponent selector -->
</app-child>
</app-root>
</docs-code>
However, behind the scenes, Angular uses a logical view representation as follows when resolving injection requests:
<docs-code language="html">
<app-root> <!-- AppComponent selector -->
<#VIEW>
<app-child> <!-- ChildComponent selector -->
<#VIEW>
</#VIEW>
</app-child>
</#VIEW>
</app-root>
</docs-code>
The `<#VIEW>` here represents an instance of a template.
Notice that each component has its own `<#VIEW>`.
Knowledge of this structure can inform how you provide and inject your services, and give you complete control of service visibility.
Now, consider that `<app-root>` injects the `FlowerService`:
<docs-code header="src/app/app.component.ts" language="typescript">
export class AppComponent {
constructor(public flower: FlowerService) {}
}
</docs-code>
Add a binding to the `<app-root>` template to visualize the result:
<docs-code header="src/app/app.component.html" language="html">
<p>Emoji from FlowerService: {{flower.emoji}}</p>
</docs-code>
The output in the view would be:
<docs-code language="shell">
Emoji from FlowerService: 🌺
</docs-code>
In the logical tree, this would be represented as follows:
<docs-code language="html" highlight="[[1],[2],[4]]">
<app-root @ApplicationConfig
@Inject(FlowerService) flower=>"🌺">
<#VIEW>
<p>Emoji from FlowerService: {{flower.emoji}} (🌺)</p>
<app-child>
<#VIEW>
</#VIEW>
</app-child>
</#VIEW>
</app-root>
</docs-code>
When `<app-root>` requests the `FlowerService`, it is the injector's job to resolve the `FlowerService` token.
The resolution of the token happens in two phases:
1. The injector determines the starting location in the logical tree and an ending location of the search.
The injector begins with the starting location and looks for the token at each view level in the logical tree.
If the token is found it is returned.
1. If the token is not found, the injector looks for the closest parent `EnvironmentInjector` to delegate the request to.
In the example case, the constraints are:
1. Start with `<#VIEW>` belonging to `<app-root>` and end with `<app-root>`.
* Normally the starting point for search is at the point of injection.
However, in this case `<app-root>` is a component. `@Component`s are special in that they also include their own `viewProviders`, which is why the search starts at `<#VIEW>` belonging to `<app-root>`.
This would not be the case for a directive matched at the same location.
* The ending location happens to be the same as the component itself, because it is the topmost component in this application.
1. The `EnvironmentInjector` provided by the `ApplicationConfig` acts as the fallback injector when the injection token can't be found in the `ElementInjector` hierarchies.
### Using the `providers` array
Now, in the `ChildComponent` class, add a provider for `FlowerService` to demonstrate more complex resolution rules in the upcoming sections:
<docs-code header="src/app/child.component.ts" language="typescript"
highlight="[[5,6],[10]]">
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
// use the providers array to provide a service
providers: [{ provide: FlowerService, useValue: { emoji: '🌻' } }]
})
export class ChildComponent {
// inject the service
constructor( public flower: FlowerService) { }
}
</docs-code>
Now that the `FlowerService` is provided in the `@Component()` decorator, when the `<app-child>` requests the service, the injector has only to look as far as the `ElementInjector` in the `<app-child>`.
It won't have to continue the search any further through the injector tree.
The next step is to add a binding to the `ChildComponent` template.
<docs-code header="src/app/child.component.html" language="html">
<p>Emoji from FlowerService: {{flower.emoji}}</p>
</docs-code>
To render the new values, add `<app-child>` to the bottom of the `AppComponent` template so the view also displays the sunflower:
<docs-code language="shell">
Child Component
Emoji from FlowerService: 🌻
</docs-code>
In the logical tree, this is represented as follows:
<docs-code language="html">
<app-root @ApplicationConfig
@Inject(FlowerService) flower=>"🌺">
<#VIEW>
<p>Emoji from FlowerService: {{flower.emoji}} (🌺)</p>
<app-child @Provide(FlowerService="🌻")
@Inject(FlowerService)=>"🌻"> <!-- search ends here -->
<#VIEW> <!-- search starts here -->
<h2>Child Component</h2>
<p>Emoji from FlowerService: {{flower.emoji}} (🌻)</p>
</#VIEW>
</app-child>
</#VIEW>
</app-root>
</docs-code>
When `<app-child>` requests the `FlowerService`, the injector begins its search at the `<#VIEW>` belonging to `<app-child>` \(`<#VIEW>` is included because it is injected from `@Component()`\) and ends with `<app-child>`.
In this case, the `FlowerService` is resolved in the `providers` array with sunflower <code>🌻</code> of the `<app-child>`.
The injector doesn't have to look any further in the injector tree.
It stops as soon as it finds the `FlowerService` and never sees the red hibiscus <code>🌺</code>.
### Using the `viewPr | {
"end_byte": 25301,
"start_byte": 17607,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/hierarchical-dependency-injection.md"
} |
angular/adev/src/content/guide/di/hierarchical-dependency-injection.md_25301_28944 | oviders` array
Use the `viewProviders` array as another way to provide services in the `@Component()` decorator.
Using `viewProviders` makes services visible in the `<#VIEW>`.
HELPFUL: The steps are the same as using the `providers` array, with the exception of using the `viewProviders` array instead.
For step-by-step instructions, continue with this section.
If you can set it up on your own, skip ahead to [Modifying service availability](#visibility-of-provided-tokens).
For demonstration, we are building an `AnimalService` to demonstrate `viewProviders`.
First, create an `AnimalService` with an `emoji` property of whale <code>🐳</code>:
<docs-code header="src/app/animal.service.ts" language="typescript">
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AnimalService {
emoji = '🐳';
}
</docs-code>
Following the same pattern as with the `FlowerService`, inject the `AnimalService` in the `AppComponent` class:
<docs-code header="src/app/app.component.ts" language="typescript" highlight="[4]">
export class AppComponent {
constructor(
public flower: FlowerService,
public animal: AnimalService) {}
}
</docs-code>
HELPFUL: You can leave all the `FlowerService` related code in place as it will allow a comparison with the `AnimalService`.
Add a `viewProviders` array and inject the `AnimalService` in the `<app-child>` class, too, but give `emoji` a different value.
Here, it has a value of dog <code>🐶</code>.
<docs-code header="src/app/child.component.ts" language="typescript"
highlight="[[7],[11]]">
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
// provide services
providers: [{ provide: FlowerService, useValue: { emoji: '🌻' } }],
viewProviders: [{ provide: AnimalService, useValue: { emoji: '🐶' } }]
})
export class ChildComponent {
// inject service
constructor( public flower: FlowerService, public animal: AnimalService) { }
...
}
</docs-code>
Add bindings to the `ChildComponent` and the `AppComponent` templates.
In the `ChildComponent` template, add the following binding:
<docs-code header="src/app/child.component.html" language="html">
<p>Emoji from AnimalService: {{animal.emoji}}</p>
</docs-code>
Additionally, add the same to the `AppComponent` template:
<docs-code header="src/app/app.component.html" language="html">
<p>Emoji from AnimalService: {{animal.emoji}}</p>s
</docs-code>
Now you should see both values in the browser:
<docs-code hideCopy language="shell">
AppComponent
Emoji from AnimalService: 🐳
Child Component
Emoji from AnimalService: 🐶
</docs-code>
The logic tree for this example of `viewProviders` is as follows:
<docs-code language="html">
<app-root @ApplicationConfig
@Inject(AnimalService) animal=>"🐳">
<#VIEW>
<app-child>
<#VIEW @Provide(AnimalService="🐶")
@Inject(AnimalService=>"🐶")>
<!-- ^^using viewProviders means AnimalService is available in <#VIEW>-->
<p>Emoji from AnimalService: {{animal.emoji}} (🐶)</p>
</#VIEW>
</app-child>
</#VIEW>
</app-root>
</docs-code>
Just as with the `FlowerService` example, the `AnimalService` is provided in the `<app-child>` `@Component()` decorator.
This means that since the injector first looks in the `ElementInjector` of the component, it finds the `AnimalService` value of dog <code>🐶</code>.
It doesn't need to continue searching the `ElementInjector` tree, nor does it need to search the `ModuleInjector`.
### `providers` vs. `viewProvi | {
"end_byte": 28944,
"start_byte": 25301,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/hierarchical-dependency-injection.md"
} |
angular/adev/src/content/guide/di/hierarchical-dependency-injection.md_28944_35856 | ders`
The `viewProviders` field is conceptually similar to `providers`, but there is one notable difference.
Configured providers in `viewProviders` are not visible to projected content that ends up as a logical children of the component.
To see the difference between using `providers` and `viewProviders`, add another component to the example and call it `InspectorComponent`.
`InspectorComponent` will be a child of the `ChildComponent`.
In `inspector.component.ts`, inject the `FlowerService` and `AnimalService` in the constructor:
<docs-code header="src/app/inspector/inspector.component.ts" language="typescript">
export class InspectorComponent {
constructor(public flower: FlowerService, public animal: AnimalService) { }
}
</docs-code>
You do not need a `providers` or `viewProviders` array.
Next, in `inspector.component.html`, add the same markup from previous components:
<docs-code header="src/app/inspector/inspector.component.html" language="html">
<p>Emoji from FlowerService: {{flower.emoji}}</p>
<p>Emoji from AnimalService: {{animal.emoji}}</p>
</docs-code>
Remember to add the `InspectorComponent` to the `ChildComponent` `imports` array.
<docs-code header="src/app/child/child.component.ts" language="typescript"
highlight="[3]">
@Component({
...
imports: [InspectorComponent]
})
</docs-code>
Next, add the following to `child.component.html`:
<docs-code header="src/app/child/child.component.html" language="html"
highlight="[3,9]">
...
<div class="container">
<h3>Content projection</h3>
<ng-content></ng-content>
</div>
<h3>Inside the view</h3>
<app-inspector></app-inspector>
</docs-code>
`<ng-content>` allows you to project content, and `<app-inspector>` inside the `ChildComponent` template makes the `InspectorComponent` a child component of `ChildComponent`.
Next, add the following to `app.component.html` to take advantage of content projection.
<docs-code header="src/app/app.component.html" language="html" highlight="[2]">
<app-child>
<app-inspector></app-inspector>
</app-child>
</docs-code>
The browser now renders the following, omitting the previous examples for brevity:
<docs-code hideCopy language="shell">
...
Content projection
Emoji from FlowerService: 🌻
Emoji from AnimalService: 🐳
Emoji from FlowerService: 🌻
Emoji from AnimalService: 🐶
</docs-code>
These four bindings demonstrate the difference between `providers` and `viewProviders`.
Remember that the dog emoji <code>🐶</code> is declared inside the `<#VIEW>` of `ChildComponent` and isn't visible to the projected content.
Instead, the projected content sees the whale <code>🐳</code>.
However, in the next output section though, the `InspectorComponent` is an actual child component of `ChildComponent`, `InspectorComponent` is inside the `<#VIEW>`, so when it asks for the `AnimalService`, it sees the dog <code>🐶</code>.
The `AnimalService` in the logical tree would look like this:
<docs-code language="html">
<app-root @ApplicationConfig
@Inject(AnimalService) animal=>"🐳">
<#VIEW>
<app-child>
<#VIEW @Provide(AnimalService="🐶")
@Inject(AnimalService=>"🐶")>
<!-- ^^using viewProviders means AnimalService is available in <#VIEW>-->
<p>Emoji from AnimalService: {{animal.emoji}} (🐶)</p>
<div class="container">
<h3>Content projection</h3>
<app-inspector @Inject(AnimalService) animal=>"🐳">
<p>Emoji from AnimalService: {{animal.emoji}} (🐳)</p>
</app-inspector>
</div>
<app-inspector>
<#VIEW @Inject(AnimalService) animal=>"🐶">
<p>Emoji from AnimalService: {{animal.emoji}} (🐶)</p>
</#VIEW>
</app-inspector>
</#VIEW>
</app-child>
</#VIEW>
</app-root>
</docs-code>
The projected content of `<app-inspector>` sees the whale <code>🐳</code>, not the dog <code>🐶</code>, because the dog <code>🐶</code> is inside the `<app-child>` `<#VIEW>`.
The `<app-inspector>` can only see the dog <code>🐶</code> if it is also within the `<#VIEW>`.
### Visibility of provided tokens
Visibility decorators influence where the search for the injection token begins and ends in the logic tree.
To do this, place visibility decorators at the point of injection, that is, the `constructor()`, rather than at a point of declaration.
To alter where the injector starts looking for `FlowerService`, add `@SkipSelf()` to the `<app-child>` `@Inject` declaration where `FlowerService` is injected.
This declaration is in the `<app-child>` constructor as shown in `child.component.ts`:
<docs-code language="typescript">
constructor(@SkipSelf() public flower: FlowerService) { }
</docs-code>
With `@SkipSelf()`, the `<app-child>` injector doesn't look to itself for the `FlowerService`.
Instead, the injector starts looking for the `FlowerService` at the `ElementInjector` of the `<app-root>`, where it finds nothing.
Then, it goes back to the `<app-child>` `ModuleInjector` and finds the red hibiscus <code>🌺</code> value, which is available because `<app-child>` and `<app-root>` share the same `ModuleInjector`.
The UI renders the following:
<docs-code hideCopy language="shell">
Emoji from FlowerService: 🌺
</docs-code>
In a logical tree, this same idea might look like this:
<docs-code language="html">
<app-root @ApplicationConfig
@Inject(FlowerService) flower=>"🌺">
<#VIEW>
<app-child @Provide(FlowerService="🌻")>
<#VIEW @Inject(FlowerService, SkipSelf)=>"🌺">
<!-- With SkipSelf, the injector looks to the next injector up the tree (app-root) -->
</#VIEW>
</app-child>
</#VIEW>
</app-root>
</docs-code>
Though `<app-child>` provides the sunflower <code>🌻</code>, the application renders the red hibiscus <code>🌺</code> because `@SkipSelf()` causes the current injector (`app-child`) to skip itself and look to its parent.
If you now add `@Host()` (in addition to the `@SkipSelf()`), the result will be `null`.
This is because `@Host()` limits the upper bound of the search to the `app-child` `<#VIEW>`.
Here's the idea in the logical tree:
<docs-code language="html">
<app-root @ApplicationConfig
@Inject(FlowerService) flower=>"🌺">
<#VIEW> <!-- end search here with null-->
<app-child @Provide(FlowerService="🌻")> <!-- start search here -->
<#VIEW @Inject(FlowerService, @SkipSelf, @Host, @Optional)=>null>
</#VIEW>
</app-parent>
</#VIEW>
</app-root>
</docs-code>
Here, the services and their values are the same, but `@Host()` stops the injector from looking any further than the `<#VIEW>` for `FlowerService`, so it doesn't find it and returns `null`.
### `@SkipSelf()` and `viewPro | {
"end_byte": 35856,
"start_byte": 28944,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/hierarchical-dependency-injection.md"
} |
angular/adev/src/content/guide/di/hierarchical-dependency-injection.md_35856_40775 | viders`
Remember, `<app-child>` provides the `AnimalService` in the `viewProviders` array with the value of dog <code>🐶</code>.
Because the injector has only to look at the `ElementInjector` of the `<app-child>` for the `AnimalService`, it never sees the whale <code>🐳</code>.
As in the `FlowerService` example, if you add `@SkipSelf()` to the constructor for the `AnimalService`, the injector won't look in the `ElementInjector` of the current `<app-child>` for the `AnimalService`.
Instead, the injector will begin at the `<app-root>` `ElementInjector`.
<docs-code language="typescript" highlight="[6]">
@Component({
standalone: true,
selector: 'app-child',
…
viewProviders: [
{ provide: AnimalService, useValue: { emoji: '🐶' } },
],
})
</docs-code>
The logical tree looks like this with `@SkipSelf()` in `<app-child>`:
<docs-code language="html">
<app-root @ApplicationConfig
@Inject(AnimalService=>"🐳")>
<#VIEW><!-- search begins here -->
<app-child>
<#VIEW @Provide(AnimalService="🐶")
@Inject(AnimalService, SkipSelf=>"🐳")>
<!--Add @SkipSelf -->
</#VIEW>
</app-child>
</#VIEW>
</app-root>
</docs-code>
With `@SkipSelf()` in the `<app-child>`, the injector begins its search for the `AnimalService` in the `<app-root>` `ElementInjector` and finds whale <code>🐳</code>.
### `@Host()` and `viewProviders`
If you just use `@Host()` for the injection of `AnimalService`, the result is dog <code>🐶</code> because the injector finds the `AnimalService` in the `<app-child>` `<#VIEW>` itself.
The `ChildComponent` configures the `viewProviders` so that the dog emoji is provided as `AnimalService` value.
You can also see `@Host()` in the constructor:
<docs-code language="typescript" highlight="[[6],[10]]">
@Component({
standalone: true
selector: 'app-child',
…
viewProviders: [
{ provide: AnimalService, useValue: { emoji: '🐶' } },
]
})
export class ChildComponent {
constructor(@Host() public animal: AnimalService) { }
}
</docs-code>
`@Host()` causes the injector to look until it encounters the edge of the `<#VIEW>`.
<docs-code language="html">
<app-root @ApplicationConfig
@Inject(AnimalService=>"🐳")>
<#VIEW>
<app-child>
<#VIEW @Provide(AnimalService="🐶")
@Inject(AnimalService, @Host=>"🐶")> <!-- @Host stops search here -->
</#VIEW>
</app-child>
</#VIEW>
</app-root>
</docs-code>
Add a `viewProviders` array with a third animal, hedgehog <code>🦔</code>, to the `app.component.ts` `@Component()` metadata:
<docs-code language="typescript" highlight="[7]">
@Component({
standalone: true,
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
viewProviders: [
{ provide: AnimalService, useValue: { emoji: '🦔' } },
],
})
</docs-code>
Next, add `@SkipSelf()` along with `@Host()` to the constructor for the `AnimalService` injection in `child.component.ts`.
Here are `@Host()` and `@SkipSelf()` in the `<app-child>` constructor:
<docs-code language="typescript" highlight="[4]">
export class ChildComponent {
constructor(
@Host() @SkipSelf() public animal: AnimalService) { }
}
</docs-code>
<!-- TODO: This requires a rework. It seems not well explained what `viewProviders`/`injectors` is here
and how `@Host()` works.
-->
When `@Host()` and `@SkipSelf()` were applied to the `FlowerService`, which is in the `providers` array, the result was `null` because `@SkipSelf()` starts its search in the `<app-child>` injector, but `@Host()` stops searching at `<#VIEW>` —where there is no `FlowerService`
In the logical tree, you can see that the `FlowerService` is visible in `<app-child>`, not its `<#VIEW>`.
However, the `AnimalService`, which is provided in the `AppComponent` `viewProviders` array, is visible.
The logical tree representation shows why this is:
<docs-code language="html">
<app-root @ApplicationConfig
@Inject(AnimalService=>"🐳")>
<#VIEW @Provide(AnimalService="🦔")
@Inject(AnimalService, @Optional)=>"🦔">
<!-- ^^@SkipSelf() starts here, @Host() stops here^^ -->
<app-child>
<#VIEW @Provide(AnimalService="🐶")
@Inject(AnimalService, @SkipSelf, @Host, @Optional)=>"🦔">
<!-- Add @SkipSelf ^^-->
</#VIEW>
</app-child>
</#VIEW>
</app-root>
</docs-code>
`@SkipSelf()`, causes the injector to start its search for the `AnimalService` at the `<app-root>`, not the `<app-child>`, where the request originates, and `@Host()` stops the search at the `<app-root>` `<#VIEW>`.
Since `AnimalService` is provided by way of the `viewProviders` array, the injector finds hedgehog <code>🦔</code> in the `<#VIEW>`.
## Example: `ElementInjector` use ca | {
"end_byte": 40775,
"start_byte": 35856,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/hierarchical-dependency-injection.md"
} |
angular/adev/src/content/guide/di/hierarchical-dependency-injection.md_40775_49721 | 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 | {
"end_byte": 49721,
"start_byte": 40775,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/hierarchical-dependency-injection.md"
} |
angular/adev/src/content/guide/di/hierarchical-dependency-injection.md_49721_49870 | cs-pill-row>
<docs-pill href="/guide/di/dependency-injection-providers" title="DI Providers"/>
</docs-pill-row> | {
"end_byte": 49870,
"start_byte": 49721,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/hierarchical-dependency-injection.md"
} |
angular/adev/src/content/guide/di/BUILD.bazel_0_379 | load("//adev/shared-docs:index.bzl", "generate_guides")
generate_guides(
name = "di",
srcs = glob([
"*.md",
]),
data = [
"//adev/src/assets/images:dependency_injection.svg",
"//adev/src/content/examples/resolution-modifiers:src/app/self/self.component.ts",
],
mermaid_blocks = True,
visibility = ["//adev:__subpackages__"],
)
| {
"end_byte": 379,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/BUILD.bazel"
} |
angular/adev/src/content/guide/di/lightweight-injection-tokens.md_0_9579 | # Optimizing client application size with lightweight injection tokens
This page provides a conceptual overview of a dependency injection technique that is recommended for library developers.
Designing your library with *lightweight injection tokens* helps optimize the bundle size of client applications that use your library.
You can manage the dependency structure among your components and injectable services to optimize bundle size by using tree-shakable providers.
This normally ensures that if a provided component or service is never actually used by the application, the compiler can remove its code from the bundle.
Due to the way Angular stores injection tokens, it is possible that such an unused component or service can end up in the bundle anyway.
This page describes a dependency injection design pattern that supports proper tree-shaking by using lightweight injection tokens.
The lightweight injection token design pattern is especially important for library developers.
It ensures that when an application uses only some of your library's capabilities, the unused code can be eliminated from the client's application bundle.
When an application uses your library, there might be some services that your library supplies which the client application doesn't use.
In this case, the application developer should expect that service to be tree-shaken, and not contribute to the size of the compiled application.
Because the application developer cannot know about or remedy a tree-shaking problem in the library, it is the responsibility of the library developer to do so.
To prevent the retention of unused components, your library should use the lightweight injection token design pattern.
## When tokens are retained
To better explain the condition under which token retention occurs, consider a library that provides a library-card component.
This component contains a body and can contain an optional header:
<docs-code language="html">
<lib-card>;
<lib-header>…</lib-header>;
</lib-card>;
</docs-code>
In a likely implementation, the `<lib-card>` component uses `@ContentChild()` or `@ContentChildren()` to get `<lib-header>` and `<lib-body>`, as in the following:
<docs-code language="typescript" highlight="[12]">
@Component({
selector: 'lib-header',
…,
})
class LibHeaderComponent {}
@Component({
selector: 'lib-card',
…,
})
class LibCardComponent {
@ContentChild(LibHeaderComponent) header: LibHeaderComponent|null = null;
}
</docs-code>
Because `<lib-header>` is optional, the element can appear in the template in its minimal form, `<lib-card></lib-card>`.
In this case, `<lib-header>` is not used and you would expect it to be tree-shaken, but that is not what happens.
This is because `LibCardComponent` actually contains two references to the `LibHeaderComponent`:
<docs-code language="typescript">
@ContentChild(LibHeaderComponent) header: LibHeaderComponent;
</docs-code>
* One of these reference is in the *type position*-- that is, it specifies `LibHeaderComponent` as a type: `header: LibHeaderComponent;`.
* The other reference is in the *value position*-- that is, LibHeaderComponent is the value of the `@ContentChild()` parameter decorator: `@ContentChild(LibHeaderComponent)`.
The compiler handles token references in these positions differently:
* The compiler erases *type position* references after conversion from TypeScript, so they have no impact on tree-shaking.
* The compiler must keep *value position* references at runtime, which **prevents** the component from being tree-shaken.
In the example, the compiler retains the `LibHeaderComponent` token that occurs in the value position.
This prevents the referenced component from being tree-shaken, even if the application does not actually use `<lib-header>` anywhere.
If `LibHeaderComponent` 's code, template, and styles combine to become too large, including it unnecessarily can significantly increase the size of the client application.
## When to use the lightweight injection token pattern
The tree-shaking problem arises when a component is used as an injection token.
There are two cases when that can happen:
* The token is used in the value position of a [content query](guide/components/queries#content-queries).
* The token is used as a type specifier for constructor injection.
In the following example, both uses of the `OtherComponent` token cause retention of `OtherComponent`, preventing it from being tree-shaken when it is not used:
<docs-code language="typescript" highlight="[[2],[4]]">
class MyComponent {
constructor(@Optional() other: OtherComponent) {}
@ContentChild(OtherComponent) other: OtherComponent|null;
}
</docs-code>
Although tokens used only as type specifiers are removed when converted to JavaScript, all tokens used for dependency injection are needed at runtime.
These effectively change `constructor(@Optional() other: OtherComponent)` to `constructor(@Optional() @Inject(OtherComponent) other)`.
The token is now in a value position, which causes the tree-shaker to keep the reference.
HELPFUL: Libraries should use [tree-shakable providers](guide/di/dependency-injection#providing-dependency) for all services, providing dependencies at the root level rather than in components or modules.
## Using lightweight injection tokens
The lightweight injection token design pattern consists of using a small abstract class as an injection token, and providing the actual implementation at a later stage.
The abstract class is retained, not tree-shaken, but it is small and has no material impact on the application size.
The following example shows how this works for the `LibHeaderComponent`:
<docs-code language="typescript" language="[[1],[6],[17]]">
abstract class LibHeaderToken {}
@Component({
selector: 'lib-header',
providers: [
{provide: LibHeaderToken, useExisting: LibHeaderComponent}
]
…,
})
class LibHeaderComponent extends LibHeaderToken {}
@Component({
selector: 'lib-card',
…,
})
class LibCardComponent {
@ContentChild(LibHeaderToken) header: LibHeaderToken|null = null;
}
</docs-code>
In this example, the `LibCardComponent` implementation no longer refers to `LibHeaderComponent` in either the type position or the value position.
This lets full tree-shaking of `LibHeaderComponent` take place.
The `LibHeaderToken` is retained, but it is only a class declaration, with no concrete implementation.
It is small and does not materially impact the application size when retained after compilation.
Instead, `LibHeaderComponent` itself implements the abstract `LibHeaderToken` class.
You can safely use that token as the provider in the component definition, allowing Angular to correctly inject the concrete type.
To summarize, the lightweight injection token pattern consists of the following:
1. A lightweight injection token that is represented as an abstract class.
1. A component definition that implements the abstract class.
1. Injection of the lightweight pattern, using `@ContentChild()` or `@ContentChildren()`.
1. A provider in the implementation of the lightweight injection token which associates the lightweight injection token with the implementation.
### Use the lightweight injection token for API definition
A component that injects a lightweight injection token might need to invoke a method in the injected class.
The token is now an abstract class. Since the injectable component implements that class, you must also declare an abstract method in the abstract lightweight injection token class.
The implementation of the method, with all its code overhead, resides in the injectable component that can be tree-shaken.
This lets the parent communicate with the child, if it is present, in a type-safe manner.
For example, the `LibCardComponent` now queries `LibHeaderToken` rather than `LibHeaderComponent`.
The following example shows how the pattern lets `LibCardComponent` communicate with the `LibHeaderComponent` without actually referring to `LibHeaderComponent`:
<docs-code language="typescript" highlight="[[3],[13,16],[27]]">
abstract class LibHeaderToken {
abstract doSomething(): void;
}
@Component({
selector: 'lib-header',
providers: [
{provide: LibHeaderToken, useExisting: LibHeaderComponent}
]
…,
})
class LibHeaderComponent extends LibHeaderToken {
doSomething(): void {
// Concrete implementation of `doSomething`
}
}
@Component({
selector: 'lib-card',
…,
})
class LibCardComponent implement AfterContentInit {
@ContentChild(LibHeaderToken) header: LibHeaderToken|null = null;
ngAfterContentInit(): void {
if (this.header !== null) {
this.header?.doSomething();
}
}
}
</docs-code>
In this example, the parent queries the token to get the child component, and stores the resulting component reference if it is present.
Before calling a method in the child, the parent component checks to see if the child component is present.
If the child component has been tree-shaken, there is no runtime reference to it, and no call to its method.
### Naming your lightweight injection token
Lightweight injection tokens are only useful with components.
The Angular style guide suggests that you name components using the "Component" suffix.
The example "LibHeaderComponent" follows this convention.
You should maintain the relationship between the component and its token while still distinguishing between them.
The recommended style is to use the component base name with the suffix "`Token`" to name your lightweight injection tokens: "`LibHeaderToken`."
| {
"end_byte": 9579,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/di/lightweight-injection-tokens.md"
} |
angular/adev/src/content/guide/forms/overview.md_0_6241 | <docs-decorative-header title="Forms in Angular" imgSrc="adev/src/assets/images/overview.svg"> <!-- markdownlint-disable-line -->
Handling user input with forms is the cornerstone of many common applications.
</docs-decorative-header>
Applications use forms to enable users to log in, to update a profile, to enter sensitive information, and to perform many other data-entry tasks.
Angular provides two different approaches to handling user input through forms: reactive and template-driven.
Both capture user input events from the view, validate the user input, create a form model and data model to update, and provide a way to track changes.
This guide provides information to help you decide which type of form works best for your situation.
It introduces the common building blocks used by both approaches.
It also summarizes the key differences between the two approaches, and demonstrates those differences in the context of setup, data flow, and testing.
## Choosing an approach
Reactive forms and template-driven forms process and manage form data differently.
Each approach offers different advantages.
| Forms | Details |
|:--- |:--- |
| Reactive forms | Provide direct, explicit access to the underlying form's object model. Compared to template-driven forms, they are more robust: they're more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building your application, use reactive forms. |
| Template-driven forms | Rely on directives in the template to create and manipulate the underlying object model. They are useful for adding a simple form to an app, such as an email list signup form. They're straightforward to add to an app, but they don't scale as well as reactive forms. If you have very basic form requirements and logic that can be managed solely in the template, template-driven forms could be a good fit. |
### Key differences
The following table summarizes the key differences between reactive and template-driven forms.
| | Reactive | Template-driven |
|:--- |:--- |:--- |
| [Setup of form model](#setting-up-the-form-model) | Explicit, created in component class | Implicit, created by directives |
| [Data model](#mutability-of-the-data-model) | Structured and immutable | Unstructured and mutable |
| [Data flow](#data-flow-in-forms) | Synchronous | Asynchronous |
| [Form validation](#form-validation) | Functions | Directives |
### Scalability
If forms are a central part of your application, scalability is very important.
Being able to reuse form models across components is critical.
Reactive forms are more scalable than template-driven forms.
They provide direct access to the underlying form API, and use [synchronous data flow](#data-flow-in-reactive-forms) between the view and the data model, which makes creating large-scale forms easier.
Reactive forms require less setup for testing, and testing does not require deep understanding of change detection to properly test form updates and validation.
Template-driven forms focus on simple scenarios and are not as reusable.
They abstract away the underlying form API, and use [asynchronous data flow](#data-flow-in-template-driven-forms) between the view and the data model.
The abstraction of template-driven forms also affects testing.
Tests are deeply reliant on manual change detection execution to run properly, and require more setup.
## Setting up the form model
Both reactive and template-driven forms track value changes between the form input elements that users interact with and the form data in your component model.
The two approaches share underlying building blocks, but differ in how you create and manage the common form-control instances.
### Common form foundation classes
Both reactive and template-driven forms are built on the following base classes.
| Base classes | Details |
|:--- |:--- |
| `FormControl` | Tracks the value and validation status of an individual form control. |
| `FormGroup` | Tracks the same values and status for a collection of form controls. |
| `FormArray` | Tracks the same values and status for an array of form controls. |
| `ControlValueAccessor` | Creates a bridge between Angular `FormControl` instances and built-in DOM elements. |
### Setup in reactive forms
With reactive forms, you define the form model directly in the component class.
The `[formControl]` directive links the explicitly created `FormControl` instance to a specific form element in the view, using an internal value accessor.
The following component implements an input field for a single control, using reactive forms.
In this example, the form model is the `FormControl` instance.
<docs-code path="adev/src/content/examples/forms-overview/src/app/reactive/favorite-color/favorite-color.component.ts"/>
IMPORTANT: In reactive forms, the form model is the source of truth; it provides the value and status of the form element at any given point in time, through the `[formControl]` directive on the `<input>` element.
### Setup in template-driven forms
In template-driven forms, the form model is implicit, rather than explicit.
The directive `NgModel` creates and manages a `FormControl` instance for a given form element.
The following component implements the same input field for a single control, using template-driven forms.
<docs-code path="adev/src/content/examples/forms-overview/src/app/template/favorite-color/favorite-color.component.ts"/>
IMPORTANT: In a template-driven form the source of truth is the template. The `NgModel` directive automatically manages the `FormControl` instance for you.
| {
"end_byte": 6241,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/overview.md"
} |
angular/adev/src/content/guide/forms/overview.md_6241_14515 | ## 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).
| {
"end_byte": 14515,
"start_byte": 6241,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/overview.md"
} |
angular/adev/src/content/guide/forms/overview.md_14515_19165 | ## Testing
Testing plays a large part in complex applications.
A simpler testing strategy is useful when validating that your forms function correctly.
Reactive forms and template-driven forms have different levels of reliance on rendering the UI to perform assertions based on form control and form field changes.
The following examples demonstrate the process of testing forms with reactive and template-driven forms.
### Testing reactive forms
Reactive forms provide a relatively straightforward testing strategy because they provide synchronous access to the form and data models, and they can be tested without rendering the UI.
In these tests, status and data are queried and manipulated through the control without interacting with the change detection cycle.
The following tests use the favorite-color components from previous examples to verify the view-to-model and model-to-view data flows for a reactive form.
<!--todo: make consistent with other topics -->
#### Verifying view-to-model data flow
The first example performs the following steps to verify the view-to-model data flow.
1. Query the view for the form input element, and create a custom "input" event for the test.
1. Set the new value for the input to *Red*, and dispatch the "input" event on the form input element.
1. Assert that the component's `favoriteColorControl` value matches the value from the input.
<docs-code header="Favorite color test - view to model" path="adev/src/content/examples/forms-overview/src/app/reactive/favorite-color/favorite-color.component.spec.ts" visibleRegion="view-to-model"/>
The next example performs the following steps to verify the model-to-view data flow.
1. Use the `favoriteColorControl`, a `FormControl` instance, to set the new value.
1. Query the view for the form input element.
1. Assert that the new value set on the control matches the value in the input.
<docs-code header="Favorite color test - model to view" path="adev/src/content/examples/forms-overview/src/app/reactive/favorite-color/favorite-color.component.spec.ts" visibleRegion="model-to-view"/>
### Testing template-driven forms
Writing tests with template-driven forms requires a detailed knowledge of the change detection process and an understanding of how directives run on each cycle to ensure that elements are queried, tested, or changed at the correct time.
The following tests use the favorite color components mentioned earlier to verify the data flows from view to model and model to view for a template-driven form.
The following test verifies the data flow from view to model.
<docs-code header="Favorite color test - view to model" path="adev/src/content/examples/forms-overview/src/app/template/favorite-color/favorite-color.component.spec.ts" visibleRegion="view-to-model"/>
Here are the steps performed in the view to model test.
1. Query the view for the form input element, and create a custom "input" event for the test.
1. Set the new value for the input to *Red*, and dispatch the "input" event on the form input element.
1. Run change detection through the test fixture.
1. Assert that the component `favoriteColor` property value matches the value from the input.
The following test verifies the data flow from model to view.
<docs-code header="Favorite color test - model to view" path="adev/src/content/examples/forms-overview/src/app/template/favorite-color/favorite-color.component.spec.ts" visibleRegion="model-to-view"/>
Here are the steps performed in the model to view test.
1. Use the component instance to set the value of the `favoriteColor` property.
1. Run change detection through the test fixture.
1. Use the `tick()` method to simulate the passage of time within the `fakeAsync()` task.
1. Query the view for the form input element.
1. Assert that the input value matches the value of the `favoriteColor` property in the component instance.
## Next steps
To learn more about reactive forms, see the following guides:
<docs-pill-row>
<docs-pill href="guide/forms/reactive-forms" title="Reactive forms"/>
<docs-pill href="guide/forms/form-validation#validating-input-in-reactive-forms" title="Form validation"/>
<docs-pill href="guide/forms/dynamic-forms" title="Dynamic forms"/>
</docs-pill-row>
To learn more about template-driven forms, see the following guides:
<docs-pill-row>
<docs-pill href="guide/forms/template-driven-forms" title="Template Driven Forms tutorial" />
<docs-pill href="guide/forms/form-validation#validating-input-in-template-driven-forms" title="Form validation" />
<docs-pill href="api/forms/NgForm" title="NgForm directive API reference" />
</docs-pill-row>
| {
"end_byte": 19165,
"start_byte": 14515,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/overview.md"
} |
angular/adev/src/content/guide/forms/dynamic-forms.md_0_8848 | # Building dynamic forms
Many forms, such as questionnaires, can be very similar to one another in format and intent.
To make it faster and easier to generate different versions of such a form, you can create a _dynamic form template_ based on metadata that describes the business object model.
Then, use the template to generate new forms automatically, according to changes in the data model.
The technique is particularly useful when you have a type of form whose content must change frequently to meet rapidly changing business and regulatory requirements.
A typical use-case is a questionnaire.
You might need to get input from users in different contexts.
The format and style of the forms a user sees should remain constant, while the actual questions you need to ask vary with the context.
In this tutorial you will build a dynamic form that presents a basic questionnaire.
You build an online application for heroes seeking employment.
The agency is constantly tinkering with the application process, but by using the dynamic form
you can create the new forms on the fly without changing the application code.
The tutorial walks you through the following steps.
1. Enable reactive forms for a project.
1. Establish a data model to represent form controls.
1. Populate the model with sample data.
1. Develop a component to create form controls dynamically.
The form you create uses input validation and styling to improve the user experience.
It has a Submit button that is only enabled when all user input is valid, and flags invalid input with color coding and error messages.
The basic version can evolve to support a richer variety of questions, more graceful rendering, and superior user experience.
## Enable reactive forms for your project
Dynamic forms are based on reactive forms.
To give the application access reactive forms directives, import `ReactiveFormsModule` from the `@angular/forms` library into the necessary components.
The following code from the example shows the setup in the root module.
<docs-code-multifile>
<docs-code header="dynamic-form.component.ts" path="adev/src/content/examples/dynamic-form/src/app/dynamic-form.component.ts"/>
<docs-code header="dynamic-form-question.component.ts" path="adev/src/content/examples/dynamic-form/src/app/dynamic-form-question.component.ts"/>
</docs-code-multifile>
## Create a form object model
A dynamic form requires an object model that can describe all scenarios needed by the form functionality.
The example hero-application form is a set of questions — that is, each control in the form must ask a question and accept an answer.
The data model for this type of form must represent a question.
The example includes the `DynamicFormQuestionComponent`, which defines a question as the fundamental object in the model.
The following `QuestionBase` is a base class for a set of controls that can represent the question and its answer in the form.
<docs-code header="src/app/question-base.ts" path="adev/src/content/examples/dynamic-form/src/app/question-base.ts"/>
### Define control classes
From this base, the example derives two new classes, `TextboxQuestion` and `DropdownQuestion`, that represent different control types.
When you create the form template in the next step, you instantiate these specific question types in order to render the appropriate controls dynamically.
The `TextboxQuestion` control type is represented in a form template using an `<input>` element. It presents a question and lets users enter input. The `type` attribute of the element is defined based on the `type` field specified in the `options` argument (for example `text`, `email`, `url`).
<docs-code header="question-textbox.ts" path="adev/src/content/examples/dynamic-form/src/app/question-textbox.ts"/>
The `DropdownQuestion` control type presents a list of choices in a select box.
<docs-code header="question-dropdown.ts" path="adev/src/content/examples/dynamic-form/src/app/question-dropdown.ts"/>
### Compose form groups
A dynamic form uses a service to create grouped sets of input controls, based on the form model.
The following `QuestionControlService` collects a set of `FormGroup` instances that consume the metadata from the question model.
You can specify default values and validation rules.
<docs-code header="src/app/question-control.service.ts" path="adev/src/content/examples/dynamic-form/src/app/question-control.service.ts"/>
## Compose dynamic form contents
The dynamic form itself is represented by a container component, which you add in a later step.
Each question is represented in the form component's template by an `<app-question>` tag, which matches an instance of `DynamicFormQuestionComponent`.
The `DynamicFormQuestionComponent` is responsible for rendering the details of an individual question based on values in the data-bound question object.
The form relies on a [`[formGroup]` directive](api/forms/FormGroupDirective "API reference") to connect the template HTML to the underlying control objects.
The `DynamicFormQuestionComponent` creates form groups and populates them with controls defined in the question model, specifying display and validation rules.
<docs-code-multifile>
<docs-code header="dynamic-form-question.component.html" path="adev/src/content/examples/dynamic-form/src/app/dynamic-form-question.component.html"/>
<docs-code header="dynamic-form-question.component.ts" path="adev/src/content/examples/dynamic-form/src/app/dynamic-form-question.component.ts"/>
</docs-code-multifile>
The goal of the `DynamicFormQuestionComponent` is to present question types defined in your model.
You only have two types of questions at this point but you can imagine many more.
The `ngSwitch` statement in the template determines which type of question to display.
The switch uses directives with the [`formControlName`](api/forms/FormControlName "FormControlName directive API reference") and [`formGroup`](api/forms/FormGroupDirective "FormGroupDirective API reference") selectors.
Both directives are defined in `ReactiveFormsModule`.
### Supply data
Another service is needed to supply a specific set of questions from which to build an individual form.
For this exercise you create the `QuestionService` to supply this array of questions from the hard-coded sample data.
In a real-world app, the service might fetch data from a backend system.
The key point, however, is that you control the hero job-application questions entirely through the objects returned from `QuestionService`.
To maintain the questionnaire as requirements change, you only need to add, update, and remove objects from the `questions` array.
The `QuestionService` supplies a set of questions in the form of an array bound to `@Input()` questions.
<docs-code header="src/app/question.service.ts" path="adev/src/content/examples/dynamic-form/src/app/question.service.ts"/>
## Create a dynamic form template
The `DynamicFormComponent` component is the entry point and the main container for the form, which is represented using the `<app-dynamic-form>` in a template.
The `DynamicFormComponent` component presents a list of questions by binding each one to an `<app-question>` element that matches the `DynamicFormQuestionComponent`.
<docs-code-multifile>
<docs-code header="dynamic-form.component.html" path="adev/src/content/examples/dynamic-form/src/app/dynamic-form.component.html"/>
<docs-code header="dynamic-form.component.ts" path="adev/src/content/examples/dynamic-form/src/app/dynamic-form.component.ts"/>
</docs-code-multifile>
### Display the form
To display an instance of the dynamic form, the `AppComponent` shell template passes the `questions` array returned by the `QuestionService` to the form container component, `<app-dynamic-form>`.
<docs-code header="app.component.ts" path="adev/src/content/examples/dynamic-form/src/app/app.component.ts"/>
This separation of model and data lets you repurpose the components for any type of survey, as long as it's compatible with the _question_ object model.
### Ensuring valid data
The form template uses dynamic data binding of metadata to render the form without making any hardcoded assumptions about specific questions.
It adds both control metadata and validation criteria dynamically.
To ensure valid input, the _Save_ button is disabled until the form is in a valid state.
When the form is valid, click _Save_ and the application renders the current form values as JSON.
The following figure shows the final form.
<img alt="Dynamic-Form" src="assets/images/guide/dynamic-form/dynamic-form.png">
## Next steps
<docs-pill-row>
<docs-pill title="Validating form input" href="guide/forms/reactive-forms#validating-form-input" />
<docs-pill title="Form validation guide" href="guide/forms/form-validation" />
</docs-pill-row>
| {
"end_byte": 8848,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/dynamic-forms.md"
} |
angular/adev/src/content/guide/forms/form-validation.md_0_9567 | # Validating form input
You can improve overall data quality by validating user input for accuracy and completeness.
This page shows how to validate user input from the UI and display useful validation messages, in both reactive and template-driven forms.
## Validating input in template-driven forms
To add validation to a template-driven form, you add the same validation attributes as you would with [native HTML form validation](https://developer.mozilla.org/docs/Web/Guide/HTML/HTML5/Constraint_validation).
Angular uses directives to match these attributes with validator functions in the framework.
Every time the value of a form control changes, Angular runs validation and generates either a list of validation errors that results in an `INVALID` status, or null, which results in a VALID status.
You can then inspect the control's state by exporting `ngModel` to a local template variable.
The following example exports `NgModel` into a variable called `name`:
<docs-code header="template/actor-form-template.component.html (name)" path="adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.html" visibleRegion="name-with-error-msg"/>
Notice the following features illustrated by the example.
* The `<input>` element carries the HTML validation attributes: `required` and `minlength`.
It also carries a custom validator directive, `forbiddenName`.
For more information, see the [Custom validators](#defining-custom-validators) section.
* `#name="ngModel"` exports `NgModel` into a local variable called `name`.
`NgModel` mirrors many of the properties of its underlying `FormControl` instance, so you can use this in the template to check for control states such as `valid` and `dirty`.
For a full list of control properties, see the [AbstractControl](api/forms/AbstractControl) API reference.
* The `*ngIf` on the `<div>` element reveals a set of nested message `divs` but only if the `name` is invalid and the control is either `dirty` or `touched`.
* Each nested `<div>` can present a custom message for one of the possible validation errors.
There are messages for `required`, `minlength`, and `forbiddenName`.
HELPFUL: To prevent the validator from displaying errors before the user has a chance to edit the form, you should check for either the `dirty` or `touched` states in a control.
* When the user changes the value in the watched field, the control is marked as "dirty"
* When the user blurs the form control element, the control is marked as "touched"
## Validating input in reactive forms
In a reactive form, the source of truth is the component class.
Instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class.
Angular then calls these functions whenever the value of the control changes.
### Validator functions
Validator functions can be either synchronous or asynchronous.
| Validator type | Details |
|:--- |:--- |
| Sync validators | Synchronous functions that take a control instance and immediately return either a set of validation errors or `null`. Pass these in as the second argument when you instantiate a `FormControl`. |
| Async validators | Asynchronous functions that take a control instance and return a Promise or Observable that later emits a set of validation errors or `null`. Pass these in as the third argument when you instantiate a `FormControl`. |
For performance reasons, Angular only runs async validators if all sync validators pass.
Each must complete before errors are set.
### Built-in validator functions
You can choose to [write your own validator functions](#defining-custom-validators), or you can use some of Angular's built-in validators.
The same built-in validators that are available as attributes in template-driven forms, such as `required` and `minlength`, are all available to use as functions from the `Validators` class.
For a full list of built-in validators, see the [Validators](api/forms/Validators) API reference.
To update the actor form to be a reactive form, use some of the same
built-in validators —this time, in function form, as in the following example.
<docs-code header="reactive/actor-form-reactive.component.ts (validator functions)" path="adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.1.ts" visibleRegion="form-group"/>
In this example, the `name` control sets up two built-in validators —`Validators.required` and `Validators.minLength(4)`— and one custom validator, `forbiddenNameValidator`.
All of these validators are synchronous, so they are passed as the second argument.
Notice that you can support multiple validators by passing the functions in as an array.
This example also adds a few getter methods.
In a reactive form, you can always access any form control through the `get` method on its parent group, but sometimes it's useful to define getters as shorthand for the template.
If you look at the template for the `name` input again, it is fairly similar to the template-driven example.
<docs-code header="reactive/actor-form-reactive.component.html (name with error msg)" path="adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.html" visibleRegion="name-with-error-msg"/>
This form differs from the template-driven version in that it no longer exports any directives. Instead, it uses the `name` getter defined in the component class.
Notice that the `required` attribute is still present in the template. Although it's not necessary for validation, it should be retained for accessibility purposes.
## Defining custom validators
The built-in validators don't always match the exact use case of your application, so you sometimes need to create a custom validator.
Consider the `forbiddenNameValidator` function from the previous example.
Here's what the definition of that function looks like.
<docs-code header="shared/forbidden-name.directive.ts (forbiddenNameValidator)" path="adev/src/content/examples/form-validation/src/app/shared/forbidden-name.directive.ts" visibleRegion="custom-validator"/>
The function is a factory that takes a regular expression to detect a *specific* forbidden name and returns a validator function.
In this sample, the forbidden name is "bob", so the validator rejects any actor name containing "bob".
Elsewhere it could reject "alice" or any name that the configuring regular expression matches.
The `forbiddenNameValidator` factory returns the configured validator function.
That function takes an Angular control object and returns *either* null if the control value is valid *or* a validation error object.
The validation error object typically has a property whose name is the validation key, `'forbiddenName'`, and whose value is an arbitrary dictionary of values that you could insert into an error message, `{name}`.
Custom async validators are similar to sync validators, but they must instead return a Promise or observable that later emits null or a validation error object.
In the case of an observable, the observable must complete, at which point the form uses the last value emitted for validation.
### Adding custom validators to reactive forms
In reactive forms, add a custom validator by passing the function directly to the `FormControl`.
<docs-code header="reactive/actor-form-reactive.component.ts (validator functions)" path="adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.1.ts" visibleRegion="custom-validator"/>
### Adding custom validators to template-driven forms
In template-driven forms, add a directive to the template, where the directive wraps the validator function.
For example, the corresponding `ForbiddenValidatorDirective` serves as a wrapper around the `forbiddenNameValidator`.
Angular recognizes the directive's role in the validation process because the directive registers itself with the `NG_VALIDATORS` provider, as shown in the following example.
`NG_VALIDATORS` is a predefined provider with an extensible collection of validators.
<docs-code header="shared/forbidden-name.directive.ts (providers)" path="adev/src/content/examples/form-validation/src/app/shared/forbidden-name.directive.ts" visibleRegion="directive-providers"/>
The directive class then implements the `Validator` interface, so that it can easily integrate with Angular forms.
Here is the rest of the directive to help you get an idea of how it all comes together.
<docs-code header="shared/forbidden-name.directive.ts (directive)" path="adev/src/content/examples/form-validation/src/app/shared/forbidden-name.directive.ts" visibleRegion="directive"/>
Once the `ForbiddenValidatorDirective` is ready, you can add its selector, `appForbiddenName`, to any input element to activate it.
For example:
<docs-code header="template/actor-form-template.component.html (forbidden-name-input)" path="adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.html" visibleRegion="name-input"/>
HELPFUL: Notice that the custom validation directive is instantiated with `useExisting` rather than `useClass`.
The registered validator must be *this instance* of the `ForbiddenValidatorDirective` —the instance in the form with its `forbiddenName` property bound to "bob".
If you were to replace `useExisting` with `useClass`, then you'd be registering a new class instance, one that doesn't have a `forbiddenName`.
## Contr | {
"end_byte": 9567,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/form-validation.md"
} |
angular/adev/src/content/guide/forms/form-validation.md_9567_14726 | ol status CSS classes
Angular automatically mirrors many control properties onto the form control element as CSS classes.
Use these classes to style form control elements according to the state of the form.
The following classes are currently supported.
* `.ng-valid`
* `.ng-invalid`
* `.ng-pending`
* `.ng-pristine`
* `.ng-dirty`
* `.ng-untouched`
* `.ng-touched`
* `.ng-submitted` \(enclosing form element only\)
In the following example, the actor form uses the `.ng-valid` and `.ng-invalid` classes to
set the color of each form control's border.
<docs-code header="forms.css (status classes)" path="adev/src/content/examples/form-validation/src/assets/forms.css"/>
## Cross-field validation
A cross-field validator is a [custom validator](#defining-custom-validators "Read about custom validators") that compares the values of different fields in a form and accepts or rejects them in combination.
For example, you might have a form that offers mutually incompatible options, so that if the user can choose A or B, but not both.
Some field values might also depend on others; a user might be allowed to choose B only if A is also chosen.
The following cross validation examples show how to do the following:
* Validate reactive or template-based form input based on the values of two sibling controls,
* Show a descriptive error message after the user interacted with the form and the validation failed.
The examples use cross-validation to ensure that actors do not reuse the same name in their role by filling out the Actor Form.
The validators do this by checking that the actor names and roles do not match.
### Adding cross-validation to reactive forms
The form has the following structure:
<docs-code language="javascript">
const actorForm = new FormGroup({
'name': new FormControl(),
'role': new FormControl(),
'skill': new FormControl()
});
</docs-code>
Notice that the `name` and `role` are sibling controls.
To evaluate both controls in a single custom validator, you must perform the validation in a common ancestor control: the `FormGroup`.
You query the `FormGroup` for its child controls so that you can compare their values.
To add a validator to the `FormGroup`, pass the new validator in as the second argument on creation.
<docs-code language="javascript">
const actorForm = new FormGroup({
'name': new FormControl(),
'role': new FormControl(),
'skill': new FormControl()
}, { validators: unambiguousRoleValidator });
</docs-code>
The validator code is as follows.
<docs-code header="shared/unambiguous-role.directive.ts" path="adev/src/content/examples/form-validation/src/app/shared/unambiguous-role.directive.ts" visibleRegion="cross-validation-validator"/>
The `unambiguousRoleValidator` validator implements the `ValidatorFn` interface.
It takes an Angular control object as an argument and returns either null if the form is valid, or `ValidationErrors` otherwise.
The validator retrieves the child controls by calling the `FormGroup`'s [get](api/forms/AbstractControl#get) method, then compares the values of the `name` and `role` controls.
If the values do not match, the role is unambiguous, both are valid, and the validator returns null.
If they do match, the actor's role is ambiguous and the validator must mark the form as invalid by returning an error object.
To provide better user experience, the template shows an appropriate error message when the form is invalid.
<docs-code header="reactive/actor-form-template.component.html" path="adev/src/content/examples/form-validation/src/app/reactive/actor-form-reactive.component.html" visibleRegion="cross-validation-error-message"/>
This `*ngIf` displays the error if the `FormGroup` has the cross validation error returned by the `unambiguousRoleValidator` validator, but only if the user finished [interacting with the form](#control-status-css-classes).
### Adding cross-validation to template-driven forms
For a template-driven form, you must create a directive to wrap the validator function.
You provide that directive as the validator using the [`NG_VALIDATORS` token](/api/forms/NG_VALIDATORS), as shown in the following example.
<docs-code header="shared/unambiguous-role.directive.ts" path="adev/src/content/examples/form-validation/src/app/shared/unambiguous-role.directive.ts" visibleRegion="cross-validation-directive"/>
You must add the new directive to the HTML template.
Because the validator must be registered at the highest level in the form, the following template puts the directive on the `form` tag.
<docs-code header="template/actor-form-template.component.html" path="adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.html" visibleRegion="cross-validation-register-validator"/>
To provide better user experience, an appropriate error message appears when the form is invalid.
<docs-code header="template/actor-form-template.component.html" path="adev/src/content/examples/form-validation/src/app/template/actor-form-template.component.html" visibleRegion="cross-validation-error-message"/>
This is the same in both template-driven and reactive forms.
## Creat | {
"end_byte": 14726,
"start_byte": 9567,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/form-validation.md"
} |
angular/adev/src/content/guide/forms/form-validation.md_14726_21860 | 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.
| {
"end_byte": 21860,
"start_byte": 14726,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/form-validation.md"
} |
angular/adev/src/content/guide/forms/reactive-forms.md_0_7330 | # Reactive forms
Reactive forms provide a model-driven approach to handling form inputs whose values change over time.
This guide shows you how to create and update a basic form control, progress to using multiple controls in a group, validate form values, and create dynamic forms where you can add or remove controls at run time.
## Overview of reactive forms
Reactive forms use an explicit and immutable approach to managing the state of a form at a given point in time.
Each change to the form state returns a new state, which maintains the integrity of the model between changes.
Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously.
Reactive forms also provide a straightforward path to testing because you are assured that your data is consistent and predictable when requested.
Any consumers of the streams have access to manipulate that data safely.
Reactive forms differ from [template-driven forms](guide/forms/template-driven-forms) in distinct ways.
Reactive forms provide synchronous access to the data model, immutability with observable operators, and change tracking through observable streams.
Template-driven forms let direct access modify data in your template, but are less explicit than reactive forms because they rely on directives embedded in the template, along with mutable data to track changes asynchronously.
See the [Forms Overview](guide/forms) for detailed comparisons between the two paradigms.
## Adding a basic form control
There are three steps to using form controls.
1. Register the reactive forms module in your application.
This module declares the reactive-form directives that you need to use reactive forms.
1. Generate a new component and instantiate a new `FormControl`.
1. Register the `FormControl` in the template.
You can then display the form by adding the component to the template.
The following examples show how to add a single form control.
In the example, the user enters their name into an input field, captures that input value, and displays the current value of the form control element.
<docs-workflow>
<docs-step title="Import the ReactiveFormsModule">
To use reactive form controls, import `ReactiveFormsModule` from the `@angular/forms` package and add it to your NgModule's `imports` array.
<docs-code header="src/app/app.module.ts (excerpt)" path="adev/src/content/examples/reactive-forms/src/app/app.module.ts" visibleRegion="imports" />
</docs-step>
<docs-step title="Generate a new component with a FormControl">
Use the CLI command `ng generate component` to generate a component in your project to host the control.
<docs-code header="src/app/name-editor/name-editor.component.ts" path="adev/src/content/examples/reactive-forms/src/app/name-editor/name-editor.component.ts" visibleRegion="create-control"/>
Use the constructor of `FormControl` to set its initial value, which in this case is an empty string. By creating these controls in your component class, you get immediate access to listen for, update, and validate the state of the form input.
</docs-step>
<docs-step title="Register the control in the template">
After you create the control in the component class, you must associate it with a form control element in the template. Update the template with the form control using the `formControl` binding provided by `FormControlDirective`, which is also included in the `ReactiveFormsModule`.
<docs-code header="src/app/name-editor/name-editor.component.html" path="adev/src/content/examples/reactive-forms/src/app/name-editor/name-editor.component.html" visibleRegion="control-binding" />
Using the template binding syntax, the form control is now registered to the `name` input element in the template. The form control and DOM element communicate with each other: the view reflects changes in the model, and the model reflects changes in the view.
</docs-step>
<docs-step title="Display the component">
The `FormControl` assigned to the `name` property is displayed when the `<app-name-editor>` component is added to a template.
<docs-code header="src/app/app.component.html (name editor)" path="adev/src/content/examples/reactive-forms/src/app/app.component.1.html" visibleRegion="app-name-editor"/>
</docs-step>
</docs-workflow>
### Displaying a form control value
You can display the value in the following ways.
* Through the `valueChanges` observable where you can listen for changes in the form's value in the template using `AsyncPipe` or in the component class using the `subscribe()` method
* With the `value` property, which gives you a snapshot of the current value
The following example shows you how to display the current value using interpolation in the template.
<docs-code header="src/app/name-editor/name-editor.component.html (control value)" path="adev/src/content/examples/reactive-forms/src/app/name-editor/name-editor.component.html" visibleRegion="display-value"/>
The displayed value changes as you update the form control element.
Reactive forms provide access to information about a given control through properties and methods provided with each instance.
These properties and methods of the underlying [AbstractControl](api/forms/AbstractControl "API reference") class are used to control form state and determine when to display messages when handling [input validation](#validating-form-input "Learn more about validating form input").
Read about other `FormControl` properties and methods in the [API Reference](api/forms/FormControl "Detailed syntax reference").
### Replacing a form control value
Reactive forms have methods to change a control's value programmatically, which gives you the flexibility to update the value without user interaction.
A form control instance provides a `setValue()` method that updates the value of the form control and validates the structure of the value provided against the control's structure.
For example, when retrieving form data from a backend API or service, use the `setValue()` method to update the control to its new value, replacing the old value entirely.
The following example adds a method to the component class to update the value of the control to *Nancy* using the `setValue()` method.
<docs-code header="src/app/name-editor/name-editor.component.ts (update value)" path="adev/src/content/examples/reactive-forms/src/app/name-editor/name-editor.component.ts" visibleRegion="update-value"/>
Update the template with a button to simulate a name update.
When you click the **Update Name** button, the value entered in the form control element is reflected as its current value.
<docs-code header="src/app/name-editor/name-editor.component.html (update value)" path="adev/src/content/examples/reactive-forms/src/app/name-editor/name-editor.component.html" visibleRegion="update-value"/>
The form model is the source of truth for the control, so when you click the button, the value of the input is changed within the component class, overriding its current value.
HELPFUL: In this example, you're using a single control.
When using the `setValue()` method with a [form group](#grouping-form-controls) or [form array](#creating-dynamic-forms) instance, the value needs to match the structure of the group or array.
| {
"end_byte": 7330,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/reactive-forms.md"
} |
angular/adev/src/content/guide/forms/reactive-forms.md_7330_16022 | ## Grouping form controls
Forms typically contain several related controls.
Reactive forms provide two ways of grouping multiple related controls into a single input form.
| Form groups | Details |
|:--- |:--- |
| Form group | Defines a form with a fixed set of controls that you can manage together. Form group basics are discussed in this section. You can also [nest form groups](#creating-nested-form-groups "See more about nesting groups") to create more complex forms. |
| Form array | Defines a dynamic form, where you can add and remove controls at run time. You can also nest form arrays to create more complex forms. For more about this option, see [Creating dynamic forms](#creating-dynamic-forms). |
Just as a form control instance gives you control over a single input field, a form group instance tracks the form state of a group of form control instances \(for example, a form\).
Each control in a form group instance is tracked by name when creating the form group.
The following example shows how to manage multiple form control instances in a single group.
Generate a `ProfileEditor` component and import the `FormGroup` and `FormControl` classes from the `@angular/forms` package.
<docs-code language="shell">
ng generate component ProfileEditor
</docs-code>
<docs-code header="src/app/profile-editor/profile-editor.component.ts (imports)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.1.ts" visibleRegion="imports"/>
To add a form group to this component, take the following steps.
1. Create a `FormGroup` instance.
1. Associate the `FormGroup` model and view.
1. Save the form data.
<docs-workflow>
<docs-step title="Create a FormGroup instance">
Create a property in the component class named `profileForm` and set the property to a new form group instance. To initialize the form group, provide the constructor with an object of named keys mapped to their control.
For the profile form, add two form control instances with the names `firstName` and `lastName`
<docs-code header="src/app/profile-editor/profile-editor.component.ts (form group)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.1.ts" visibleRegion="formgroup"/>
The individual form controls are now collected within a group. A `FormGroup` instance provides its model value as an object reduced from the values of each control in the group. A form group instance has the same properties (such as `value` and `untouched`) and methods (such as `setValue()`) as a form control instance.
</docs-step>
<docs-step title="Associate the FormGroup model and view">
A form group tracks the status and changes for each of its controls, so if one of the controls changes, the parent control also emits a new status or value change. The model for the group is maintained from its members. After you define the model, you must update the template to reflect the model in the view.
<docs-code header="src/app/profile-editor/profile-editor.component.html (template form group)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.1.html" visibleRegion="formgroup"/>
Just as a form group contains a group of controls, the *profileForm* `FormGroup` is bound to the `form` element with the `FormGroup` directive, creating a communication layer between the model and the form containing the inputs. The `formControlName` input provided by the `FormControlName` directive binds each individual input to the form control defined in `FormGroup`. The form controls communicate with their respective elements. They also communicate changes to the form group instance, which provides the source of truth for the model value.
</docs-step>
<docs-step title="Save form data">
The `ProfileEditor` component accepts input from the user, but in a real scenario you want to capture the form value and make it available for further processing outside the component. The `FormGroup` directive listens for the `submit` event emitted by the `form` element and emits an `ngSubmit` event that you can bind to a callback function. Add an `ngSubmit` event listener to the `form` tag with the `onSubmit()` callback method.
<docs-code header="src/app/profile-editor/profile-editor.component.html (submit event)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.html" visibleRegion="ng-submit"/>
The `onSubmit()` method in the `ProfileEditor` component captures the current value of `profileForm`. Use `EventEmitter` to keep the form encapsulated and to provide the form value outside the component. The following example uses `console.warn` to log a message to the browser console.
<docs-code header="src/app/profile-editor/profile-editor.component.ts (submit method)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.ts" visibleRegion="on-submit"/>
The `submit` event is emitted by the `form` tag using the built-in DOM event. You trigger the event by clicking a button with `submit` type. This lets the user press the **Enter** key to submit the completed form.
Use a `button` element to add a button to the bottom of the form to trigger the form submission.
<docs-code header="src/app/profile-editor/profile-editor.component.html (submit button)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.html" visibleRegion="submit-button"/>
The button in the preceding snippet also has a `disabled` binding attached to it to disable the button when `profileForm` is invalid. You aren't performing any validation yet, so the button is always enabled. Basic form validation is covered in the [Validating form input](#validating-form-input) section.
</docs-step>
<docs-step title="Display the component">
To display the `ProfileEditor` component that contains the form, add it to a component template.
<docs-code header="src/app/app.component.html (profile editor)" path="adev/src/content/examples/reactive-forms/src/app/app.component.1.html" visibleRegion="app-profile-editor"/>
`ProfileEditor` lets you manage the form control instances for the `firstName` and `lastName` controls within the form group instance.
### Creating nested form groups
Form groups can accept both individual form control instances and other form group instances as children.
This makes composing complex form models easier to maintain and logically group together.
When building complex forms, managing the different areas of information is easier in smaller sections.
Using a nested form group instance lets you break large forms groups into smaller, more manageable ones.
To make more complex forms, use the following steps.
1. Create a nested group.
1. Group the nested form in the template.
Some types of information naturally fall into the same group.
A name and address are typical examples of such nested groups, and are used in the following examples.
<docs-workflow>
<docs-step title="Create a nested group">
To create a nested group in `profileForm`, add a nested `address` element to the form group instance.
<docs-code header="src/app/profile-editor/profile-editor.component.ts (nested form group)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.1.ts" visibleRegion="nested-formgroup"/>
In this example, `address group` combines the current `firstName` and `lastName` controls with the new `street`, `city`, `state`, and `zip` controls. Even though the `address` element in the form group is a child of the overall `profileForm` element in the form group, the same rules apply with value and status changes. Changes in status and value from the nested form group propagate to the parent form group, maintaining consistency with the overall model.
</docs-step>
<docs-step title="Group the nested form in the template">
After you update the model in the component class, update the template to connect the form group instance and its input elements. Add the `address` form group containing the `street`, `city`, `state`, and `zip` fields to the `ProfileEditor` template.
<docs-code header="src/app/profile-editor/profile-editor.component.html (template nested form group)" path="adev/src/content/examples/reactive-forms/src/app/profile-editor/profile-editor.component.1.html" visibleRegion="formgroupname"/>
The `ProfileEditor` form is displayed as one group, but the model is broken down further to represent the logical grouping areas.
Display the value for the form group instance in the component template using the `value` property and `JsonPipe`.
</docs-step>
</docs-workflow>
| {
"end_byte": 16022,
"start_byte": 7330,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/reactive-forms.md"
} |
angular/adev/src/content/guide/forms/reactive-forms.md_16022_23456 | ### 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>
| {
"end_byte": 23456,
"start_byte": 16022,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/reactive-forms.md"
} |
angular/adev/src/content/guide/forms/reactive-forms.md_23456_30706 | ## 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. |
| {
"end_byte": 30706,
"start_byte": 23456,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/reactive-forms.md"
} |
angular/adev/src/content/guide/forms/template-driven-forms.md_0_7595 | # 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.
## | {
"end_byte": 7595,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/template-driven-forms.md"
} |
angular/adev/src/content/guide/forms/template-driven-forms.md_7595_11898 | 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.
## | {
"end_byte": 11898,
"start_byte": 7595,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/template-driven-forms.md"
} |
angular/adev/src/content/guide/forms/template-driven-forms.md_11898_19564 | 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.
## | {
"end_byte": 19564,
"start_byte": 11898,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/template-driven-forms.md"
} |
angular/adev/src/content/guide/forms/template-driven-forms.md_19564_24951 | Submit the form with `ngSubmit`
The user should be able to submit this form after filling it in.
The **Submit** button at the bottom of the form does nothing on its own, but it does trigger a form-submit event because of its type (`type="submit"`).
To respond to this event, take the following steps.
<docs-workflow>
<docs-step title="Listen to ngOnSubmit">
Bind the form's [`ngSubmit`](api/forms/NgForm#properties) event property to the actor-form component's `onSubmit()` method.
<docs-code header="src/app/actor-form/actor-form.component.html (ngSubmit)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="ngSubmit"/>
</docs-step>
<docs-step title="Bind the disabled property">
Use the template reference variable, `#actorForm` to access the form that contains the **Submit** button and create an event binding.
You will bind the form property that indicates its overall validity to the **Submit** button's `disabled` property.
<docs-code header="src/app/actor-form/actor-form.component.html (submit-button)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="submit-button"/>
</docs-step>
<docs-step title="Run the application">
Notice that the button is enabled —although it doesn't do anything useful yet.
</docs-step>
<docs-step title="Delete the Name value">
This violates the "required" rule, so it displays the error message —and notice that it also disables the **Submit** button.
You didn't have to explicitly wire the button's enabled state to the form's validity.
The `FormsModule` did this automatically when you defined a template reference variable on the enhanced form element, then referred to that variable in the button control.
</docs-step>
</docs-workflow>
### Respond to form submission
To show a response to form submission, you can hide the data entry area and display something else in its place.
<docs-workflow>
<docs-step title="Wrap the form">
Wrap the entire form in a `<div>` and bind its `hidden` property to the `ActorFormComponent.submitted` property.
<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="edit-div"/>
The main form is visible from the start because the `submitted` property is false until you submit the form, as this fragment from the `ActorFormComponent` shows:
<docs-code header="src/app/actor-form/actor-form.component.ts (submitted)" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.ts" visibleRegion="submitted"/>
When you click the **Submit** button, the `submitted` flag becomes true and the form disappears.
</docs-step>
<docs-step title="Add the submitted state">
To show something else while the form is in the submitted state, add the following HTML below the new `<div>` wrapper.
<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="submitted"/>
This `<div>`, which shows a read-only actor with interpolation bindings, appears only while the component is in the submitted state.
The alternative display includes an _Edit_ button whose click event is bound to an expression that clears the `submitted` flag.
</docs-step>
<docs-step title="Test the Edit button">
Click the *Edit* button to switch the display back to the editable form.
</docs-step>
</docs-workflow>
## Summary
The Angular form discussed in this page takes advantage of the following
framework features to provide support for data modification, validation, and more.
- An Angular HTML form template
- A form component class with a `@Component` decorator
- Handling form submission by binding to the `NgForm.ngSubmit` event property
- Template-reference variables such as `#actorForm` and `#name`
- `[(ngModel)]` syntax for two-way data binding
- The use of `name` attributes for validation and form-element change tracking
- The reference variable's `valid` property on input controls indicates whether a control is valid or should show error messages
- Controlling the **Submit** button's enabled state by binding to `NgForm` validity
- Custom CSS classes that provide visual feedback to users about controls that are not valid
Here's the code for the final version of the application:
<docs-code-multifile>
<docs-code header="actor-form/actor-form.component.ts" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.ts" visibleRegion="final"/>
<docs-code header="actor-form/actor-form.component.html" path="adev/src/content/examples/forms/src/app/actor-form/actor-form.component.html" visibleRegion="final"/>
<docs-code header="actor.ts" path="adev/src/content/examples/forms/src/app/actor.ts"/>
<docs-code header="app.module.ts" path="adev/src/content/examples/forms/src/app/app.module.ts"/>
<docs-code header="app.component.html" path="adev/src/content/examples/forms/src/app/app.component.html"/>
<docs-code header="app.component.ts" path="adev/src/content/examples/forms/src/app/app.component.ts"/>
<docs-code header="main.ts" path="adev/src/content/examples/forms/src/main.ts"/>
<docs-code header="forms.css" path="adev/src/content/examples/forms/src/assets/forms.css"/>
</docs-code-multifile>
| {
"end_byte": 24951,
"start_byte": 19564,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/template-driven-forms.md"
} |
angular/adev/src/content/guide/forms/BUILD.bazel_0_3972 | load("//adev/shared-docs:index.bzl", "generate_guides")
generate_guides(
name = "forms",
srcs = glob([
"*.md",
]),
data = [
"//adev/src/assets/images:overview.svg",
"//adev/src/content/examples/dynamic-form:src/app/app.component.ts",
"//adev/src/content/examples/dynamic-form:src/app/dynamic-form.component.html",
"//adev/src/content/examples/dynamic-form:src/app/dynamic-form.component.ts",
"//adev/src/content/examples/dynamic-form:src/app/dynamic-form-question.component.html",
"//adev/src/content/examples/dynamic-form:src/app/dynamic-form-question.component.ts",
"//adev/src/content/examples/dynamic-form:src/app/question.service.ts",
"//adev/src/content/examples/dynamic-form:src/app/question-base.ts",
"//adev/src/content/examples/dynamic-form:src/app/question-control.service.ts",
"//adev/src/content/examples/dynamic-form:src/app/question-dropdown.ts",
"//adev/src/content/examples/dynamic-form:src/app/question-textbox.ts",
"//adev/src/content/examples/form-validation:src/app/reactive/actor-form-reactive.component.1.ts",
"//adev/src/content/examples/form-validation:src/app/reactive/actor-form-reactive.component.2.ts",
"//adev/src/content/examples/form-validation:src/app/reactive/actor-form-reactive.component.html",
"//adev/src/content/examples/form-validation:src/app/shared/forbidden-name.directive.ts",
"//adev/src/content/examples/form-validation:src/app/shared/role.directive.ts",
"//adev/src/content/examples/form-validation:src/app/shared/unambiguous-role.directive.ts",
"//adev/src/content/examples/form-validation:src/app/template/actor-form-template.component.html",
"//adev/src/content/examples/form-validation:src/assets/forms.css",
"//adev/src/content/examples/forms:src/app/actor.ts",
"//adev/src/content/examples/forms:src/app/actor-form/actor-form.component.html",
"//adev/src/content/examples/forms:src/app/actor-form/actor-form.component.ts",
"//adev/src/content/examples/forms:src/app/app.component.html",
"//adev/src/content/examples/forms:src/app/app.component.ts",
"//adev/src/content/examples/forms:src/app/app.module.ts",
"//adev/src/content/examples/forms:src/assets/forms.css",
"//adev/src/content/examples/forms:src/index.html",
"//adev/src/content/examples/forms:src/main.ts",
"//adev/src/content/examples/forms:src/styles.1.css",
"//adev/src/content/examples/forms-overview:src/app/reactive/favorite-color/favorite-color.component.spec.ts",
"//adev/src/content/examples/forms-overview:src/app/reactive/favorite-color/favorite-color.component.ts",
"//adev/src/content/examples/forms-overview:src/app/template/favorite-color/favorite-color.component.spec.ts",
"//adev/src/content/examples/forms-overview:src/app/template/favorite-color/favorite-color.component.ts",
"//adev/src/content/examples/reactive-forms:src/app/app.component.1.html",
"//adev/src/content/examples/reactive-forms:src/app/app.module.ts",
"//adev/src/content/examples/reactive-forms:src/app/name-editor/name-editor.component.html",
"//adev/src/content/examples/reactive-forms:src/app/name-editor/name-editor.component.ts",
"//adev/src/content/examples/reactive-forms:src/app/profile-editor/profile-editor.component.1.html",
"//adev/src/content/examples/reactive-forms:src/app/profile-editor/profile-editor.component.1.ts",
"//adev/src/content/examples/reactive-forms:src/app/profile-editor/profile-editor.component.2.ts",
"//adev/src/content/examples/reactive-forms:src/app/profile-editor/profile-editor.component.html",
"//adev/src/content/examples/reactive-forms:src/app/profile-editor/profile-editor.component.ts",
],
mermaid_blocks = True,
visibility = ["//adev:__subpackages__"],
)
| {
"end_byte": 3972,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/BUILD.bazel"
} |
angular/adev/src/content/guide/forms/typed-forms.md_0_7413 | # 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`.
| {
"end_byte": 7413,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/forms/typed-forms.md"
} |
angular/adev/src/content/guide/signals/rxjs-interop.md_0_5505 | # 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).
| {
"end_byte": 5505,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/signals/rxjs-interop.md"
} |
angular/adev/src/content/guide/signals/queries.md_0_8627 | # Signal queries
A component or directive can define queries that find child elements and read values from their injectors.
Developers most commonly use queries to retrieve references to components, directives, DOM elements, and more.
There are two categories of query: view queries and content queries.
Signal queries supply query results as a reactive signal primitive. You can use query results in `computed` and `effect`, composing these results with other signals.
If you're already familiar with Angular queries, you can jump straight to [Comparing signal-based queries to decorator-based queries](#comparing-signal-based-queries-to-decorator-based-queries)
## View queries
View queries retrieve results from the elements in the component's own template (view).
### `viewChild`
You can declare a query targeting a single result with the `viewChild` function.
```angular-ts
@Component({
template: `
<div #el></div>
<my-component />
`
})
export class TestComponent {
// query for a single result by a string predicate
divEl = viewChild<ElementRef>('el') // Signal<ElementRef|undefined>
// query for a single result by a type predicate
cmp = viewChild(MyComponent); // Signal<MyComponent|undefined>
}
```
### `viewChildren`
You can also query for multiple results with the `viewChildren` function.
```angular-ts
@Component({
template: `
<div #el></div>
@if (show) {
<div #el></div>
}
`
})
export class TestComponent {
show = true;
// query for multiple results
divEls = viewChildren<ElementRef>('el'); // Signal<ReadonlyArray<ElementRef>>
}
```
### View query options
The `viewChild` and the `viewChildren` query declaration functions have a similar signature accepting two arguments:
* a **locator** to specify the query target - it can be either a `string` or any injectable token
* a set of **options** to adjust behavior of a given query.
Signal-based view queries accept only one option: `read`. The `read` option indicates the type of result to inject from the matched nodes and return in the final results.
```angular-ts
@Component({
template: `<my-component/>`
})
export class TestComponent {
// query for a single result with options
cmp = viewChild(MyComponent, {read: ElementRef}); // Signal<ElementRef|undefined>
}
```
## Content queries
Content queries retrieve results from the elements in the component's content — the elements nested inside the component tag in the template where it's used.
### `contentChild`
You can query for a single result with the `contentChild` function.
```ts
@Component({...})
export class TestComponent {
// query by a string predicate
headerEl = contentChild<ElementRef>('h'); // Signal<ElementRef|undefined>
// query by a type predicate
header = contentChild(MyHeader); // Signal<MyHeader|undefined>
}
```
### `contentChildren`
You can also query for multiple results with the `contentChildren` function.
```ts
@Component({...})
export class TestComponent {
// query for multiple results
divEls = contentChildren<ElementRef>('h'); // Signal<ReadonlyArray<ElementRef>>
}
```
### Content query options
The `contentChild` and the `contentChildren` query declaration functions have a similar signature accepting two arguments:
* a **locator** to specify the query target - it can be either a `string` or any injectable token
* a set of **options** to adjust behavior of a given query.
Content queries accept the following options:
* `descendants` By default, content queries find only direct children of the component and do not traverse into descendants. If this option is changed to `true`, query results will include all descendants of the element. Even when `true`, however, queries _never_ descend into components.
* `read` indicates the type of result to retrieve from the matched nodes and return in the final results.
### Required child queries
If a child query (`viewChild` or `contentChild`) does not find a result, its value is `undefined`. This may occur if the target element is hidden by a control flow statement like `@if` or `@for`.
Because of this, the child queries return a signal that potentially have the `undefined` value. Most of the time, and especially for the view child queries, developers author their code such that:
* there is at least one matching result;
* results are accessed when the template was processed and query results are available.
For such cases, you can mark child queries as `required` to enforce presence of at least one matching result. This eliminates `undefined` from the result type signature. If a `required` query does not find any results, Angular throws an error.
```angular-ts
@Component({
selector: 'app-root',
standalone: true,
template: `
<div #requiredEl></div>
`,
})
export class App {
existingEl = viewChild.required('requiredEl'); // required and existing result
missingEl = viewChild.required('notInATemplate'); // required but NOT existing result
ngAfterViewInit() {
console.log(this.existingEl()); // OK :-)
console.log(this.missingEl()); // Runtime error: result marked as required by not available!
}
}
```
## Results availability timing
Signal query declaration functions (ex.: `viewChild`) will be executed while the directive is instantiated. This happens before a template is rendered and before Angular can collect any query matches. As a consequence, there is a period of time where the signal instance was created (and can be read) but no query results could have been collected. By default Angular will return `undefined` (for child queries) or an empty array (for children queries) before results are available. Required queries will throw if accessed at this point.
Angular computes signal-based query results lazily, on demand. This means that query results are not collected unless there is a code path that reads the signal.
Query results can change over time due to the view manipulation - either through the Angular's control flow (`@if`, `@for` etc.) or by the direct calls to the `ViewContainerRef` API. When you read the value from the query result signal, you can receive different values over time.
Note: to avoid returning incomplete query results while a template is rendered, Angular delays query resolution until it finishes rendering a given template.
## Query declarations functions and the associated rules
The `viewChild`, `contentChild`, `viewChildren` and `contentChildren` functions are special functions recognized by the Angular compiler. You can use those functions to declare queries by initializing a component or a directive property. You can never call these functions outside of component and directive property initializers.
```angular-ts
@Component({
selector: 'app-root',
standalone: true,
template: `
<div #el></div>
`,
})
export class App {
el = viewChild('el'); // all good!
constructor() {
const myConst = viewChild('el'); // NOT SUPPORTED
}
}
```
## Comparing signal-based queries to decorator-based queries
Signal queries are an alternative approach to the queries declared using the `@ContentChild`, `@ContentChildren`, `@ViewChild` or `@ViewChildren` decorators. The new approach exposes query results as signals which means that query results can be composed with other signals (using `computed` or `effect`) and drive change detection. Additionally, the signal-based query system offers other benefits:
* **More predictable timing.** You can access query results as soon as they're available.
* **Simpler API surface.** All queries return a signal, and queries with more than one result let you work with a standard array.
* **Improved type safety.** Fewer query use cases include `undefined` in the possible results.
* **More accurate type inference.** TypeScript can infer more accurate types when you use a type predicate or when you specify an explicit `read` option.
* **Lazier updates.** - Angular updates signal-based query results lazily; the framework does no work unless your code explicitly reads the query results.
The underlying query mechanism doesn't change much - conceptually Angular still creates singular "child" or plural "children" queries that target elements in a template (view) or content. The difference is in the type of results and the exact timing of the results availability. The authoring format for declaring signal-based queries changed as well: the `viewChild`, `viewChildren`, `contentChild` and `contentChildren` functions used as initializer of class members are automatically recognized by Angular.
| {
"end_byte": 8627,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/signals/queries.md"
} |
angular/adev/src/content/guide/signals/overview.md_0_7975 | <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.
| {
"end_byte": 7975,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/signals/overview.md"
} |
angular/adev/src/content/guide/signals/overview.md_7975_10656 | ## 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);
});
});
```
| {
"end_byte": 10656,
"start_byte": 7975,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/signals/overview.md"
} |
angular/adev/src/content/guide/signals/model.md_0_4786 | # Model inputs
**Model inputs** are a special type of input that enable a component to propagate new values
back to another component.
When creating a component, you can define a model input similarly to how you create a standard
input.
```angular-ts
import {Component, model, input} from '@angular/core';
@Component({...})
export class CustomCheckbox {
// This is a model input.
checked = model(false);
// This is a standard input.
disabled = input(false);
}
```
Both types of input allow someone to bind a value into the property. However, **model inputs allow
the component author to write values into the property**.
In other respects, you can use model inputs the same way you use standard inputs. You can read the
value by calling the signal function, including in reactive contexts like `computed` and `effect`.
```angular-ts
import {Component, model, input} from '@angular/core';
@Component({
selector: 'custom-checkbox',
template: '<div (click)="toggle()"> ... </div>',
})
export class CustomCheckbox {
checked = model(false);
disabled = input(false);
toggle() {
// While standard inputs are read-only, you can write directly to model inputs.
this.checked.set(!this.checked());
}
}
```
When a component writes a new value into a model input, Angular can propagate the new value back
to the component that is binding a value into that input. This is called **two-way binding** because
values can flow in both directions.
## Two-way binding with signals
You can bind a writable signal to a model input.
```angular-ts
@Component({
...,
// `checked` is a model input.
// The parenthesis-inside-square-brackets syntax (aka "banana-in-a-box") creates a two-way binding
template: '<custom-checkbox [(checked)]="isAdmin" />',
})
export class UserProfile {
protected isAdmin = signal(false);
}
```
In the above example, the `CustomCheckbox` can write values into its `checked` model input, which
then propagates those values back to the `isAdmin` signal in `UserProfile`. This binding keeps that
values of `checked` and `isAdmin` in sync. Notice that the binding passes the `isAdmin` signal
itself, not the _value_ of the signal.
## Two-way binding with plain properties
You can bind a plain JavaScript property to a model input.
```angular-ts
@Component({
...,
// `checked` is a model input.
// The parenthesis-inside-square-brackets syntax (aka "banana-in-a-box") creates a two-way binding
template: '<custom-checkbox [(checked)]="isAdmin" />',
})
export class UserProfile {
protected isAdmin = false;
}
```
In the example above, the `CustomCheckbox` can write values into its `checked` model input, which
then propagates those values back to the `isAdmin` property in `UserProfile`. This binding keeps
that values of `checked` and `isAdmin` in sync.
## Implicit `change` events
When you declare a model input in a component or directive, Angular automatically creates a
corresponding [output](guide/components/outputs) for that model. The output's name is the model
input's name suffixed with "Change".
```angular-ts
@Directive({...})
export class CustomCheckbox {
// This automatically creates an output named "checkedChange".
// Can be subscribed to using `(checkedChange)="handler()"` in the template.
checked = model(false);
}
```
Angular emits this change event whenever you write a new value into the model input by calling
its `set` or `update` methods.
## Customizing model inputs
You can mark a model input as required or provide an alias in the same way as a
[standard input](guide/signals/inputs).
Model inputs do not support input transforms.
## Differences between `model()` and `input()`
Both `input()` and `model()` functions are ways to define signal-based inputs in Angular, but they
differ in a few ways:
1. `model()` defines **both** an input and an output. The output's name is always the name of the
input suffixed with `Change` to support two-way bindings. It will be up to the consumer of your
directive to decide if they want to use just the input, just the output, or both.
2. `ModelSignal` is a `WritableSignal` which means that its value can be changed from anywhere
using the `set` and `update` methods. When a new value is assigned, the `ModelSignal` will emit
to its output. This is different from `InputSignal` which is read-only and can only be changed
through the template.
3. Model inputs do not support input transforms while signal inputs do.
## When to use model inputs
Use model inputs when you want a component to support two-way binding. This is typically
appropriate when a component exists to modify a value based on user interaction. Most commonly,
custom form controls such as a date picker or combobox should use model inputs for their primary
value.
| {
"end_byte": 4786,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/signals/model.md"
} |
angular/adev/src/content/guide/signals/inputs.md_0_5109 | # 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.
| {
"end_byte": 5109,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/signals/inputs.md"
} |
angular/adev/src/content/guide/signals/BUILD.bazel_0_253 | load("//adev/shared-docs:index.bzl", "generate_guides")
generate_guides(
name = "signals",
srcs = glob([
"*.md",
]),
data = [
"//adev/src/assets/images:signals.svg",
],
visibility = ["//adev:__subpackages__"],
)
| {
"end_byte": 253,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/signals/BUILD.bazel"
} |
angular/adev/src/content/guide/pipes/template.md_0_2152 | # Using a pipe in a template
To apply a pipe, use the pipe operator (`|`) within a template expression as shown in the following code example.
<docs-code language="angular-html" header="app.component.html">
<p>The hero's birthday is {{ birthday | date }}</p>
</docs-code>
The component's `birthday` value flows through the pipe operator (`|`) to the [`DatePipe`](api/common/DatePipe) whose pipe name is `date`.
The pipe renders the date in the default format like **Apr 07, 2023**.
<docs-code header="app.component.ts" preview>
import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
standalone: true,
templateUrl: './app.component.html',
imports: [DatePipe],
})
export class AppComponent {
birthday = new Date();
}
</docs-code>
## Additional parameters for pipes
Pipes can take additional parameters that configure the transformation. Parameters can be optional or required.
For example, the `date` pipe takes optional parameters that control the date's display format.
To specify the parameter, follow the pipe name with a colon (`:`) and the parameter value (the format).
<docs-code language="angular-html" header="app.component.html">
<p>The hero's birthday is in {{ birthday | date:'yyyy' }}</p>
</docs-code>
Pipes can also take multiple parameters. You can pass multiple parameters by separating these via colons (`:`).
For example, the `date` pipe accepts a second optional parameter for controlling the timezone.
<docs-code header="app.component.html">
<p>The current time is: {{ currentTime | date:'hh:mm':'UTC' }}</p>
</docs-code>
This will display the current time (like `10:53`) in the `UTC` timezone.
## Chaining pipes
You can connect multiple pipes so that the output of one pipe becomes the input to the next.
The following example passes a date to the `DatePipe` and then forwards the result to the [`UpperCasePipe`](api/common/UpperCasePipe 'API reference') pipe.
<docs-code language="angular-html" header="app.component.html">
<p>The hero's birthday is {{ birthday | date }}</p>
<p>The hero's birthday is in {{ birthday | date:'yyyy' | uppercase }}</p>
</docs-code>
| {
"end_byte": 2152,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/src/content/guide/pipes/template.md"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.