### 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: ` Ahoj Svet `, }) 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: `