diff --git a/aio/content/cli/cache.md b/aio/content/cli/cache.md index 19bc0d8a700ea..51954c7a702dc 100644 --- a/aio/content/cli/cache.md +++ b/aio/content/cli/cache.md @@ -1,5 +1,6 @@ # Persistent disk cache + Angular CLI saves a number of cachable operations on disk by default. When you re-run the same build, the build system restores the state of the previous build and re-uses previously performed operations, which decreases the time taken to build and test your applications and libraries. @@ -7,9 +8,10 @@ When you re-run the same build, the build system restores the state of the previ To amend the default cache settings, add the `cli.cache` object to your [Workspace Configuration](guide/workspace-config). The object goes under `cli.cache` at the top level of the file, outside the `projects` sections. -```json + + { - "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "cli": { "cache": { @@ -18,27 +20,35 @@ The object goes under `cli.cache` at the top level of the file, outside the `pro }, "projects": {} } -``` + + For more information, see [cache options](guide/workspace-config#cache-options). ### Enabling and disabling the cache -Caching is enabled by default. To disable caching run the following command: -```bash +Caching is enabled by default. +To disable caching run the following command: + + + ng config cli.cache.enabled false -``` + + To re-enable caching, set `cli.cache.enabled` to `true`. ### Cache environments + By default, disk cache is only enabled for local environments. To enable caching for all environments, run the following command: -```bash + + ng config cli.cache.environment all -``` + + For more information, see `environment` in [cache options](guide/workspace-config#cache-options). @@ -50,11 +60,14 @@ The Angular CLI checks for the presence and value of the `CI` environment variab ### Cache path -By default, `.angular/cache` is used as a base directory to store cache results. To change this path, run the following command: +By default, `.angular/cache` is used as a base directory to store cache results. +To change this path, run the following command: + + -```bash ng config cli.cache.path ".cache/ng" -``` + + ### Clearing the cache @@ -62,14 +75,18 @@ To clear the cache, run one of the following commands. To clear the cache on Unix-based operating systems: -```bash + + rm -rf .angular/cache -``` + + To clear the cache on Windows: -```bash + + rmdir /s /q .angular\cache -``` -For more information, see [rm command](https://man7.org/linux/man-pages/man1/rm.1.html) and [rmdir command](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/rmdir). \ No newline at end of file + + +For more information, see [rm command](https://man7.org/linux/man-pages/man1/rm.1.html) and [rmdir command](https://docs.microsoft.com/windows-server/administration/windows-commands/rmdir). diff --git a/aio/content/cli/index.md b/aio/content/cli/index.md index 337c7584a4ef2..29e3cc468a60e 100644 --- a/aio/content/cli/index.md +++ b/aio/content/cli/index.md @@ -7,30 +7,36 @@ The Angular CLI is a command-line interface tool that you use to initialize, dev Major versions of Angular CLI follow the supported major version of Angular, but minor versions can be released separately. Install the CLI using the `npm` package manager: - -npm install -g @angular/cli + + + +npm install -g @angular/cli + -For details about changes between versions, and information about updating from previous releases, -see the Releases tab on GitHub: https://github.com/angular/angular-cli/releases +For details about changes between versions, and information about updating from previous releases, see the Releases tab on GitHub: https://github.com/angular/angular-cli/releases ## Basic workflow Invoke the tool on the command line through the `ng` executable. Online help is available on the command line. -Enter the following to list commands or options for a given command (such as [generate](cli/generate)) with a short description. +Enter the following to list commands or options for a given command \(such as [generate](cli/generate)\) with a short description. + + - ng help ng generate --help + To create, build, and serve a new, basic Angular project on a development server, go to the parent directory of your new workspace use the following commands: - + + ng new my-first-project cd my-first-project ng serve + In your browser, open http://localhost:4200/ to see the new application run. @@ -38,9 +44,10 @@ When you use the [ng serve](cli/serve) command to build an application and serve
- When you run `ng new my-first-project` a new folder, named `my-first-project`, will be created in the current working directory. Since you want to be able to create files inside that folder, make sure you have sufficient rights in the current working directory before running the command. +When you run `ng new my-first-project` a new folder, named `my-first-project`, will be created in the current working directory. +Since you want to be able to create files inside that folder, make sure you have sufficient rights in the current working directory before running the command. - If the current working directory is not the right place for your project, you can change to a more appropriate directory by running `cd ` first. +If the current working directory is not the right place for your project, you can change to a more appropriate directory by running `cd `.
@@ -58,7 +65,7 @@ You can edit the generated files directly, or add to and modify them using CLI c Use the [ng generate](cli/generate) command to add new files for additional components and services, and code for new pipes, directives, and so on. Commands such as [add](cli/add) and [generate](cli/generate), which create or operate on applications and libraries, must be executed from within a workspace or project folder. -* See more about the [Workspace file structure](guide/file-structure). +* See more about the [Workspace file structure](guide/file-structure). ### Workspace and project configuration @@ -66,9 +73,15 @@ A single workspace configuration file, `angular.json`, is created at the top lev This is where you can set per-project defaults for CLI command options, and specify configurations to use when the CLI builds a project for different targets. The [ng config](cli/config) command lets you set and retrieve configuration values from the command line, or you can edit the `angular.json` file directly. -Note that option names in the configuration file must use [camelCase](guide/glossary#case-types), while option names supplied to commands must be dash-case. -* See more about [Workspace Configuration](guide/workspace-config). +
+ +**NOTE**:
+Option names in the configuration file must use [camelCase](guide/glossary#case-types), while option names supplied to commands must be dash-case. + +
+ +* See more about [Workspace Configuration](guide/workspace-config). ## CLI command-language syntax @@ -76,34 +89,44 @@ Command syntax is shown as follows: `ng` *commandNameOrAlias* *requiredArg* [*optionalArg*] `[options]` -* Most commands, and some options, have aliases. Aliases are shown in the syntax statement for each command. +* Most commands, and some options, have aliases. + Aliases are shown in the syntax statement for each command. -* Option names are prefixed with a double dash (--). - Option aliases are prefixed with a single dash (-). +* Option names are prefixed with a double dash \(`--`\) characters. + Option aliases are prefixed with a single dash \(`-`\) character. Arguments are not prefixed. For example: - - ng build my-app -c production + + + + ng build my-app -c production + -* Typically, the name of a generated artifact can be given as an argument to the command or specified with the --name option. +* Typically, the name of a generated artifact can be given as an argument to the command or specified with the `--name` option. -* Argument and option names can be given in either -[camelCase or dash-case](guide/glossary#case-types). -`--myOptionName` is equivalent to `--my-option-name`. +* Argument and option names can be given in either [camelCase or dash-case](guide/glossary#case-types). + `--myOptionName` is equivalent to `--my-option-name`. ### Boolean options Boolean options have two forms: `--this-option` sets the flag to `true`, `--no-this-option` sets it to `false`. If neither option is supplied, the flag remains in its default state, as listed in the reference documentation. - ### Relative paths Options that specify files can be given as absolute paths, or as paths relative to the current working directory, which is generally either the workspace or project root. ### Schematics -The [ng generate](cli/generate) and [ng add](cli/add) commands take as an argument the artifact or library to be generated or added to the current project. +The [ng generate](cli/generate) and [ng add](cli/add) commands take, as an argument, the artifact or library to be generated or added to the current project. In addition to any general options, each artifact or library defines its own options in a *schematic*. Schematic options are supplied to the command in the same format as immediate command options. + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/cli/usage-analytics-gathering.md b/aio/content/cli/usage-analytics-gathering.md index b53bfd8bdad5b..dda514dc8cd7c 100644 --- a/aio/content/cli/usage-analytics-gathering.md +++ b/aio/content/cli/usage-analytics-gathering.md @@ -20,14 +20,18 @@ This ID is a string that looks like `UA-123456-12`. You can choose to use a descriptive string as the key value, or be assigned a random key when you run the CLI command. For example, the following command adds a configuration key named "tracking". - + + ng config --global cli.analyticsSharing.tracking UA-123456-12 + To turn off this feature, run the following command: - + + ng config --global cli.analyticsSharing undefined + ## Per user tracking @@ -35,12 +39,24 @@ ng config --global cli.analyticsSharing undefined You can add a custom user ID to the global configuration, in order to identify unique usage of commands and flags. If that user enables CLI analytics for their own project, your analytics display tracks and labels their individual usage. - + + ng config --global cli.analyticsSharing.uuid SOME_USER_NAME + To generate a new random user ID, run the following command: - + + ng config --global cli.analyticsSharing.uuid "" + + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG0100.md b/aio/content/errors/NG0100.md index ebf034e40e22f..0b3e875c39cb4 100644 --- a/aio/content/errors/NG0100.md +++ b/aio/content/errors/NG0100.md @@ -4,17 +4,36 @@ @shortDescription Expression has changed after it was checked @description -Angular throws an `ExpressionChangedAfterItHasBeenCheckedError` when an expression value has been changed after change detection has completed. Angular only throws this error in development mode. -In development mode, Angular performs an additional check after each change detection run, to ensure the bindings haven’t changed. This catches errors where the view is left in an inconsistent state. This can occur, for example, if a method or getter returns a different value each time it is called, or if a child component changes values on its parent. If either of these occur, this is a sign that change detection is not stabilized. Angular throws the error to ensure data is always reflected correctly in the view, which prevents erratic UI behavior or a possible infinite loop. +Angular throws an `ExpressionChangedAfterItHasBeenCheckedError` when an expression value has been changed after change detection has completed. +Angular only throws this error in development mode. -This error commonly occurs when you’ve added template expressions or begun to implement lifecycle hooks like `ngAfterViewInit` or `ngOnChanges`. It is also common when dealing with loading status and asynchronous operations, or a child component changes its parent bindings. +In development mode, Angular performs an additional check after each change detection run, to ensure the bindings haven't changed. +This catches errors where the view is left in an inconsistent state. +This can occur, for example, if a method or getter returns a different value each time it is called, or if a child component changes values on its parent. +If either of these occur, this is a sign that change detection is not stabilized +Angular throws the error to ensure data is always reflected correctly in the view, which prevents erratic UI behavior or a possible infinite loop. + +This error commonly occurs when you've added template expressions or have begun to implement lifecycle hooks like `ngAfterViewInit` or `ngOnChanges`. +It is also common when dealing with loading status and asynchronous operations, or when a child component changes its parent bindings. @debugging -The [source maps](https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Use_a_source_map) generated by the CLI are very useful when debugging. Navigate up the call stack until you find a template expression where the value displayed in the error has changed. -Ensure that there are no changes to the bindings in the template after change detection is run. This often means refactoring to use the correct [component lifecycle hook](guide/lifecycle-hooks) for your use case. If the issue exists within `ngAfterViewInit`, the recommended solution is to use a constructor or `ngOnInit` to set initial values, or use `ngAfterContentInit` for other value bindings. +The [source maps](https://developer.mozilla.org/docs/Tools/Debugger/How_to/Use_a_source_map) generated by the CLI are very useful when debugging. +Navigate up the call stack until you find a template expression where the value displayed in the error has changed. + +Ensure that there are no changes to the bindings in the template after change detection is run. +This often means refactoring to use the correct [component lifecycle hook](guide/lifecycle-hooks) for your use case. +If the issue exists within `ngAfterViewInit`, the recommended solution is to use a constructor or `ngOnInit` to set initial values, or use `ngAfterContentInit` for other value bindings. If you are binding to methods in the view, ensure that the invocation does not update any of the other bindings in the template. -Read more about which solution is right for you in ['Everything you need to know about the "ExpressionChangedAfterItHasBeenCheckedError" error'](https://indepth.dev/posts/1001/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error) and why this is useful at ['Angular Debugging "Expression has changed after it was checked": Simple Explanation (and Fix)'](https://blog.angular-university.io/angular-debugging/). +Read more about which solution is right for you in ['Everything you need to know about the "ExpressionChangedAfterItHasBeenCheckedError" error'](https://indepth.dev/posts/1001/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error) and why this is useful at ['Angular Debugging "Expression has changed after it was checked": Simple Explanation (and Fix)'](https://blog.angular-university.io/angular-debugging). + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG0200.md b/aio/content/errors/NG0200.md index 4965761fb3409..1f4a75480c451 100644 --- a/aio/content/errors/NG0200.md +++ b/aio/content/errors/NG0200.md @@ -4,9 +4,23 @@ @shortDescription Circular dependency in DI detected while instantiating a provider @description -A cyclic dependency exists when a [dependency of a service](guide/hierarchical-dependency-injection) directly or indirectly depends on the service itself. For example, if `UserService` depends on `EmployeeService`, which also depends on `UserService`. Angular will have to instantiate `EmployeeService` to create `UserService`, which depends on `UserService`, itself. + +A cyclic dependency exists when a [dependency of a service](guide/hierarchical-dependency-injection) directly or indirectly depends on the service itself. +For example, if `UserService` depends on `EmployeeService`, which also depends on `UserService`. +Angular will have to instantiate `EmployeeService` to create `UserService`, which depends on `UserService`, itself. @debugging -Use the call stack to determine where the cyclical dependency exists. You will be able to see if any child dependencies rely on the original file by [mapping out](guide/dependency-injection-in-action) the component, module, or service’s dependencies and identify the loop causing the problem. -Break this loop (or circle) of dependency to resolve this error. This most commonly means removing or refactoring the dependencies to not be reliant on one another. +Use the call stack to determine where the cyclical dependency exists. +You will be able to see if any child dependencies rely on the original file by [mapping out](guide/dependency-injection-in-action) the component, module, or service's dependencies, and identifying the loop causing the problem. + +Break this loop \(or circle\) of dependency to resolve this error. +This most commonly means removing or refactoring the dependencies to not be reliant on one another. + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG0201.md b/aio/content/errors/NG0201.md index c5fd8069f130e..ed13d7ca1cf7c 100644 --- a/aio/content/errors/NG0201.md +++ b/aio/content/errors/NG0201.md @@ -4,17 +4,30 @@ @shortDescription No provider for {token} found! @description + You see this error when you try to inject a service but have not declared a corresponding provider. A provider is a mapping that supplies a value that you can inject into the constructor of a class in your application. Read more on providers in our [Dependency Injection guide](guide/dependency-injection). @debugging -Work backwards from the object where the error states that a [provider](guide/architecture-services) is missing: `No provider for ${this}!`. This is commonly thrown in [services](tutorial/toh-pt4), which require non-existing providers. + +Work backwards from the object where the error states that a [provider](guide/architecture-services) is missing: `No provider for ${this}!`. +This is commonly thrown in [services](tutorial/toh-pt4), which require non-existing providers. To fix the error ensure that your service is registered in the list of providers of an `NgModule` or has the `@Injectable` decorator with a `providedIn` property at top. The most common solution is to add a provider in `@Injectable` using `providedIn`: -```typescript -@Injectable({ providedIn: 'app' }) -``` + + +@Injectable({ providedIn: 'app' }) + + + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG0300.md b/aio/content/errors/NG0300.md index 3d91a5c783d81..4530c50da463c 100644 --- a/aio/content/errors/NG0300.md +++ b/aio/content/errors/NG0300.md @@ -7,15 +7,25 @@ Two or more components use the same [element selector](guide/component-overview#specifying-a-components-css-selector). Because there can only be a single component associated with an element, selectors must be unique strings to prevent ambiguity for Angular. @debugging -Use the element name from the error message to search for places where you’re using the same [selector declaration](guide/architecture-components) in your codebase: +Use the element name from the error message to search for places where you're using the same [selector declaration](guide/architecture-components) in your codebase: -```typescript -@Component({ + + +@Component({ selector: 'YOUR_STRING', - ... + … }) -``` + + Ensure that each component has a unique CSS selector. This will guarantee that Angular renders the component you expect. -If you’re having trouble finding multiple components with this selector tag name, check for components from imported component libraries, such as Angular Material. Make sure you're following the [best practices](guide/styleguide#component-selectors) for your selectors to prevent collisions. +If you're having trouble finding multiple components with this selector tag name, check for components from imported component libraries, such as Angular Material. Make sure you're following the [best practices](guide/styleguide#component-selectors) for your selectors to prevent collisions. + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG0301.md b/aio/content/errors/NG0301.md index 67135f6c1c7ee..b917f91226ee1 100644 --- a/aio/content/errors/NG0301.md +++ b/aio/content/errors/NG0301.md @@ -4,7 +4,10 @@ @shortDescription Export not found! @description -Angular can’t find a directive with `{{ PLACEHOLDER }}` export name. The export name is specified in the `exportAs` property of the directive decorator. This is common when using FormsModule or Material modules in templates, and you’ve forgotten to [import the corresponding modules](guide/sharing-ngmodules). + +Angular can't find a directive with `{{ PLACEHOLDER }}` export name. +The export name is specified in the `exportAs` property of the directive decorator. +This is common when using FormsModule or Material modules in templates and you've forgotten to [import the corresponding modules](guide/sharing-ngmodules).
@@ -13,20 +16,30 @@ This is the runtime equivalent of a common compiler error [NG8003: No directive
@debugging + Use the export name to trace the templates or modules using this export. -Ensure that all dependencies are [properly imported and declared in your NgModules](guide/sharing-ngmodules). For example, if the export not found is `ngForm`, we need to import `FormsModule` and declare it in the list of imports in `*.module.ts` to resolve the error. +Ensure that all dependencies are [properly imported and declared in your NgModules](guide/sharing-ngmodules). +For example, if the export not found is `ngForm`, we need to import `FormsModule` and declare it in the list of imports in `*.module.ts` to resolve the error. + + -```typescript -import { FormsModule } from '@angular/forms'; +import { FormsModule } from '@angular/forms'; -@NgModule({ - ... +@NgModule({ + … imports: [ FormsModule, - … -``` + … + + If you recently added an import, you may need to restart your server to see these changes. + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG0302.md b/aio/content/errors/NG0302.md index 597dbfc9bf978..4690e3c72f622 100644 --- a/aio/content/errors/NG0302.md +++ b/aio/content/errors/NG0302.md @@ -4,15 +4,26 @@ @shortDescription Pipe not found! @description -Angular can't find a pipe with this name. -The pipe referenced in the template has not been named or declared properly. + +Angular can't find a pipe with this name. +The pipe referenced in the template has not been named or declared properly. A [pipe](guide/pipes) must be either declared or imported in the `NgModule` where it is used, and the name used in a template must match the name defined in the pipe decorator. @debugging + Use the pipe name to trace the templates or modules where this pipe is declared and used. To resolve this error, ensure that: -- A local custom pipe is uniquely named in the pipe's decorator, and declared in the `NgModule`, or -- A pipe from another `NgModule` is added to the imports of the `NgModule` where it is used. + +* A local custom pipe is uniquely named in the pipe's decorator, and declared in the `NgModule`, or +* A pipe from another `NgModule` is added to the imports of the `NgModule` where it is used If you recently added an import or declaration, you may need to restart your server to see these changes. + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG1001.md b/aio/content/errors/NG1001.md index 59d25a9fbffcb..7fbfed2c50052 100644 --- a/aio/content/errors/NG1001.md +++ b/aio/content/errors/NG1001.md @@ -3,27 +3,42 @@ @shortDescription Decorator argument is not an object literal @description + To make the metadata extraction in the Angular compiler faster, the decorators `@NgModule`, `@Pipe`, `@Component`, `@Directive`, and `@Injectable` accept only object literals as arguments. -This is an [intentional change in Ivy](https://github.com/angular/angular/issues/30840#issuecomment-498869540), which enforces stricter argument requirements for decorators than View Engine. Ivy requires this approach because it compiles decorators by moving the expressions into other locations in the class output. +This is an [intentional change in Ivy](https://github.com/angular/angular/issues/30840#issuecomment-498869540), which enforces stricter argument requirements for decorators than View Engine. +Ivy requires this approach because it compiles decorators by moving the expressions into other locations in the class output. @debugging + Move all declarations: -```typescript -const moduleDefinition = {...} + + +const moduleDefinition = {…} -@NgModule(moduleDefinition) +@NgModule(moduleDefinition) export class AppModule { constructor() {} } -``` + + into the decorator: -```typescript -@NgModule({...}) + + +@NgModule({…}) export class AppModule { constructor() {} } -``` + + + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG2003.md b/aio/content/errors/NG2003.md index e833c18142cbc..c5059eb797112 100644 --- a/aio/content/errors/NG2003.md +++ b/aio/content/errors/NG2003.md @@ -3,9 +3,21 @@ @shortDescription No suitable injection token for parameter @description + There is no injection token for a constructor parameter at compile time. [InjectionTokens](api/core/InjectionToken) are tokens that can be used in a Dependency Injection Provider. @debugging -Look at the parameter that throws the error and all uses of the class. This error is commonly thrown when a constructor defines parameters with primitive types like `string`, `number`, `boolean`, and `Object`. -Use the `@Injectable` method or `@Inject` decorator from `@angular/core` to ensure that the type you are injecting is reified (has a runtime representation). Make sure to add a provider to this decorator so that you do not throw [NG0201: No Provider Found](errors/NG0201). +Look at the parameter that throws the error, and all uses of the class. +This error is commonly thrown when a constructor defines parameters with primitive types such as `string`, `number`, `boolean`, and `Object`. + +Use the `@Injectable` method or `@Inject` decorator from `@angular/core` to ensure that the type you are injecting is reified \(has a runtime representation\). +Make sure to add a provider to this decorator so that you do not throw [NG0201: No Provider Found](errors/NG0201). + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG2009.md b/aio/content/errors/NG2009.md index 3f9d535be7a52..b83df7f3b85e4 100644 --- a/aio/content/errors/NG2009.md +++ b/aio/content/errors/NG2009.md @@ -3,30 +3,39 @@ @shortDescription Component selector does not match shadow DOM requirements @description + The selector of a component using `ViewEncapsulation.ShadowDom` doesn't match the custom element tag name requirements. In order for a tag name to be considered a valid custom element name, it has to: -* Be in lower case. -* Contain a hyphen. -* Start with a letter (a-z). + +* Be in lower case. +* Contain a hyphen. +* Start with a letter \(a-z\). @debugging + Rename your component's selector so that it matches the requirements. **Before:** -```typescript -@Component({ + + + +@Component({ selector: 'comp', encapsulation: ViewEncapsulation.ShadowDom - ... + … }) -``` + + **After:** -```typescript -@Component({ + + + +@Component({ selector: 'app-comp', encapsulation: ViewEncapsulation.ShadowDom - ... + … }) -``` + + diff --git a/aio/content/errors/NG3003.md b/aio/content/errors/NG3003.md index f65d58a4f5fb9..898c5f8267773 100644 --- a/aio/content/errors/NG3003.md +++ b/aio/content/errors/NG3003.md @@ -4,54 +4,59 @@ @description -A component, directive or pipe that is referenced by this component would require the compiler -to add an import that would lead to a cycle of imports. For example, consider a scenario where -a `ParentComponent` references a `ChildComponent` in its template: +A component, directive, or pipe that is referenced by this component would require the compiler to add an import that would lead to a cycle of imports. +For example, consider a scenario where a `ParentComponent` references a `ChildComponent` in its template: - + - + -There is already an import from `child.component.ts` to `parent.component.ts` since the `ChildComponent` -references the `ParentComponent` in its constructor. +There is already an import from `child.component.ts` to `parent.component.ts` since the `ChildComponent` references the `ParentComponent` in its constructor. -But note that the parent component's template contains ``. The generated code for this -template must therefore contain a reference to the `ChildComponent` class. In order to make this reference -the compiler would have to add an import from `parent.component.ts` to `child.component.ts`, which would -cause an import cycle: +
-``` -parent.component.ts -> child.component.ts -> parent.component.ts -``` +**NOTE**:
+The parent component's template contains ``. +The generated code for this template must therefore contain a reference to the `ChildComponent` class. +In order to make this reference, the compiler would have to add an import from `parent.component.ts` to `child.component.ts`, which would cause an import cycle: -### Remote Scoping + -To avoid adding imports that create cycles, additional code is added to the `NgModule` class where -the component is declared that wires up the dependencies. This is known as "remote scoping". +parent.component.ts -> child.component.ts -> parent.component.ts + -### Libraries +
-Unfortunately, "remote scoping" code is side-effectful, which prevents tree shaking, and cannot -be used in libraries. So when building libraries using the `"compilationMode": "partial"` setting, -any component that would require a cyclic import will cause this `NG3003` compiler error to be raised. +### Remote Scoping + +To avoid adding imports that create cycles, additional code is added to the `NgModule` class where the component that wires up the dependencies is declared. +This is known as "remote scoping". +### Libraries + +Unfortunately, "remote scoping" code is side-effectful —which prevents tree shaking— and cannot be used in libraries. +So when building libraries using the `"compilationMode": "partial"` setting, any component that would require a cyclic import will cause this `NG3003` compiler error to be raised. @debugging -The cycle that would be generated is shown as part of the error message. For example: +The cycle that would be generated is shown as part of the error message. +For example: -The component ChildComponent is used in the template but importing it would create a cycle: -/parent.component.ts -> /child.component.ts -> /parent.component.ts + +The component ChildComponent is used in the template but importing it would create a cycle: +/parent.component.ts -> /child.component.ts -> /parent.component.ts + -Use this to identify how the referenced component, pipe or directive has a dependency back to the -component being compiled. Here are some ideas for fixing the problem: +Use this to identify how the referenced component, pipe, or directive has a dependency back to the component being compiled. +Here are some ideas for fixing the problem: + +* Try to rearrange your dependencies to avoid the cycle. + For example, using an intermediate interface that is stored in an independent file that can be imported to both dependent files without causing an import cycle. + +* Move the classes that reference each other into the same file, to avoid any imports between them. +* Convert import statements to type-only imports \(using `import type` syntax\) if the imported declarations are only used as types, as type-only imports do not contribute to cycles. -* Try to re-arrange your dependencies to avoid the cycle. For example using an intermediate interface -that is stored in an independent file that can be imported to both dependent files without -causing an import cycle. -* Move the classes that reference each other into the same file, to avoid any imports between them. -* Convert import statements to type-only imports (using `import type` syntax) if the imported declarations -are only used as types, as type-only imports do not contribute to cycles. +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG6999.md b/aio/content/errors/NG6999.md index 7d34205306bc4..da996318a2320 100644 --- a/aio/content/errors/NG6999.md +++ b/aio/content/errors/NG6999.md @@ -3,9 +3,11 @@ @shortDescription Invalid @NgModule() metadata @description + This error represents the import or export of an `@NgModule()` that doesn't have valid metadata. @debugging + The library might have been processed with `ngcc`. If this is the case, try removing and reinstalling `node_modules`. This error is likely due to the library being published for Angular Ivy, which cannot be used in this View Engine application. diff --git a/aio/content/errors/NG8001.md b/aio/content/errors/NG8001.md index 4ae217fcec90b..6e279f326cbf7 100644 --- a/aio/content/errors/NG8001.md +++ b/aio/content/errors/NG8001.md @@ -3,19 +3,30 @@ @shortDescription Unknown HTML element or component @description + One or more elements cannot be resolved during compilation because the element is not defined by the HTML spec, or there is no component or directive with such element selector.
-This is the compiler equivalent of a common runtime error `NG0304: '${tagName}' is not a known element: …`. +This is the compiler equivalent of a common runtime error `NG0304: '${tagName}' is not a known element: …`.
@debugging + Use the element name in the error to find the file(s) where the element is being used. -Check that the name and selector are correct. If the component is from a different module or import, check that the component is exported from its origin module and imported into the correct `*.modules.ts` file, and declared in the imports list. +Check that the name and selector are correct. +If the component is from a different module or import, check that the component is exported from its origin module and imported into the correct `*.modules.ts` file, and declared in the imports list. When using custom elements or web components, ensure that you add [`CUSTOM_ELEMENTS_SCHEMA`](api/core/CUSTOM_ELEMENTS_SCHEMA) to the application module. If this does not resolve the error, check the imported libraries for any recent changes to the exports and properties you are using, and restart your server. + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG8002.md b/aio/content/errors/NG8002.md index a0fd6916d5815..05367e258d726 100644 --- a/aio/content/errors/NG8002.md +++ b/aio/content/errors/NG8002.md @@ -4,13 +4,27 @@ @shortDescription Unknown attribute or input @description + An attribute or property cannot be resolved during compilation. -This error arises when attempting to bind to a property that does not exist. Any property binding must correspond to either: -* A native property on the HTML element, or -* An `@Input()` property of a component or directive applied to the element. +This error arises when attempting to bind to a property that does not exist. +Any property binding must correspond to either: + +* A native property on the HTML element, or +* An `@Input()` property of a component or directive applied to the element. -The runtime error for this is `NG0304: '${tagName}' is not a known element: …’`. +The runtime error for this is `NG0304: '${tagName}' is not a known element: …'`. @debugging -Look at documentation for the specific [binding syntax](guide/binding-syntax) used. This is usually a typo or incorrect import. There may also be a missing direction with property selector ‘name’ or missing input. + +Look at documentation for the specific [binding syntax](guide/binding-syntax) used. +This is usually a typo or incorrect import. +There may also be a missing direction with property selector 'name' or missing input. + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/errors/NG8003.md b/aio/content/errors/NG8003.md index f97a30d72f26b..0fcc7e9e838bb 100644 --- a/aio/content/errors/NG8003.md +++ b/aio/content/errors/NG8003.md @@ -4,8 +4,9 @@ @shortDescription No directive found with export @description -Angular can’t find a directive with `{{ PLACEHOLDER }}` export name. This is common with a missing import or a missing [`exportAs`](api/core/Directive#exportAs) on a directive. +Angular can't find a directive with `{{ PLACEHOLDER }}` export name. +This is common with a missing import or a missing [`exportAs`](api/core/Directive#exportAs) on a directive.
@@ -14,18 +15,30 @@ This is the compiler equivalent of a common runtime error [NG0301: Export Not Fo
@debugging + Use the string name of the export not found to trace the templates or modules using this export. -Ensure that all dependencies are properly imported and declared in our Modules. For example, if the export not found is `ngForm`, we will need to import `FormsModule` and declare it in our list of imports in `*.module.ts` to resolve the missing export error. +Ensure that all dependencies are properly imported and declared in our Modules. +For example, if the export not found is `ngForm`, we will need to import `FormsModule` and declare it in our list of imports in `*.module.ts` to resolve the missing export error. + + -```typescript -import { FormsModule } from '@angular/forms'; +import { FormsModule } from '@angular/forms'; -@NgModule({ - ... +@NgModule({ + … imports: [ FormsModule, - … -``` + … + + If you recently added an import, you will need to restart your server to see these changes. + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/examples/angular-linker-plugin/webpack.config.mjs b/aio/content/examples/angular-linker-plugin/webpack.config.mjs index 430a57d171b19..479a307b50e90 100644 --- a/aio/content/examples/angular-linker-plugin/webpack.config.mjs +++ b/aio/content/examples/angular-linker-plugin/webpack.config.mjs @@ -1,4 +1,4 @@ -// #docplaster ... +// #docplaster … // #docregion webpack-config import linkerPlugin from '@angular/compiler-cli/linker/babel'; diff --git a/aio/content/examples/router/src/app/app-routing.module.10.ts b/aio/content/examples/router/src/app/app-routing.module.10.ts new file mode 100644 index 0000000000000..64f0892044025 --- /dev/null +++ b/aio/content/examples/router/src/app/app-routing.module.10.ts @@ -0,0 +1,65 @@ +// #docplaster +import {Injectable, NgModule} from '@angular/core'; +import {Title} from '@angular/platform-browser'; +import { + Resolve, + RouterModule, + RouterStateSnapshot, + Routes, + TitleStrategy, +} from '@angular/router'; // CLI imports router + +// #docregion page-title +const routes: Routes = [ + { + path: 'first-component', + title: 'First component', + component: FirstComponent, // this is the component with the in the template + children: [ + { + path: 'child-a', // child route path + title: ResolvedChildATitle, + component: ChildAComponent, // child route component that the router renders + }, + { + path: 'child-b', + title: 'child b', + component: ChildBComponent, // another child route component that the router renders + }, + ], + }, +]; + +@Injectable({providedIn: 'root'}) +export class ResolvedChildATitle implements Resolve { + resolve() { + return Promise.resolve('child a'); + } +} +// #enddocregion page-title + + +// #docregion custom-page-title +export class TemplatePageTitleStrategy extends TitleStrategy { + constructor(private readonly title: Title) { + super(); + } + + override updateTitle(routerState: RouterStateSnapshot) { + const title = this.buildTitle(routerState); + if (title !== undefined) { + this.title.setTitle(`My Application | ${title}`); + } + } +} + +@NgModule({ + imports: [RouterModule.forRoot(routes)], + exports: [RouterModule], + providers: [ + {provide: TitleStrategy, useClass: TemplatePageTitleStrategy}, + ] +}) +export class AppRoutingModule { +} +// #enddocregion custom-page-title diff --git a/aio/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts b/aio/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts index d463a4ba2945d..e35daf2903be7 100644 --- a/aio/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts +++ b/aio/content/examples/schematics-for-libraries/projects/my-lib/schematics/my-service/index.ts @@ -41,12 +41,6 @@ export function myService(options: MyServiceSchema): Rule { // #enddocregion workspace // #docregion project-info -// #docregion project-fallback - if (!options.project && typeof workspace.extensions.defaultProject === 'string') { - options.project = workspace.extensions.defaultProject; - } -// #enddocregion project-fallback - const project = (options.project != null) ? workspace.projects.get(options.project) : null; if (!project) { throw new SchematicsException(`Invalid project name: ${options.project}`); diff --git a/aio/content/examples/upgrade-phonecat-1-typescript/README.md b/aio/content/examples/upgrade-phonecat-1-typescript/README.md index f3433b901ae9c..5354de2a28608 100644 --- a/aio/content/examples/upgrade-phonecat-1-typescript/README.md +++ b/aio/content/examples/upgrade-phonecat-1-typescript/README.md @@ -1,34 +1,39 @@ -This is the Angular Phonecat application adjusted to fit our boilerplate project -structure. +This is the Angular Phonecat application adjusted to fit our boilerplate project structure. The following changes from vanilla Phonecat are applied: -* The TypeScript config file shown in the guide is `tsconfig.ajs.json` instead - of the default, because we don't want to enable `noImplicitAny` for migration. -* Karma config for unit tests is in karma.conf.ajs.js because the boilerplate - Karma config is not compatible with the way AngularJS tests need to be run. - The shell script run-unit-tests.sh can be used to run the unit tests. -* Instead of using Bower, AngularJS and its dependencies are fetched from a CDN - in index.html and karma.conf.ajs.js. -* E2E tests have been moved to the parent directory, where `gulp run-e2e-tests` can - discover and run them along with all the other examples. -* Most of the phone JSON and image data removed in the interest of keeping - repo weight down. Keeping enough to retain testability of the app. +* The TypeScript config file shown in the guide is `tsconfig.ajs.json` instead of the default, because we don't want to enable `noImplicitAny` for migration. +* Karma config for unit tests is in karma.conf.ajs.js because the boilerplate Karma config is not compatible with the way AngularJS tests need to be run. + The shell script run-unit-tests.sh can be used to run the unit tests. + +* Instead of using Bower, AngularJS and its dependencies are fetched from a CDN in index.html and karma.conf.ajs.js. +* E2E tests have been moved to the parent directory, where `gulp run-e2e-tests` can discover and run them along with all the other examples. +* Most of the phone JSON and image data removed in the interest of keeping repo weight down. Keeping enough to retain testability of the app. ## Running the app Start like any example - npm run start +```shell +npm run start +``` + +You'll find the app under the /app path: -You'll find the app under the /app path: http://localhost:3002/app/index.html +```http +http://localhost:3002/app/index.html +``` ## Running unit tests - ./run-unit-tests.sh +```shell +./run-unit-tests.sh +``` ## Running E2E tests -Like for any example (at the project root): +Like for any example \(at the project root\): - gulp run-e2e-tests --filter=phonecat-1 +```shell +gulp run-e2e-tests --filter=phonecat-1 +``` diff --git a/aio/content/examples/upgrade-phonecat-2-hybrid/README.md b/aio/content/examples/upgrade-phonecat-2-hybrid/README.md index 76eb21fc6cd06..18b7e0260a2f6 100644 --- a/aio/content/examples/upgrade-phonecat-2-hybrid/README.md +++ b/aio/content/examples/upgrade-phonecat-2-hybrid/README.md @@ -1,32 +1,33 @@ -This is the Angular Phonecat application adjusted to fit our boilerplate project -structure. +This is the Angular Phonecat application adjusted to fit our boilerplate project structure. The following changes from vanilla Phonecat are applied: -* Karma config for unit tests is in karma.conf.ajs.js because the boilerplate - Karma config is not compatible with the way AngularJS tests need to be run. - The shell script run-unit-tests.sh can be used to run the unit tests. -* Also for the Karma shim, there is a `karma-test-shim.1.js` file which isn't - used but is shown in the test appendix. -* Instead of using Bower, AngularJS and its dependencies are fetched from a CDN - in index.html and karma.conf.ajs.js. -* E2E tests have been moved to the parent directory, where `run-e2e-tests` can - discover and run them along with all the other examples. -* Most of the phone JSON and image data removed in the interest of keeping - repo weight down. Keeping enough to retain testability of the app. +* Karma config for unit tests is in karma.conf.ajs.js because the boilerplate Karma config is not compatible with the way AngularJS tests need to be run. + The shell script run-unit-tests.sh can be used to run the unit tests. + +* Also for the Karma shim, there is a `karma-test-shim.1.js` file which isn't used but is shown in the test appendix. +* Instead of using Bower, AngularJS and its dependencies are fetched from a CDN in index.html and karma.conf.ajs.js. +* E2E tests have been moved to the parent directory, where `run-e2e-tests` can discover and run them along with all the other examples. +* Most of the phone JSON and image data removed in the interest of keeping repo weight down. Keeping enough to retain testability of the app. ## Running the app Start like any example - npm run start +```shell +npm run start +``` ## Running unit tests - ./run-unit-tests.sh +```shell +./run-unit-tests.sh +``` ## Running E2E tests -Like for any example (at the project root): +Like for any example \(at the project root\): - gulp run-e2e-tests --filter=phonecat-2 +```shell +gulp run-e2e-tests --filter=phonecat-2 +``` diff --git a/aio/content/examples/upgrade-phonecat-3-final/README.md b/aio/content/examples/upgrade-phonecat-3-final/README.md index 83d1f4a7c4163..14e266a323df8 100644 --- a/aio/content/examples/upgrade-phonecat-3-final/README.md +++ b/aio/content/examples/upgrade-phonecat-3-final/README.md @@ -3,19 +3,22 @@ structure. The following changes from vanilla Phonecat are applied: -* E2E tests have been moved to the parent directory, where `run-e2e-tests` can - discover and run them along with all the other examples. -* Most of the phone JSON and image data removed in the interest of keeping - repo weight down. Keeping enough to retain testability of the app. +* E2E tests have been moved to the parent directory, where `run-e2e-tests` can discover and run them along with all the other examples. +* Most of the phone JSON and image data removed in the interest of keeping repo weight down. + Keeping enough to retain testability of the app. ## Running the app Start like any example - npm run start +```shell +npm run start +``` ## Running E2E tests -Like for any example (at the project root): +Like for any example \(at the project root\): - gulp run-e2e-tests --filter=phonecat-3 +```shell +gulp run-e2e-tests --filter=phonecat-3 +``` diff --git a/aio/content/extended-diagnostics/NG8101.md b/aio/content/extended-diagnostics/NG8101.md index 67e109ec32670..db8ac09271af6 100644 --- a/aio/content/extended-diagnostics/NG8101.md +++ b/aio/content/extended-diagnostics/NG8101.md @@ -2,37 +2,42 @@ @description -This diagnostic detects a backwards "banana-in-box" syntax for -[two-way bindings](guide/two-way-binding). +This diagnostic detects a backwards "banana-in-box" syntax for [two-way bindings](guide/two-way-binding). -```html -
-``` + + +<div ([var])="otherVar"></div> + + ## What's wrong with that? -As it stands, `([var])` is actually an [event binding](guide/event-binding) with -the name `[var]`. The author likely intended this as a two-way binding to a variable named -`var` but as written this binding has no effect. +As it stands, `([var])` is actually an [event binding](guide/event-binding) with the name `[var]`. +The author likely intended this as a two-way binding to a variable named `var` but, as written, this binding has no effect. ## What should I do instead? -Fix the typo. As the name suggests, the banana `(` should go *inside* the box `[]`. In this case: +Fix the typo. +As the name suggests, the banana `(` should go *inside* the box `[]`. +In this case: + + -```html -
-``` +<div [(var)]="otherVar"></div> + +
## Configuration requirements -[`strictTemplates`](/guide/template-typecheck#strict-mode) must be enabled for any extended -diagnostic to emit. `invalidBananaInBox` has no additional requirements beyond `strictTemplates`. +[`strictTemplates`](guide/template-typecheck#strict-mode) must be enabled for any extended diagnostic to emit. +`invalidBananaInBox` has no additional requirements beyond `strictTemplates`. ## What if I can't avoid this? This diagnostic can be disabled by editing the project's `tsconfig.json` file: -```json + + { "angularCompilerOptions": { "extendedDiagnostics": { @@ -42,6 +47,15 @@ This diagnostic can be disabled by editing the project's `tsconfig.json` file: } } } -``` + + See [extended diagnostic configuration](extended-diagnostics#configuration) for more info. + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/extended-diagnostics/NG8102.md b/aio/content/extended-diagnostics/NG8102.md index 9206a0b021587..9876ab7f4319a 100644 --- a/aio/content/extended-diagnostics/NG8102.md +++ b/aio/content/extended-diagnostics/NG8102.md @@ -2,81 +2,96 @@ @description -This diagnostic detects a useless nullish coalescing operator (`??`) in Angular templates. -Specifically, it looks for operations where the input is not "nullable", meaning its type does not -include `null` or `undefined`. For such values, the right side of the `??` will never be used. - -```typescript -import {Component} from '@angular/core'; - -@Component({ - // Template displays `foo` if present, falls back to 'bar' if it is `null` - // or `undefined`. - template: `
{{ foo ?? 'bar' }}
`, - // ... +This diagnostic detects a useless nullish coalescing operator \(`??`\) characters in Angular templates. +Specifically, it looks for operations where the input is not "nullable", meaning its type does not include `null` or `undefined`. +For such values, the right side of the `??` will never be used. + + + +import {Component} from '@angular/core'; + +@Component({ + // Template displays `foo` if present, falls back to 'bar' if it is `null` + // or `undefined`. + template: ` + <div> + {{ foo ?? 'bar' }} + </div> + `, + // … }) class MyComponent { - // `foo` is declared as a `string` which *cannot* be `null` or `undefined`. + // `foo` is declared as a `string` which *cannot* be `null` or `undefined`. foo: string = 'test'; } -``` + + ## What's wrong with that? -Using the nullish coalescing operator with a non-nullable input has no effect and is indicative of a -discrepancy between the allowed type of a value and how it is presented in the template. A developer -might reasonably assume that the right side of the nullish coalescing operator is displayed in some -case, but it will never actually be displayed. This can lead to confusion about the expected output -of the program. +Using the nullish coalescing operator with a non-nullable input has no effect and is indicative of a discrepancy between the allowed type of a value and how it is presented in the template. +A developer might reasonably assume that the right side of the nullish coalescing operator is displayed in some case, but it will never actually be displayed. +This can lead to confusion about the expected output of the program. ## What should I do instead? -Update the template and declared type to be in sync. Double check the type of the input and confirm -whether it is actually expected to be nullable. +Update the template and declared type to be in sync. +Double-check the type of the input and confirm whether it is actually expected to be nullable. If the input should be nullable, add `null` or `undefined` to its type to indicate this. -```typescript -import {Component} from '@angular/core'; + + +import {Component} from '@angular/core'; -@Component({ - template: `
{{ foo ?? 'bar' }}
`, - // ... +@Component({ + template: ` + <div> + {{ foo ?? 'bar' }} + <l/div> + `, + // … }) class MyComponent { - // `foo` is now nullable. If it is ever set to `null`, 'bar' will be displayed. - foo: string | null = 'test'; + // `foo` is now nullable. If it is ever set to `null`, 'bar' will be displayed. + foo: string | null = 'test'; } -``` -If the input should *not* be nullable, delete the `??` operator and its right operand, since the -value is guaranteed by TypeScript to always be non-nullable. +
+ +If the input should *not* be nullable, delete the `??` operator and its right operand, since the value is guaranteed by TypeScript to always be non-nullable. -```typescript -import {Component} from '@angular/core'; + -@Component({ - // Template always displays `foo`, which is guaranteed to never be `null` or - // `undefined`. - template: `
{{ foo }}
`, - // ... +import {Component} from '@angular/core'; + +@Component({ + // Template always displays `foo`, which is guaranteed to never be `null` or + // `undefined`. + template: ` + <div> + {{ foo }} + </div> + `, + // … }) class MyComponent { foo: string = 'test'; } -``` + +
## Configuration requirements -[`strictTemplates`](/guide/template-typecheck#strict-mode) must be enabled for any extended -diagnostic to emit. [`strictNullChecks`](/guide/template-typecheck#strict-null-checks) must also be -enabled to emit any `nullishCoalescingNotNullable` diagnostics. +[`strictTemplates`](guide/template-typecheck#strict-mode) must be enabled for any extended diagnostic to emit. +[`strictNullChecks`](guide/template-typecheck#strict-null-checks) must also be enabled to emit any `nullishCoalescingNotNullable` diagnostics. ## What if I can't avoid this? This diagnostic can be disabled by editing the project's `tsconfig.json` file: -```json + + { "angularCompilerOptions": { "extendedDiagnostics": { @@ -86,6 +101,15 @@ This diagnostic can be disabled by editing the project's `tsconfig.json` file: } } } -``` + + See [extended diagnostic configuration](extended-diagnostics#configuration) for more info. + + + + + + + +@reviewed 2022-02-28 diff --git a/aio/content/extended-diagnostics/index.md b/aio/content/extended-diagnostics/index.md index be815ea724a3a..f516dc84dd966 100644 --- a/aio/content/extended-diagnostics/index.md +++ b/aio/content/extended-diagnostics/index.md @@ -1,32 +1,33 @@ # Extended Diagnostics -There are many coding patterns that are technically valid to the compiler or runtime, but which may -have complex nuances or caveats. These patterns may not have the intended effect expected by a -developer, which often leads to bugs. The Angular compiler includes "extended diagnostics" which -identify many of these patterns to warn developers about the potential issues and enforce common -best practices within a codebase. +There are many coding patterns that are technically valid to the compiler or runtime, but which may have complex nuances or caveats. +These patterns may not have the intended effect expected by a developer, which often leads to bugs. +The Angular compiler includes "extended diagnostics" which identify many of these patterns, in order to warn developers about the potential issues and enforce common best practices within a codebase. ## Diagnostics Currently, Angular supports the following extended diagnostics: -* [NG8101 - `invalidBananaInBox`](extended-diagnostics/NG8101) -* [NG8102 - `nullishCoalescingNotNullable`](extended-diagnostics/NG8102) +* [NG8101 - `invalidBananaInBox`](extended-diagnostics/NG8101) +* [NG8102 - `nullishCoalescingNotNullable`](extended-diagnostics/NG8102) ## Configuration -Extended diagnostics are warnings by default and do not block compilation. Each diagnostic can be -configured as either: +Extended diagnostics are warnings by default and do not block compilation. +Each diagnostic can be configured as either: -* `warning` (default) - The compiler emits the diagnostic as a warning but does not block - compilation. The compiler will still exit with status code 0, even if warnings are emitted. -* `error` - The compiler emits the diagnostic as an error and fails the compilation. The compiler - will exit with a non-zero status code if one or more errors are emitted. -* `suppress` - The compiler does *not* emit the diagnostic at all. +* `warning` \(default\) - The compiler emits the diagnostic as a warning but does not block compilation. + The compiler will still exit with status code 0, even if warnings are emitted. + +* `error` - The compiler emits the diagnostic as an error and fails the compilation. + The compiler will exit with a non-zero status code if one or more errors are emitted. + +* `suppress` - The compiler does *not* emit the diagnostic at all. Check severity can be configured in the project's `tsconfig.json` file: -```jsonc + + { "angularCompilerOptions": { "extendedDiagnostics": { @@ -36,50 +37,53 @@ Check severity can be configured in the project's `tsconfig.json` file: "invalidBananaInBox": "suppress" }, - // The category to use for any diagnostics not listed in `checks` above. + // The category to use for any diagnostics not listed in `checks` above. "defaultCategory": "error" } } } -``` -The `checks` field maps the name of individual diagnostics to their associated category. See -[Diagnostics](#diagnostics) for a complete list of extended diagnostics and the name to use for -configuring them. + + +The `checks` field maps the name of individual diagnostics to their associated category. +See [Diagnostics](#diagnostics) for a complete list of extended diagnostics and the name to use for configuring them. -The `defaultCategory` field is used for any diagnostics that are not explicitly listed under -`checks`. If not set, such diagnostics will be treated as `warning`. +The `defaultCategory` field is used for any diagnostics that are not explicitly listed under `checks`. +If not set, such diagnostics will be treated as `warning`. -Extended diagnostics will emit when [`strictTemplates`](/guide/template-typecheck#strict-mode) is -enabled. This is required to allow the compiler to better understand Angular template types and -provide accurate and meaningful diagnostics. +Extended diagnostics will emit when [`strictTemplates`](guide/template-typecheck#strict-mode) is enabled. +This is required to allow the compiler to better understand Angular template types and provide accurate and meaningful diagnostics. ## Semantic Versioning -The Angular team intends to add or enable new extended diagnostics in **minor** versions of Angular -(see [semver](https://docs.npmjs.com/about-semantic-versioning)). This means that upgrading Angular -may show new warnings in your existing codebase. This enables the team to deliver features more -quickly and to make extended diagnostics more accessible to developers. +The Angular team intends to add or enable new extended diagnostics in **minor** versions of Angular (see [semver](https://docs.npmjs.com/about-semantic-versioning)). +This means that upgrading Angular may show new warnings in your existing codebase. +This enables the team to deliver features more quickly and to make extended diagnostics more accessible to developers. -However, setting `"defaultCategory": "error"` will promote such warnings to hard errors. This can -cause a minor version upgrade to introduce compilation errors, which may be seen as a semver -non-compliant breaking change. Any new diagnostics can be suppressed or demoted to warnings via the -above [configuration](#configuration), so the impact of a new diagnostic should be minimal to -projects that treat extended diagnostics as errors by default. Defaulting to error is a very -powerful tool; just be aware of this semver caveat when deciding if `error` is the right default for -your project. +However, setting `"defaultCategory": "error"` will promote such warnings to hard errors. +This can cause a minor version upgrade to introduce compilation errors, which may be seen as a semver non-compliant breaking change. +Any new diagnostics can be suppressed or demoted to warnings via the above [configuration](#configuration), so the impact of a new diagnostic should be minimal to +projects that treat extended diagnostics as errors by default. +Defaulting to error is a very powerful tool; just be aware of this semver caveat when deciding if `error` is the right default for your project. ## New Diagnostics -The Angular team is always open to suggestions about new diagnostics that could be added. Extended -diagnostics should generally: +The Angular team is always open to suggestions about new diagnostics that could be added. +Extended diagnostics should generally: + +* Detect a common, non-obvious developer mistake with Angular templates +* Clearly articulate why this pattern can lead to bugs or unintended behavior +* Suggest one or more clear solutions +* Have a low \(preferrably zero\) false-positive rate +* Apply to the vast majority of Angular applications \(not specific to an unofficial library\) +* Improve program correctness or performance \(not style, that responsibility falls to a linter\) + +If you have an idea for a compiler check which fits these criteria, consider filing a [feature request](https://github.com/angular/angular/issues/new?template=2-feature-request.yaml). + + + + -* Detect a common, non-obvious developer mistake with Angular templates. -* Clearly articulate why this pattern can lead to bugs or unintended behavior. -* Suggest one or more clear solutions. -* Have a low (preferrably zero) false-positive rate. -* Apply to the vast majority of Angular applications (not specific to an unofficial library). -* Improve program correctness or performance (not style, that responsibility falls to a linter). + -If you have an idea for a compiler check which fits these criteria, consider filing a -[feature request](https://github.com/angular/angular/issues/new?template=2-feature-request.yaml). +@reviewed 2022-02-28 diff --git a/aio/content/guide/accessibility.md b/aio/content/guide/accessibility.md index e813e226eecaf..7d1f4edaf5119 100644 --- a/aio/content/guide/accessibility.md +++ b/aio/content/guide/accessibility.md @@ -1,65 +1,70 @@ # Accessibility in Angular The web is used by a wide variety of people, including those who have visual or motor impairments. -A variety of assistive technologies are available that make it much easier for these groups to -interact with web-based software applications. +A variety of assistive technologies are available that make it much easier for these groups to interact with web-based software applications. In addition, designing an application to be more accessible generally improves the user experience for all users. -For an in-depth introduction to issues and techniques for designing accessible applications, see the [Accessibility](https://developers.google.com/web/fundamentals/accessibility/#what_is_accessibility) section of the Google's [Web Fundamentals](https://developers.google.com/web/fundamentals/). +For an in-depth introduction to issues and techniques for designing accessible applications, see the [Accessibility](https://developers.google.com/web/fundamentals/accessibility/#what_is_accessibility) section of the Google's [Web Fundamentals](https://developers.google.com/web/fundamentals). -This page discusses best practices for designing Angular applications that -work well for all users, including those who rely on assistive technologies. +This page discusses best practices for designing Angular applications that work well for all users, including those who rely on assistive technologies.
- For the sample application that this page describes, see the . +For the sample application that this page describes, see the .
## Accessibility attributes -Building accessible web experience often involves setting [ARIA attributes](https://developers.google.com/web/fundamentals/accessibility/semantics-aria) -to provide semantic meaning where it might otherwise be missing. +Building accessible web experience often involves setting [ARIA attributes](https://developers.google.com/web/fundamentals/accessibility/semantics-aria) to provide semantic meaning where it might otherwise be missing. Use [attribute binding](guide/attribute-binding) template syntax to control the values of accessibility-related attributes. -When binding to ARIA attributes in Angular, you must use the `attr.` prefix, as the ARIA -specification depends specifically on HTML attributes rather than properties of DOM elements. +When binding to ARIA attributes in Angular, you must use the `attr.` prefix, as the ARIA specification depends specifically on HTML attributes rather than properties of DOM elements. -```html - - -``` + -Note that this syntax is only necessary for attribute _bindings_. -Static ARIA attributes require no extra syntax. +<!-- Use 'attr.' when binding to an ARIA attribute --> +<button [attr.aria-label]="myActionLabel">…</button> -```html - - -``` +
- By convention, HTML attributes use lowercase names (`tabindex`), while properties use camelCase names (`tabIndex`). +**NOTE**
+This syntax is only necessary for attribute *bindings*. +Static ARIA attributes require no extra syntax. + + - See the [Binding syntax](guide/binding-syntax#html-attribute-vs-dom-property) guide for more background on the difference between attributes and properties. +<!-- Static ARIA attributes require no extra syntax --> +<button aria-label="Save document">…</button> + +
+
+ +By convention, HTML attributes use lowercase names \(`tabindex`\), while properties use camelCase names \(`tabIndex`\). + +See the [Binding syntax](guide/binding-syntax#html-attribute-vs-dom-property) guide for more background on the difference between attributes and properties. + +
## Angular UI components -The [Angular Material](https://material.angular.io/) library, which is maintained by the Angular team, is a suite of reusable UI components that aims to be fully accessible. +The [Angular Material](https://material.angular.io) library, which is maintained by the Angular team, is a suite of reusable UI components that aims to be fully accessible. The [Component Development Kit (CDK)](https://material.angular.io/cdk/categories) includes the `a11y` package that provides tools to support various areas of accessibility. For example: -* `LiveAnnouncer` is used to announce messages for screen-reader users using an `aria-live` region. See the W3C documentation for more information on [aria-live regions](https://www.w3.org/WAI/PF/aria-1.1/states_and_properties#aria-live). +* `LiveAnnouncer` is used to announce messages for screen-reader users using an `aria-live` region. + See the W3C documentation for more information on [aria-live regions](https://www.w3.org/WAI/PF/aria-1.1/states_and_properties#aria-live). -* The `cdkTrapFocus` directive traps Tab-key focus within an element. Use it to create accessible experience for components like modal dialogs, where focus must be constrained. +* The `cdkTrapFocus` directive traps Tab-key focus within an element. + Use it to create accessible experience for components such as modal dialogs, where focus must be constrained. For full details of these and other tools, see the [Angular CDK accessibility overview](https://material.angular.io/cdk/a11y/overview). - ### Augmenting native elements Native HTML elements capture a number of standard interaction patterns that are important to accessibility. @@ -68,17 +73,15 @@ When authoring Angular components, you should re-use these native elements direc For example, instead of creating a custom element for a new variety of button, create a component that uses an attribute selector with a native `