### Router Setup with Features
Source: https://v20.angular.dev/api/router/provideRouter
An example showing how to configure the Router with additional features like debug tracing and custom router configuration.
```typescript
const appRoutes: Routes = [];
bootstrapApplication(AppComponent,
{
providers: [
provideRouter(appRoutes,
withDebugTracing(),
withRouterConfig({paramsInheritanceStrategy: 'always'}))
]
}
);
```
--------------------------------
### Basic Server Rendering Setup
Source: https://v20.angular.dev/api/platform-server/provideServerRendering
Example of how to add server support to your application by including provideServerRendering in the bootstrapApplication providers.
```typescript
bootstrapApplication(AppComponent, { providers: [provideServerRendering()]});
```
--------------------------------
### Enable autocompletion via CLI prompt
Source: https://v20.angular.dev/cli/completion
Example of the automated setup prompt provided by the Angular CLI.
```bash
$ ng serve? Would you like to enable autocompletion? This will set up your terminal so pressing TAB while typing Angular CLI commands will show possible options and autocomplete arguments. (Enabling autocompletion will modify configuration files in your home directory.) YesAppended `source <(ng completion script)` to `/home/my-username/.bashrc`. Restart your terminal or run:source <(ng completion script)to autocomplete `ng` commands.# Serve output...
```
--------------------------------
### Basic Router Setup
Source: https://v20.angular.dev/api/router/provideRouter
A basic example demonstrating how to add Router functionality to an Angular application using provideRouter with an empty routes array.
```typescript
const appRoutes: Routes = [];
bootstrapApplication(AppComponent, {
providers: [provideRouter(appRoutes)]
});
```
--------------------------------
### Configuring an Initialization Function
Source: https://v20.angular.dev/api/core/provideAppInitializer
Example showing how to use provideAppInitializer within bootstrapApplication to load external data before the application starts.
```typescript
bootstrapApplication(App, { providers: [ provideAppInitializer(() => { const http = inject(HttpClient); return firstValueFrom( http .get("https://someUrl.com/api/user") .pipe(tap(user => { ... })) ); }), provideHttpClient(), ],});
```
--------------------------------
### Simple NgComponentOutlet Example
Source: https://v20.angular.dev/api/common/NgComponentOutlet
A basic example demonstrating the creation of a 'HelloWorld' component using NgComponentOutlet.
```typescript
@Component({
selector: 'hello-world',
template: 'Hello World!',
})
export class HelloWorld {}
@Component({
selector: 'ng-component-outlet-simple-example',
imports: [NgComponentOutlet],
template: ``,
})
export class NgComponentOutletSimpleExample {
// This field is necessary to expose HelloWorld to the template.
HelloWorld = HelloWorld;
}
```
--------------------------------
### Manual Application Bootstrapping Example
Source: https://v20.angular.dev/api/core/DoBootstrap
Example of implementing DoBootstrap to manually bootstrap an AppComponent using ApplicationRef.bootstrap().
```typescript
class AppModule implements DoBootstrap {
ngDoBootstrap(appRef: ApplicationRef) {
appRef.bootstrap(AppComponent);
}
}
```
--------------------------------
### Bootstrap Module Example
Source: https://v20.angular.dev/api/core/PlatformRef
A simple example demonstrating how to bootstrap an NgModule using the platform browser.
```typescript
@NgModule({ imports: [BrowserModule]})class MyModule {}let moduleRef = platformBrowser().bootstrapModule(MyModule);
```
--------------------------------
### FactoryProvider Usage Examples
Source: https://v20.angular.dev/api/core/FactoryProvider
Examples demonstrating standard factory usage, optional dependency injection, and multi-provider configuration.
```typescript
const Location = new InjectionToken('location'); const Hash = new InjectionToken('hash'); const injector = Injector.create({ providers: [ {provide: Location, useValue: 'https://angular.io/#someLocation'}, { provide: Hash, useFactory: (location: string) => location.split('#')[1], deps: [Location], }, ], }); expect(injector.get(Hash)).toEqual('someLocation');
```
```typescript
const Location = new InjectionToken('location'); const Hash = new InjectionToken('hash'); const injector = Injector.create({ providers: [ { provide: Hash, useFactory: (location: string) => `Hash for: ${location}`, // use a nested array to define metadata for dependencies. deps: [[new Optional(), Location]], }, ], }); expect(injector.get(Hash)).toEqual('Hash for: null');
```
```typescript
const locale = new InjectionToken('locale'); const injector = Injector.create({ providers: [ {provide: locale, multi: true, useValue: 'en'}, {provide: locale, multi: true, useValue: 'sk'}, ], }); const locales: string[] = injector.get(locale); expect(locales).toEqual(['en', 'sk']);
```
--------------------------------
### Setup Function for Testing Without beforeEach()
Source: https://v20.angular.dev/context/llm-files/llms-full.txt
Organize reusable test setup logic into a setup function instead of using beforeEach(). This function returns an object with test-specific variables.
```typescript
function setup() {
const masterService = new MasterService();
const getSpy = spyOn(masterService, 'get');
return { masterService, getSpy };
}
```
--------------------------------
### Create BannerComponent (Minimal Setup)
Source: https://v20.angular.dev/guide/testing/components-basics
A minimal test to verify component creation without extensive setup in beforeEach.
```typescript
describe('BannerComponent (minimal)', () => {
it('should create', () => {
TestBed.configureTestingModule({imports: [BannerComponent]});
const fixture = TestBed.createComponent(BannerComponent);
const component = fixture.componentInstance;
expect(component).toBeDefined();
});
});
```
--------------------------------
### Navigate and Install Dependencies
Source: https://v20.angular.dev/tools/cli/schematics-authoring
Commands to change directory into the new schematics project, install npm dependencies, and build the project.
```bash
cd hello-world
npm install
npm run build
code .
```
--------------------------------
### Standalone Application Initialization Example
Source: https://v20.angular.dev/api/core/APP_INITIALIZER
Example of configuring APP_INITIALIZER with a function returning a Promise for standalone applications. Requires provideHttpClient.
```typescript
function initializeApp() { const http = inject(HttpClient); return firstValueFrom ( http .get("https://someUrl.com/api/user") .pipe(tap(user => { ... })) ); }bootstrapApplication(App, { providers: [ provideHttpClient(), { provide: APP_INITIALIZER, useValue: initializeApp, multi: true, }, ],});
```
--------------------------------
### Complete NgComponentOutlet Example
Source: https://v20.angular.dev/api/common/NgComponentOutlet
A comprehensive example showcasing NgComponentOutlet with inputs, a custom injector, and projected content.
```typescript
@Injectable()
export class Greeter {
suffix = '!';
}
@Component({
selector: 'complete-component',
template: `{{ label() }}: {{ greeter.suffix }}`,
})
export class CompleteComponent {
label = input.required();
constructor(public greeter: Greeter) {}
}
@Component({
selector: 'ng-component-outlet-complete-example',
imports: [NgComponentOutlet],
template: `
AhojSvet`,
})
export class NgComponentOutletCompleteExample {
// This field is necessary to expose CompleteComponent to the template.
CompleteComponent = CompleteComponent;
myInputs = {'label': 'Complete'};
myInjector: Injector;
ahojTemplateRef = viewChild.required>('ahoj');
svetTemplateRef = viewChild.required>('svet');
myContent?: any[][];
constructor(
injector: Injector,
private vcr: ViewContainerRef,
) {
this.myInjector = Injector.create({
providers: [{provide: Greeter, deps: []}],
parent: injector,
});
effect(() => {
this.myContent = [
this.vcr.createEmbeddedView(this.ahojTemplateRef()).rootNodes,
this.vcr.createEmbeddedView(this.svetTemplateRef()).rootNodes,
];
});
}
}
```
--------------------------------
### Example angular.json deploy configuration
Source: https://v20.angular.dev/cli/deploy
An example of how a deployment configuration might look in the angular.json file after adding a deployment package.
```json
"projects": {
"my-project": {
...
"architect": {
...
"deploy": {
"builder": "@angular/fire:deploy",
"options": {}
}
}
}
}
```
--------------------------------
### ConstructorProvider Usage Examples
Source: https://v20.angular.dev/api/core/ConstructorProvider
Basic usage of ConstructorProvider for dependency injection and an example of multi-value provider configuration.
```typescript
class Square { name = 'square'; } const injector = Injector.create({providers: [{provide: Square, deps: []}]}); const shape: Square = injector.get(Square); expect(shape.name).toEqual('square'); expect(shape instanceof Square).toBe(true);
```
```typescript
const locale = new InjectionToken('locale'); const injector = Injector.create({ providers: [ {provide: locale, multi: true, useValue: 'en'}, {provide: locale, multi: true, useValue: 'sk'}, ], }); const locales: string[] = injector.get(locale); expect(locales).toEqual(['en', 'sk']);
```
--------------------------------
### Install Libraries with npm
Source: https://v20.angular.dev/tools/libraries/using-libraries
Install jQuery, Popper.js, and Bootstrap using npm. These are common dependencies for web applications.
```bash
npm install jquery --savenpm install popper.js --savenpm install bootstrap --save
```
--------------------------------
### Wait for stability before starting polling
Source: https://v20.angular.dev/api/core/ApplicationRef
This example correctly waits for the application to become stable before starting a polling process. The success message is logged, and then the counter starts incrementing.
```typescript
constructor(appRef: ApplicationRef) { appRef.isStable.pipe( first(stable => stable), tap(stable => console.log('App is stable now')), switchMap(() => interval(1000)) ).subscribe(counter => console.log(counter));}
```
--------------------------------
### Get Slider Thumb Value
Source: https://v20.angular.dev/context/llm-files/llms-full.txt
Example of using the Angular Material slider component harness to get the value of the slider thumb.
```typescript
it('should get value of slider thumb', async () => {
const slider = await loader.getHarness(MatSliderHarness);
const thumb = await slider.getEndThumb();
expect(await thumb.getValue()).toBe(50);
});
```
--------------------------------
### Complete Component Test Setup
Source: https://v20.angular.dev/context/llm-files/llms-full.txt
This code block shows the complete beforeEach setup for testing the WelcomeComponent, including TestBed configuration and service injection.
```typescript
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [WelcomeComponent],
providers: [UserService] // UserService is provided here
})
.compileComponents();
fixture = TestBed.createComponent(WelcomeComponent);
component = fixture.componentInstance;
// Get the UserService from the root injector
userService = TestBed.inject(UserService);
// Get the element with the welcome message
el = fixture.debugElement.query(By.css('.welcome-message'));
});
```
--------------------------------
### Basic Router Configuration Example
Source: https://v20.angular.dev/api/router/withRouterConfig
Demonstrates how to provide extra configuration options, such as 'onSameUrlNavigation: 'reload'', when setting up the router using bootstrapApplication.
```typescript
const appRoutes: Routes = [];bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withRouterConfig({ onSameUrlNavigation: 'reload' })) ] });
```
--------------------------------
### GET Request Examples
Source: https://v20.angular.dev/api/common/http/HttpClient
This section details various ways to use the GET method for fetching data, including different response types and observation options.
```APIDOC
## GET /websites/v20_angular_dev
### Description
Fetches resources from the server. This endpoint supports various configurations for response observation and type.
### Method
GET
### Endpoint
/websites/v20_angular_dev
### Parameters
#### Query Parameters
- **url** (string) - Required - The URL to fetch.
- **options** (object) - Optional - Configuration options for the request.
- **headers** (HttpHeaders | Record) - Optional - Sets request headers.
- **observe** (string) - Required - Specifies how to observe the response ('events' or 'response').
- **context** (HttpContext) - Optional - Sets the HttpContext for the request.
- **params** (HttpParams | Record) - Optional - Sets request parameters.
- **reportProgress** (boolean) - Optional - Enables reporting of progress events.
- **responseType** (string) - Optional - Specifies the response type ('arraybuffer', 'blob', 'json', 'text').
- **withCredentials** (boolean) - Optional - Indicates whether to send credentials.
- **credentials** (RequestCredentials) - Optional - Sets the credentials for the request.
- **keepalive** (boolean) - Optional - Indicates if the connection should be kept alive.
- **priority** (RequestPriority) - Optional - Sets the priority of the request.
- **cache** (RequestCache) - Optional - Configures caching for the request.
- **mode** (RequestMode) - Optional - Sets the mode for the request (e.g., 'cors', 'no-cors').
- **redirect** (RequestRedirect) - Optional - Specifies the redirect behavior.
- **referrer** (string) - Optional - Sets the referrer header.
- **integrity** (string) - Optional - Provides the integrity value for subresource integrity.
- **transferCache** (boolean | { includeHeaders?: string[] | undefined; }) - Optional - Configures transfer cache.
- **timeout** (number) - Optional - Sets a timeout for the request in milliseconds.
### Request Example
```json
{
"url": "/api/data",
"options": {
"observe": "response",
"responseType": "json"
}
}
```
### Response
#### Success Response (200)
- **body** (any) - The response body, type depends on `responseType`.
- **status** (number) - The HTTP status code.
- **headers** (HttpHeaders) - The response headers.
#### Response Example
```json
{
"body": {
"message": "Success"
},
"status": 200,
"headers": {
"Content-Type": "application/json"
}
}
```
```
--------------------------------
### NgZone Usage Example
Source: https://v20.angular.dev/api/core/NgZone
Basic setup for using NgZone within an Angular component.
```typescript
import {Component, NgZone} from '@angular/core';@Component({ selector: 'ng-zone-demo', template: `
Demo: NgZone
Progress: {{progress}}%
```
--------------------------------
### Component Setup with TestBed.inject()
Source: https://v20.angular.dev/guide/testing/components-scenarios
Complete `beforeEach` block demonstrating the setup for testing a component, including injecting services using `TestBed.inject()`.
```typescript
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [WelcomeComponent],
providers: [UserService] // UserService is provided in the root testing module
}).compileComponents();
fixture = TestBed.createComponent(WelcomeComponent);
// userService = TestBed.inject(UserService);
});
```
--------------------------------
### Subscribe to isStable and start polling
Source: https://v20.angular.dev/api/core/ApplicationRef
This example shows a common mistake where a polling process is started before the application is stable. As a result, `isStable` will never emit `true`, and the success message will not be logged.
```typescript
constructor(appRef: ApplicationRef) { appRef.isStable.pipe( filter(stable => stable) ).subscribe(() => console.log('App is stable now'); interval(1000).subscribe(counter => console.log(counter));}
```
--------------------------------
### Initialize a FormGroup for error checking
Source: https://v20.angular.dev/api/forms/AbstractControlDirective
Example setup for a nested FormGroup to demonstrate path-based error checking.
```typescript
form = new FormGroup({ address: new FormGroup({ street: new FormControl() })});
```
--------------------------------
### Basic Component Setup and Test
Source: https://v20.angular.dev/guide/testing/components-basics
Sets up a basic Angular component test environment using `TestBed` and verifies that the component instance can be created.
```typescript
import {DebugElement} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {BannerComponent} from './banner-initial.component';
describe('BannerComponent (initial CLI generated)', () => {
let component: BannerComponent;
let fixture: ComponentFixture;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({imports: [BannerComponent]});
}));
beforeEach(() => {
fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeDefined();
});
});
describe('BannerComponent (minimal)', () => {
it('should create', () => {
TestBed.configureTestingModule({imports: [BannerComponent]});
const fixture = TestBed.createComponent(BannerComponent);
const component = fixture.componentInstance;
expect(component).toBeDefined();
});
});
describe('BannerComponent (with beforeEach)', () => {
let component: BannerComponent;
let fixture: ComponentFixture;
beforeEach(() => {
TestBed.configureTestingModule({imports: [BannerComponent]});
fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeDefined();
});
it('should contain "banner works!"', () => {
const bannerElement: HTMLElement = fixture.nativeElement;
expect(bannerElement.textContent).toContain('banner works!');
});
it('should have
with "banner works!"', () => {
const bannerElement: HTMLElement = fixture.nativeElement;
const p = bannerElement.querySelector('p')!;
expect(p.textContent).toEqual('banner works!');
});
it('should find the
with fixture.debugElement.nativeElement', () => {
const bannerDe: DebugElement = fixture.debugElement;
const bannerEl: HTMLElement = bannerDe.nativeElement;
const p = bannerEl.querySelector('p')!;
expect(p.textContent).toEqual('banner works!');
});
it('should find the
with fixture.debugElement.query(By.css)', () => {
const bannerDe: DebugElement = fixture.debugElement;
const paragraphDe = bannerDe.query(By.css('p'));
const p: HTMLElement = paragraphDe.nativeElement;
expect(p.textContent).toEqual('banner works!');
});
});
```
--------------------------------
### Example URL String
Source: https://v20.angular.dev/api/router/DefaultUrlSerializer
A sample URL string demonstrating the syntax supported by the DefaultUrlSerializer.
```text
/inbox/33(popup:compose)/inbox/33;open=true/messages/44
```
--------------------------------
### Angular @Self Decorator Usage Example
Source: https://v20.angular.dev/api/core/Self
This example demonstrates how to use the @Self decorator to resolve a dependency from the local injector. Resolution starts locally and moves up the injector hierarchy. Child injectors configured with @Self() for the same dependency will fail to resolve it.
```typescript
class Dependency {}
@Injectable()
class NeedsDependency {
constructor(@Self() public dependency: Dependency) {}
}
let inj = Injector.create({
providers: [
{provide: Dependency, deps: []},
{provide: NeedsDependency, deps: [[new Self(), Dependency]]},
],
});
const nd = inj.get(NeedsDependency);
expect(nd.dependency instanceof Dependency).toBe(true);
const child = Injector.create({
providers: [{provide: NeedsDependency, deps: [[new Self(), Dependency]]}],
parent: inj,
});
expect(() => child.get(NeedsDependency)).toThrowError();
```
--------------------------------
### SlicePipe Usage Example
Source: https://v20.angular.dev/api/common/SlicePipe
Demonstrates how to use the SlicePipe in a template to extract a subset of elements from a value. The start and end parameters are optional.
```html
{{ value_expression | slice:start:end }}
```
--------------------------------
### Get Currency Symbol using Intl API
Source: https://v20.angular.dev/api/common/getCurrencySymbol
Example of how to extract the currency symbol using the Intl API, which is the recommended approach for i18n.
```typescript
Intl.NumberFormat('en', {style:'currency', currency: 'USD'}).formatToParts().find(part => part.type === 'currency').value
```
--------------------------------
### Component Setup with @if and @else
Source: https://v20.angular.dev/tutorials/learn-angular/4-control-flow-if
Example of an Angular component demonstrating the @if and @else control flow syntax. Includes the component decorator and class definition with a boolean property.
```typescript
import {Component} from '@angular/core';
@Component({
selector: 'app-root',
template: `
Yes, the server is running
`,
})
export class App {
// add the boolean property here
}
```
--------------------------------
### $location.path() - Get or Set Path
Source: https://v20.angular.dev/api/common/upgrade/%24locationShim
Retrieves the path of the current URL or sets a new path. Paths should start with a forward slash. Returns a reference to its own instance when setting.
```APIDOC
## GET /path
### Description
Retrieves the path of the current URL.
### Method
GET
### Endpoint
$location.path()
### Response
#### Success Response (200)
- **path** (string) - The path of the current URL, starting with '/'.
#### Response Example
```json
"/some/path"
```
## POST /path
### Description
Sets a new path for the current URL. Ensures the path starts with a forward slash. Returns a reference to its own instance.
### Method
POST
### Endpoint
$location.path(newPath)
### Parameters
#### Query Parameters
- **newPath** (string | number | null) - The new path to set. If a number is provided, it will be converted to a string.
### Request Example
```json
{
"newPath": "/new/path"
}
```
### Response
#### Success Response (200)
- **this** (object) - A reference to the $location instance.
#### Response Example
```json
{
"$location": "[instance]"
}
```
```
--------------------------------
### Display Analytics Configuration
Source: https://v20.angular.dev/cli/analytics/info
Use this command to view the current settings for analytics gathering and reporting in your Angular project. No setup is required beyond having the Angular CLI installed.
```bash
ng analytics info
```
--------------------------------
### HashLocationStrategy Component Example
Source: https://v20.angular.dev/api/common/HashLocationStrategy
Demonstrates how to use HashLocationStrategy within an Angular component. This setup configures the Location service to use hash-based routing. Ensure '@angular/common' is imported.
```typescript
import {HashLocationStrategy, Location, LocationStrategy} from '@angular/common';
import {Component} from '@angular/core';
@Component({
selector: 'hash-location',
providers: [Location, {provide: LocationStrategy, useClass: HashLocationStrategy}],
template: `
HashLocationStrategy
Current URL is: {{ location.path() }} Normalize: /foo/bar/ is: {{ location.normalize('foo/bar') }} `,
standalone: false,
})
export class HashLocationComponent {
location: Location;
constructor(location: Location) {
this.location = location;
}
}
```
--------------------------------
### Initial Component Setup with Imports
Source: https://v20.angular.dev/tutorials/signals/4-managing-async-data-with-signals
This snippet shows the initial setup of an Angular component, including necessary imports for signals and the `loadUser` function from a separate API file.
```typescript
// TODO: Add the resource import from @angular/core
import {Component, signal, computed, ChangeDetectionStrategy} from '@angular/core';
import {loadUser} from './user-api';
@Component({
selector: 'app-root',
template: `
User Profile Loader
Preview
Console
Terminal
Installing packages
refresh
Your browser is currently limiting the memory available to run the Angular Tutorials or Playground. If you have multiple tabs open with Tutorials or Playground, please close some of them and refresh this page. I understand
`
})
```
--------------------------------
### TestBed Configuration and Initialization
Source: https://v20.angular.dev/guide/testing/utility-apis
Methods for configuring and initializing the testing environment.
```APIDOC
## TestBed Configuration and Initialization
### Description
Methods for configuring and initializing the testing environment.
### Methods
- **`configureTestingModule(moduleDef: TestModuleMetadata)`**
Refines the testing module configuration by adding/removing imports, declarations, and providers.
- **`compileComponents()`**
Asynchronously compiles the testing module. Must be called if components have `templateUrl` or `styleUrls`.
- **`initTestEnvironment(ngModule: Type, platform: PlatformRef, aotSummaries?: () => any[])`**
Initializes the testing environment for the entire test run. Should be called exactly once.
- **`resetTestEnvironment()`**
Resets the initial test environment, including the default testing module.
### Types
#### `TestModuleMetadata`
```typescript
type TestModuleMetadata = {
providers?: any[];
declarations?: any[];
imports?: any[];
schemas?: Array;
};
```
#### `MetadataOverride`
```typescript
type MetadataOverride = {
add?: Partial;
remove?: Partial;
set?: Partial;
};
```
```
--------------------------------
### Provide Protractor Testing Support
Source: https://v20.angular.dev/api/platform-browser/provideProtractorTestingSupport
Use this function to get providers for Testability setup when bootstrapping an application with `bootstrapApplication`. This is necessary for Protractor to interact with the application's Testability APIs.
```typescript
function provideProtractorTestingSupport(): Provider[];
```
--------------------------------
### Build the application
Source: https://v20.angular.dev/ecosystem/service-workers/app-shell
Commands to build the application for development or production environments.
```bash
ng build --configuration=development
```
```bash
ng build
```
--------------------------------
### Implementing a HeroResolver
Source: https://v20.angular.dev/api/router/Resolve
Example of a class implementing the `Resolve` interface to fetch hero data. This resolver is provided at the root level and uses a `HeroService` to get the hero by ID from route parameters.
```typescript
@Injectable({ providedIn: 'root' })
export class HeroResolver implements Resolve {
constructor(private service: HeroService) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable|Promise|Hero {
return this.service.getHero(route.paramMap.get('id'));
}
}
```
--------------------------------
### Initialize App with Standalone Application
Source: https://v20.angular.dev/api/core/APP_INITIALIZER
This example shows how to initialize a standalone Angular application using bootstrapApplication and provideHttpClient.
```typescript
function initializeApp() { const http = inject(HttpClient); return firstValueFrom( http .get("https://someUrl.com/api/user") .pipe(tap(user => { ... })) );
}
bootstrapApplication(App, {
providers: [
provideHttpClient(),
{
provide: APP_INITIALIZER,
useValue: initializeApp,
multi: true,
},
],
});
```
--------------------------------
### Subscribe to Router Events in Angular
Source: https://v20.angular.dev/guide/routing/lifecycle-and-events
Subscribe to router events to react to navigation lifecycle changes. This example logs navigation start and end events to the console. Ensure `takeUntilDestroyed` is imported from `@angular/core` for proper subscription management.
```typescript
import { Component, inject, signal, effect } from '@angular/core';
import { Event, Router, NavigationStart, NavigationEnd } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@Component({
selector: 'app-router-events',
template: '
Router Events Component
'
})
export class RouterEventsComponent {
private readonly router = inject(Router);
constructor() {
// Subscribe to router events and react to events
this.router.events.pipe(takeUntilDestroyed()).subscribe((event: Event) => {
if (event instanceof NavigationStart) {
// Navigation starting
console.log('Navigation starting:', event.url);
}
if (event instanceof NavigationEnd) {
// Navigation completed
console.log('Navigation completed:', event.url);
}
});
}
}
```
--------------------------------
### Implementing a Hero Resolver
Source: https://v20.angular.dev/api/router/ResolveFn
Example of a resolver function that retrieves hero data using a service. It injects `HeroService` and uses `route.paramMap` to get the hero ID. This snippet also shows how to bootstrap the application with the router configuration.
```typescript
interface Hero {
name: string;
}
@Injectable()
export class HeroService {
getHero(id: string) {
return {name: `Superman-${id}`};
}
}
export const heroResolver: ResolveFn = (
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
) => {
return inject(HeroService).getHero(route.paramMap.get('id')!);
};
bootstrapApplication(App, {
providers: [
provideRouter([
{
path: 'detail/:id',
component: HeroDetailComponent,
resolve: {hero: heroResolver},
},
]),
],
});
```
--------------------------------
### Initial Component Setup with Signals
Source: https://v20.angular.dev/tutorials/signals/3-deriving-state-with-linked-signals
This snippet shows the basic Angular component setup including signal imports and the template structure before implementing linked signals.
```typescript
import {Component, signal, computed, ChangeDetectionStrategy} from '@angular/core';
// TODO: Import linkedSignal from @angular/core
@Component({
selector: 'app-root',
template: `
Preview
Console
Terminal
Installing packages
refresh
Your browser is currently limiting the memory available to run the Angular Tutorials or Playground. If you have multiple tabs open with Tutorials or Playground, please close some of them and refresh this page. I understand
`
})
export class AppComponent {
userStatus = signal('online');
notificationsEnabled: any;
// TODO: Convert computed to linkedSignal
// notificationsEnabled = computed(() => this.userStatus() === 'online');
// TODO: Add method to toggle notifications
// toggleNotifications() {
// this.notificationsEnabled.set(!this.notificationsEnabled());
// }
}
```
--------------------------------
### Basic Component Setup with `beforeEach`
Source: https://v20.angular.dev/guide/testing/components-basics
Sets up the testing module and creates a component fixture before each test. This is a common pattern for initializing components and their dependencies.
```typescript
import {DebugElement} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {BannerComponent} from './banner-initial.component';
describe('BannerComponent (initial CLI generated)', () => {
let component: BannerComponent;
let fixture: ComponentFixture;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({imports: [BannerComponent]});
}));
beforeEach(() => {
fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeDefined();
});
});
```
--------------------------------
### Examine Attached Directives and Listeners
Source: https://v20.angular.dev/guide/testing/utility-apis
This example shows how to inspect an element's DebugElement to check for attached directives like NgModel and NgControl, as well as the number of event listeners. This is useful for verifying directive application and event handling setup.
```typescript
const fixture = TestBed.createComponent(InputComponent);
fixture.detectChanges();
const inputEl = fixture.debugElement.query(By.css('input'));
expect(inputEl.providerTokens).withContext('NgModel directive').toContain(NgModel);
const ngControl = inputEl.injector.get(NgControl);
expect(ngControl).withContext('NgControl directive').toEqual(jasmine.any(NgControl));
expect(inputEl.listeners.length).withContext('several listeners attached').toBeGreaterThan(2);
```
--------------------------------
### Fix Invalid Shadow DOM Selector in Angular
Source: https://v20.angular.dev/errors/NG2009
When using `ViewEncapsulation.ShadowDom`, ensure your component selector adheres to custom element naming rules: lowercase, contains a hyphen, and starts with a letter. This example shows a common incorrect selector and its corrected version.
```typescript
@Component({
selector: 'comp',
encapsulation: ViewEncapsulation.ShadowDom…
})
```
```typescript
@Component({
selector: 'app-comp',
encapsulation: ViewEncapsulation.ShadowDom…
})
```
--------------------------------
### Build and Publish Library
Source: https://v20.angular.dev/tools/libraries/creating-libraries
Build your library for production and then publish it to npm. Ensure you use the production configuration for optimized output.
```bash
ng build my-libcd dist/my-libnpm publish
```
--------------------------------
### Install Angular CLI using bun
Source: https://v20.angular.dev/context/llm-files/llms-full.txt
Installs the Angular CLI globally using bun. Ensure Node.js is installed and meets the version requirements.
```shell
bun install -g @angular/cli
```
--------------------------------
### Correct Multi-Provider Usage Example
Source: https://v20.angular.dev/errors/NG0209
Demonstrates the correct way to provide a token for multi-provider injection, such as `ENVIRONMENT_INITIALIZER`. Ensure the `multi: true` option is used and the value is provided correctly.
```typescript
import { ENVIRONMENT_INITIALIZER, inject } from "@angular/core";
export const initializeApp = () => {
return {
provide: ENVIRONMENT_INITIALIZER,
multi: true,
useValue: () => {
// Initialization logic here
console.log("App initialized!");
}
};
};
@NgModule({
providers: [initializeApp()]
})
export class AppModule {}
```
--------------------------------
### Install Angular CLI using yarn
Source: https://v20.angular.dev/context/llm-files/llms-full.txt
Installs the Angular CLI globally using yarn. Ensure Node.js is installed and meets the version requirements.
```shell
yarn global add @angular/cli
```
--------------------------------
### Install Angular CLI using pnpm
Source: https://v20.angular.dev/context/llm-files/llms-full.txt
Installs the Angular CLI globally using pnpm. Ensure Node.js is installed and meets the version requirements.
```shell
pnpm install -g @angular/cli
```
--------------------------------
### ActivationStart Class
Source: https://v20.angular.dev/api/router/ActivationStart
Details about the ActivationStart class, its constructor, and properties.
```APIDOC
## ActivationStart Class
### Description
An event triggered at the start of the activation part of the Resolve phase of routing.
### Constructor
`ActivationStart(snapshot: ActivatedRouteSnapshot): ActivationStart`
- **snapshot** (ActivatedRouteSnapshot) - Required - The activated route snapshot.
### Properties
- **type** (`EventType.ActivationStart`) - The type of the event.
- **snapshot** (`ActivatedRouteSnapshot`) - The activated route snapshot.
### Methods
- **toString**(): `string` - Returns a string representation of the event.
```
--------------------------------
### Install Angular CLI using npm
Source: https://v20.angular.dev/context/llm-files/llms-full.txt
Installs the Angular CLI globally using npm. Ensure Node.js is installed and meets the version requirements.
```shell
npm install -g @angular/cli
```
--------------------------------
### Component Test with `beforeEach` Setup
Source: https://v20.angular.dev/guide/testing/components-basics
Demonstrates a more structured approach using `beforeEach` to configure the testing module and create component instances and fixtures, making tests cleaner.
```typescript
describe('BannerComponent (with beforeEach)', () => {
let component: BannerComponent;
let fixture: ComponentFixture;
beforeEach(() => {
TestBed.configureTestingModule({imports: [BannerComponent]});
fixture = TestBed.createComponent(BannerComponent);
component = fixture.componentInstance;
});
it('should create', () => {
expect(component).toBeDefined();
});
it('should contain "banner works!"', () => {
const bannerElement: HTMLElement = fixture.nativeElement;
expect(bannerElement.textContent).toContain('banner works!');
});
it('should have
with "banner works!"', () => {
const bannerElement: HTMLElement = fixture.nativeElement;
const p = bannerElement.querySelector('p')!;
expect(p.textContent).toEqual('banner works!');
});
it('should find the
with fixture.debugElement.nativeElement', () => {
const bannerDe: DebugElement = fixture.debugElement;
const bannerEl: HTMLElement = bannerDe.nativeElement;
const p = bannerEl.querySelector('p')!;
expect(p.textContent).toEqual('banner works!');
});
it('should find the
with fixture.debugElement.query(By.css)', () => {
const bannerDe: DebugElement = fixture.debugElement;
const paragraphDe = bannerDe.query(By.css('p'));
const p: HTMLElement = paragraphDe.nativeElement;
expect(p.textContent).toEqual('banner works!');
});
});
```
--------------------------------
### Get Component Harnesses
Source: https://v20.angular.dev/guide/testing/using-component-harnesses
Use `getHarness()` to get the first instance of a component harness and `getHarnesses()` to get all instances. These methods are available on a `HarnessLoader` instance.
```typescript
const myComponentHarness = await loader.getHarness(MyComponent);
const myComponentHarnesses = await loader.getHarnesses(MyComponent);
```
--------------------------------
### Basic Lightweight Injection Token Setup
Source: https://v20.angular.dev/guide/di/lightweight-injection-tokens
Demonstrates the basic structure of a lightweight injection token using an abstract class and its implementation in a component. This setup allows for dependency injection without direct coupling.
```typescript
abstract class LibHeaderToken {}
@Component({
selector: 'lib-header',
providers: [{provide: LibHeaderToken, useExisting: LibHeaderComponent}]
// ... other component configurations
}):
class LibHeaderComponent extends LibHeaderToken {}
@Component({
selector: 'lib-card',
// ... other component configurations
}):
class LibCardComponent {
@ContentChild(LibHeaderToken) header: LibHeaderToken | null = null;
}
```
--------------------------------
### GET /
Source: https://v20.angular.dev/api/common/http/HttpClient
Performs an HTTP GET request to the specified URL with configurable options.
```APIDOC
## GET /
### Description
Performs an HTTP GET request to the specified URL. Supports generic type definitions for response parsing and various configuration options like headers, params, and context.
### Method
GET
### Endpoint
[url]
### Parameters
#### Path Parameters
- **url** (string) - Required - The URL to send the request to.
#### Query Parameters
- **params** (HttpParams | Record) - Optional - Query parameters to append to the URL.
- **headers** (HttpHeaders | Record) - Optional - HTTP headers to include in the request.
- **context** (HttpContext) - Optional - Request context for interceptors.
- **observe** ('body' | 'response') - Optional - Defines the return type (body or full HttpResponse).
- **reportProgress** (boolean) - Optional - Whether to report upload/download progress.
- **withCredentials** (boolean) - Optional - Whether to include credentials.
- **timeout** (number) - Optional - Request timeout in milliseconds.
### Response
#### Success Response (200)
- **Observable** - Returns an observable of the response body or the full HttpResponse object depending on the 'observe' option.
```
--------------------------------
### Bootstrap Application with Configuration
Source: https://v20.angular.dev/context/llm-files/llms-full.txt
Demonstrates how to bootstrap an Angular application with a custom configuration, creating a root EnvironmentInjector.
```javascript
bootstrapApplication(AppComponent, appConfig);
```
--------------------------------
### FormControl Usage Example
Source: https://v20.angular.dev/api/forms/FormControlName
Example demonstrating how to use FormControl within a FormGroup.
```APIDOC
## Description
Syncs a `FormControl` in an existing `FormGroup` to a form control element by name.
* * *
## Exported by
* `ReactiveFormsModule`
## Usage Notes
### FormControl within a group">Register `FormControl` within a group
The following example shows how to register multiple form controls within a form group and set their value.
```typescript
import {Component} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'example-app',
template: `
`,
standalone: false,
})
export class SimpleFormGroup {
form = new FormGroup({
first: new FormControl('Nancy', Validators.minLength(2)),
last: new FormControl('Drew'),
});
get first(): any { return this.form.get('first'); }
onSubmit(): void { console.log(this.form.value); } // {first: 'Nancy', last: 'Drew'}
setValue() { this.form.setValue({first: 'Carson', last: 'Drew'}); }
}
```
__check
To see `formControlName` examples with different form control types, see:
* Radio buttons: `RadioControlValueAccessor`
* Selects: `SelectControlValueAccessor`
### Use with ngModel is deprecated
Support for using the `ngModel` input property and `ngModelChange` event with reactive form directives has been deprecated in Angular v6 and is scheduled for removal in a future version of Angular.
Jump to details
```
--------------------------------
### Initialize a new Angular application
Source: https://v20.angular.dev/ecosystem/service-workers/app-shell
Create a new project using the Angular CLI.
```bash
ng new my-app
```