### Basic Server-Side Rendering Setup Source: https://angular.dev/api/ssr/provideServerRendering Example of enabling server-side rendering using bootstrapApplication with provideServerRendering, withRoutes, and withAppShell. ```typescript import { bootstrapApplication, BootstrapContext } from '@angular/platform-browser'; import { provideServerRendering, withRoutes, withAppShell } from '@angular/ssr'; import { AppComponent } from './app/app.component'; import { SERVER_ROUTES } from './app/app.server.routes'; import { AppShellComponent } from './app/app-shell.component'; const bootstrap = (context: BootstrapContext) => bootstrapApplication(AppComponent, { providers: [ provideServerRendering( withRoutes(SERVER_ROUTES), withAppShell(AppShellComponent), ), ], }, context); export default bootstrap; ``` -------------------------------- ### Basic Server Rendering Setup in Angular Source: https://angular.dev/api/platform-server/provideServerRendering Example of how to include server rendering support by adding provideServerRendering() to your application's providers during bootstrapping. ```typescript bootstrapApplication(AppComponent, { providers: [provideServerRendering()] }); ``` -------------------------------- ### HTTP Request Example (GET) Source: https://angular.dev/api/common/http/HttpClient Example of performing a GET request to search for heroes. It demonstrates using HttpParams and setting the responseType to 'json'. ```APIDOC ## GET heroes ### Description Performs a GET request to retrieve heroes based on a search term. ### Method GET ### Endpoint /heroes ### Parameters #### Query Parameters - **name** (string) - Required - The search term to filter heroes by name. #### Request Body None ### Request Example ```typescript // GET heroes whose name contains search term searchHeroes(term: string): Observable{ const params = new HttpParams({fromString: 'name=term'}); return this.httpClient.request('GET', this.heroesUrl, {responseType:'json', params}); } ``` Alternatively, the parameter string can be used without invoking HttpParams by directly joining to the URL. ```typescript this.httpClient.request('GET', this.heroesUrl + '?' + 'name=term', {responseType:'json'}); ``` ### Response #### Success Response (200) - **heroes** (Hero[]) - An array of Hero objects matching the search term. ``` -------------------------------- ### Usage Example Source: https://angular.dev/api/core/provideAppInitializer An example demonstrating how to use `provideAppInitializer` to load user data via HTTP during application bootstrap. ```APIDOC ## Usage Example ### Description This example shows how to configure an initialization function using `provideAppInitializer()` to fetch user data from an API when the application starts. ### Code ```typescript bootstrapApplication(App, { providers: [ provideAppInitializer(() => { const http = inject(HttpClient); return firstValueFrom( http .get("https://someUrl.com/api/user") .pipe(tap(user => { /* ... */ })) ); }), provideHttpClient(), ], }); ``` ``` -------------------------------- ### Basic Usage Example Source: https://angular.dev/api/router/withRouterConfig An example demonstrating how to use withRouterConfig to set the onSameUrlNavigation option when providing the router. ```APIDOC ## Usage Notes Basic example of how you can provide extra configuration options: ```typescript const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withRouterConfig({ onSameUrlNavigation: 'reload' })) ] } ); ``` ``` -------------------------------- ### Configuring RouterTestingModule with Routes Source: https://angular.dev/api/router/testing/RouterTestingModule Example of configuring RouterTestingModule with a set of routes for testing. This setup is now recommended to be done using `RouterModule.forRoot`. ```typescript beforeEach(() => { TestBed.configureTestingModule({ imports: [ RouterModule.forRoot( [{path: '', component: BlankCmp}, {path: 'simple', component: SimpleCmp}] ) ] }); }); ``` -------------------------------- ### Usage Examples Source: https://angular.dev/api/router/createUrlTreeFromSnapshot Illustrative examples demonstrating various ways to use createUrlTreeFromSnapshot for different navigation scenarios. ```APIDOC ## Usage Examples ### Basic Navigation ```typescript // create /team/33/user/11 createUrlTreeFromSnapshot(snapshot, ['/team', 33, 'user', 11]); ``` ### With Matrix Parameters ```typescript // create /team/33;expand=true/user/11 createUrlTreeFromSnapshot(snapshot, ['/team', 33, {expand: true}, 'user', 11]); ``` ### Collapsing Static Segments ```typescript // you can collapse static segments like this (this works only with the first passed-in value): createUrlTreeFromSnapshot(snapshot, ['/team/33/user', userId]); ``` ### Handling Segments with Slashes ```typescript // If the first segment can contain slashes, and you do not want the router to split it, // you can do the following: createUrlTreeFromSnapshot(snapshot, [{segmentPath: '/one/two'}]); ``` ### Using Outlets for Secondary Navigation ```typescript // create /team/33/(user/11//right:chat) createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}], null, null); // remove the right secondary node createUrlTreeFromSnapshot(snapshot, ['/team', 33, {outlets: {primary: 'user/11', right: null}}]); ``` ### Relative Navigation Examples (Assume the current URL is for the `/team/33/user/11` and the `ActivatedRouteSnapshot` points to `user/11`) #### Navigating to a child route ```typescript // navigate to /team/33/user/11/details createUrlTreeFromSnapshot(snapshot, ['details']); ``` #### Navigating to a sibling route ```typescript // navigate to /team/33/user/22 createUrlTreeFromSnapshot(snapshot, ['../22']); ``` #### Navigating to a route in a different part of the tree ```typescript // navigate to /team/44/user/22 createUrlTreeFromSnapshot(snapshot, ['../../team/44/user/22']); ``` ``` -------------------------------- ### HTTP GET Request Example Source: https://angular.dev/api/common/http/HttpClient Performs a GET request to fetch heroes. You can use `HttpParams` for query parameters or append them directly to the URL. ```typescript // GET heroes whose name contains search term searchHeroes(term: string): observable{ const params = new HttpParams({fromString: 'name=term'}); return this.httpClient.request('GET', this.heroesUrl, {responseType:'json', params}); } ``` ```typescript this.httpClient.request('GET', this.heroesUrl + '?' + 'name=term', {responseType:'json'}); ``` -------------------------------- ### Basic Usage Example Source: https://angular.dev/api/router/withPreloading An example demonstrating how to use withPreloading to configure the PreloadAllModules strategy within the Angular router. ```APIDOC ## Usage Example Basic example of how you can configure preloading: ```typescript const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withPreloading(PreloadAllModules)) ] } ); ``` ``` -------------------------------- ### Example Implementation of UrlMatcher Source: https://angular.dev/api/router/UrlMatcher An example demonstrating how to implement a UrlMatcher function to match HTML files. ```APIDOC ## Example: Matching HTML Files ### Description This example shows a custom `UrlMatcher` function that matches URLs consisting of a single segment ending with '.html'. ### Code ```typescript export function htmlFiles(url: UrlSegment[]) { return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null; } export const routes = [{ matcher: htmlFiles, component: AnyComponent }]; ``` ``` -------------------------------- ### Usage Example Source: https://angular.dev/api/core/ForwardRefFn An example demonstrating how to use `forwardRef` with a function that conforms to the `ForwardRefFn` interface. ```APIDOC ## Usage Example ### Example ```typescript const ref = forwardRef(() => Lock); ``` This example shows creating a forward reference to a `Lock` component using `forwardRef` and a function that implements `ForwardRefFn`. ``` -------------------------------- ### Usage Example Source: https://angular.dev/api/core/createComponent This example demonstrates how to use the createComponent function to dynamically create and attach a component to the ApplicationRef for change detection. ```APIDOC ## Usage Notes The example below demonstrates how the `createComponent` function can be used to create an instance of a ComponentRef dynamically and attach it to an ApplicationRef, so that it gets included into change detection cycles. Note: the example uses standalone components, but the function can also be used for non-standalone components (declared in an NgModule) as well. ```typescript @Component({ template: `Hello {{ name }}!` }) class HelloComponent { name = 'Angular'; } @Component({ template: `
` }) class RootComponent {} // Bootstrap an application. const applicationRef = await bootstrapApplication(RootComponent); // Locate a DOM node that would be used as a host. const hostElement = document.getElementById('hello-component-host'); // Get an `EnvironmentInjector` instance from the `ApplicationRef`. const environmentInjector = applicationRef.injector; // We can now create a `ComponentRef` instance. const componentRef = createComponent(HelloComponent, {hostElement, environmentInjector}); // Last step is to register the newly created ref using the `ApplicationRef` instance // to include the component view into change detection cycles. applicationRef.attachView(componentRef.hostView); componentRef.changeDetectorRef.detectChanges(); ``` ``` -------------------------------- ### Basic Usage Example Source: https://angular.dev/api/router/withInMemoryScrolling A basic example demonstrating how to enable the scrolling feature by providing `withInMemoryScrolling()` in the router configuration. ```typescript import { provideRouter, Routes } from '@angular/router'; import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component'; import { withInMemoryScrolling } from 'your-router-package'; // Adjust import path as needed const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withInMemoryScrolling()) // Enable scrolling feature ] }); ``` -------------------------------- ### UrlTree Usage Example Source: https://angular.dev/api/router/UrlTree Example demonstrating how to parse a URL and access its components using UrlTree. ```APIDOC ## Usage Example This example shows how to parse a URL string into a UrlTree and access its properties. ```typescript @Component({templateUrl:'template.html'}) class MyComponent { constructor(router: Router) { const tree: UrlTree = router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment'); const f = tree.fragment; // returns 'fragment' const q = tree.queryParams; // returns {debug: 'true'} const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33' g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor' g.children['support'].segments; // return 1 segment 'help' } } ``` ``` -------------------------------- ### Example Implementation of CanActivateChild Source: https://angular.dev/api/router/CanActivateChild An example demonstrating how to implement the CanActivateChild interface to protect child routes. ```APIDOC ## Example: Implementing CanActivateChild ### Class ```typescript class UserToken {} class Permissions { canActivate(user: UserToken, id: string): boolean { return true; } } @Injectable() class CanActivateTeam implements CanActivateChild { private readonly permissions = inject(Permissions); private readonly currentUser = inject(UserToken); canActivateChild( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): MaybeAsync { return this.permissions.canActivate(this.currentUser, route.params.id); } } ``` ### Route Configuration ```typescript @NgModule({ imports: [ RouterModule.forRoot([ { path: 'root', canActivateChild: [CanActivateTeam], children: [ { path: 'team/:id', component: TeamComponent } ] } ]) ], providers: [CanActivateTeam, UserToken, Permissions] }) class AppModule {} ``` ``` -------------------------------- ### Router Setup with Optional Features Source: https://angular.dev/api/router/provideRouter Enable optional Router features like debug tracing or custom configuration by passing functions from `RouterFeatures` to `provideRouter`. This example shows enabling debug tracing and setting a parameter inheritance strategy. ```typescript const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withDebugTracing(), withRouterConfig({paramsInheritanceStrategy: 'always'})) ] } ); ``` -------------------------------- ### Injector Usage Example Source: https://angular.dev/api/core/Injector Illustrates creating an injector with a value provider and retrieving values using `get`. It also shows how to handle cases where a token is not found, both by throwing an error and by providing a default value. ```typescript const injector: Injector = Injector.create({ providers: [{provide: 'validToken', useValue: 'Value'}], }); expect(injector.get('validToken')).toEqual('Value'); expect(() => injector.get('invalidToken')).toThrowError(); expect(injector.get('invalidToken', 'notFound')).toEqual('notFound'); ``` -------------------------------- ### Example Usage of CanActivate Source: https://angular.dev/api/router/CanActivate An example demonstrating how to implement and use the `CanActivate` interface to protect routes based on user permissions. ```APIDOC ## Example: Implementing and Using CanActivate ### Description This example shows a `CanActivateTeam` guard that checks user permissions before activating a route. The guard is then provided in the router configuration. ### Implementation ```typescript class UserToken {} class Permissions { canActivate(user: UserToken, id: string): boolean { // Permission check logic return true; } } @Injectable() class CanActivateTeam implements CanActivate { private readonly permissions = inject(Permissions); private readonly currentUser = inject(UserToken); canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): MaybeAsync { return this.permissions.canActivate(this.currentUser, route.params.id); } } ``` ### Router Configuration ```typescript @NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamComponent, canActivate: [CanActivateTeam] } ]) ], providers: [CanActivateTeam, UserToken, Permissions] }) class AppModule {} ``` ``` -------------------------------- ### UrlSegment Usage Example Source: https://angular.dev/api/router/UrlSegment Example demonstrating how to use UrlSegment to access path and parameters. ```APIDOC ## Usage Example ```typescript @Component({templateUrl:'template.html'}) class MyComponent { constructor(router: Router) { const tree: UrlTree = router.parseUrl('/team;id=33'); const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; const s: UrlSegment[] = g.segments; s[0].path; // returns 'team' s[0].parameters; // returns {id: 33} } } ``` ``` -------------------------------- ### Usage Example Source: https://angular.dev/api/core/OnDestroy Example of a component implementing the OnDestroy interface for custom cleanup. ```APIDOC ## Usage Example ```typescript @Component({ selector: 'my-cmp', template: `...`, }) class MyComponent implements OnDestroy { ngOnDestroy() { // ... custom cleanup logic here } } ``` ``` -------------------------------- ### Plain InjectionToken Example Source: https://angular.dev/api/core/InjectionToken Example of creating a plain InjectionToken and using it in a provider and injector. ```APIDOC ## Plain InjectionToken ```typescript const BASE_URL = new InjectionToken('BaseUrl'); const injector = Injector.create({ providers: [{provide: BASE_URL, useValue: 'http://localhost'}], }); const url = injector.get(BASE_URL); // Note: since `BASE_URL` is `InjectionToken` // `url` is correctly inferred to be `string` expect(url).toBe('http://localhost'); ``` ``` -------------------------------- ### HttpClient GET Request with Options Source: https://angular.dev/api/common/http/HttpClient Demonstrates how to make a GET request using HttpClient with various options such as headers, parameters, and response type. ```typescript get(url: string, options: { headers?: HttpHeaders | Record | undefined; observe: "events"; context?: HttpContext | undefined; params?: HttpParams | Record | undefined; reportProgress?: boolean | undefined; responseType: "blob"; withCredentials?: boolean | undefined; credentials?: RequestCredentials | undefined; keepalive?: boolean | undefined; priority?: RequestPriority | undefined; cache?: RequestCache | undefined; mode?: RequestMode | undefined; redirect?: RequestRedirect | undefined; referrer?: string | undefined; integrity?: string | undefined; referrerPolicy?: ReferrerPolicy | undefined; timeout?: number | undefined; }): Observable>; ``` -------------------------------- ### Usage Example Source: https://angular.dev/api/router/withNavigationErrorHandler This example demonstrates how to use the `withNavigationErrorHandler` function when configuring the router for an application. It shows how to provide a custom error tracking function. ```APIDOC ## Usage Example Basic example of how you can use the error handler option: ```typescript import { provideRouter, Routes } from '@angular/router'; import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { withNavigationErrorHandler } from 'your-router-module'; // Adjust import path as needed // Assume MyErrorTracker is a service you've defined // class MyErrorTracker { trackError(error: any) { console.error('Navigation Error:', error); } } const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withNavigationErrorHandler((e: any) => { // Assuming 'inject' is available in this context (e.g., within a provider function) // const errorTracker = inject(MyErrorTracker); // errorTracker.trackError(e); console.error('Navigation Error caught by handler:', e); })) ] } ); ``` ``` -------------------------------- ### setUpPreloading Source: https://angular.dev/api/router/RouterPreloader Sets up the preloading mechanism to listen for navigation events. ```APIDOC ## setUpPreloading ### Description Configures the preloader to start listening to navigation events and initiate preloading of configurations. ### Returns - void ``` -------------------------------- ### getRootHarnessLoader Source: https://angular.dev/api/cdk/testing/ContentContainerComponentHarness Gets the root harness loader from which to start searching for content contained by this harness. ```APIDOC ## getRootHarnessLoader ### Description Gets the root harness loader from which to start searching for content contained by this harness. ### Method `getRootHarnessLoader` ### Returns `Promise` - A promise that resolves with the root harness loader. ``` -------------------------------- ### HeroResolver Example Source: https://angular.dev/api/router/Resolve An example implementation of the `Resolve` interface for fetching hero data. This resolver is provided at the root and uses a service to get hero details based on the route's ID parameter. ```APIDOC ## HeroResolver ### Description Example implementation of the `Resolve` interface for fetching hero data. This resolver is provided at the root and uses a service to get hero details based on the route's ID parameter. ### Class Definition ```typescript @Injectable({ providedIn: 'root' }) export class HeroResolver implements Resolve { private readonly service = inject(HeroService); resolve( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable|Promise|Hero { return this.service.getHero(route.paramMap.get('id')); } } ``` ``` -------------------------------- ### Platform Initialization Example Source: https://angular.dev/api/core/providePlatformInitializer Demonstrates how to use `providePlatformInitializer` during platform creation. The initializer function is provided as an argument to `platformBrowser`. ```typescript const platformRef = platformBrowser([ providePlatformInitializer(() => ...) ]); bootstrapApplication(App, appConfig, { platformRef }) ``` -------------------------------- ### Starting Recurrent Task Before App is Stable Source: https://angular.dev/api/core/ApplicationRef This example demonstrates a scenario where a recurrent task is started immediately, preventing `isStable` from ever emitting `true`. The 'App is stable now' message will never 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)); } ``` -------------------------------- ### Get URL Path - AngularJS $location Source: https://angular.dev/api/common/upgrade/%24locationShim Retrieves the path portion of the current URL. If the path does not start with a forward slash, this method will prepend it. Use this to get the current route or page path. ```javascript // given URL http://example.com/#/some/path?foo=bar&baz=xoxo let path = $location.path(); // => "/some/path" ``` -------------------------------- ### Basic Usage Example Source: https://angular.dev/api/core/ConstructorProvider Demonstrates how to use ConstructorProvider to configure an Injector to provide an instance of a custom class. ```APIDOC ## Usage Example: Basic Provider ### Description Configures the `Injector` to return an instance of a `Square` class. ### Code ```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); ``` ``` -------------------------------- ### begin Source: https://angular.dev/api/core/RendererFactory2 A callback invoked when rendering has begun. ```APIDOC ## begin ### Description A callback invoked when rendering has begun. ### Method abstract optional ### Parameters - None ### Returns - **void** ### Request Example ```typescript // Example usage (conceptual) rendererFactory.begin(); ``` ### Response Example ```typescript // void ``` ``` -------------------------------- ### Get the root harness loader Source: https://angular.dev/api/cdk/testing/ContentContainerComponentHarness Use `getRootHarnessLoader` to obtain the `HarnessLoader` for the root element, allowing searches to start from the document's root. ```typescript await contentContainer.getRootHarnessLoader() ``` -------------------------------- ### Service Injection Example Source: https://angular.dev/api/core/Injectable Demonstrates how to mark service classes with @Injectable for dependency injection. This setup allows a service to be injected upon creation. ```typescript @Injectable() class UsefulService {} @Injectable() class NeedsService { constructor(public service: UsefulService) {} } const injector = Injector.create({ providers: [ {provide: NeedsService, deps: [UsefulService]}, {provide: UsefulService, deps: []}, ], }); expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true); ``` -------------------------------- ### Basic Usage of withNavigationErrorHandler Source: https://angular.dev/api/router/withNavigationErrorHandler Example demonstrating how to integrate withNavigationErrorHandler into your application's routing configuration. This setup tracks navigation errors using a custom service. ```typescript const appRoutes: Routes = [];ootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withNavigationErrorHandler((e: NavigationError) => inject(MyErrorTracker).trackError(e))) ] } ); ``` -------------------------------- ### renderApplication Usage Example Source: https://angular.dev/api/platform-server/renderApplication Demonstrates how to use the renderApplication function. It shows the necessary imports and the typical pattern for bootstrapping an application and rendering it to a string. ```typescript import { BootstrapContext, bootstrapApplication } from '@angular/platform-browser'; import { renderApplication } from '@angular/platform-server'; import { ApplicationConfig } from '@angular/core'; import { AppComponent } from './app.component'; const appConfig: ApplicationConfig = { providers: [...] }; const bootstrap = (context: BootstrapContext) => bootstrapApplication(AppComponent, config, context); const output = await renderApplication(bootstrap); ``` -------------------------------- ### Integrating ComboboxDialog with ng-template Source: https://angular.dev/api/aria/combobox/ComboboxDialog Example of how to use the ComboboxDialog directive within an ng-template to create a dialog-based combobox popup. This setup allows for modal or non-modal dialogs. ```html ``` -------------------------------- ### initialNavigation() Source: https://angular.dev/api/router/Router Sets up the location change listener and performs the initial navigation when the application loads. ```APIDOC ## initialNavigation() ### Description Sets up the location change listener and performs the initial navigation. ### Method `initialNavigation(): void` ### Returns `void` ``` -------------------------------- ### Traverse Router State Tree for Route Parameters Source: https://angular.dev/api/router/ActivatedRouteSnapshot Collect all route parameters by traversing the router state tree starting from the root. This is useful for getting params outside of an activated component. ```typescript collectRouteParams(router: Router) { let params = {}; let stack: ActivatedRouteSnapshot[] = [router.routerState.snapshot.root]; while (stack.length > 0) { const route = stack.pop()!; params = {...params, ...route.params}; stack.push(...route.children); } return params; } ``` -------------------------------- ### Basic Router Setup with provideRouter Source: https://angular.dev/api/router/provideRouter Use this basic setup to add Router functionality to your application. It requires a `Routes` array and is typically included in the `providers` array of `bootstrapApplication`. ```typescript const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [provideRouter(appRoutes)] }); ``` -------------------------------- ### Using Number Input with Reactive Forms Source: https://angular.dev/api/forms/NumberValueAccessor Example demonstrating how to bind a number input element to a FormControl in a reactive form. This setup allows for direct manipulation and validation of numerical input. ```typescript const totalCountControl = new FormControl(); ``` ```html ``` -------------------------------- ### PathLocationStrategy Example Source: https://angular.dev/api/common/Location Demonstrates using Location and PathLocationStrategy to display the current URL and normalize a given path. Ensure Location and PathLocationStrategy are provided. ```typescript import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common'; import {Component} from '@angular/core'; @Component({ selector: 'path-location', providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}], template: '

PathLocationStrategy

Current URL is: {{ location.path() }}
Normalize: /foo/bar/ is: {{ location.normalize('foo/bar') }}
', standalone: false, }) export class PathLocationComponent { location: Location; constructor(location: Location) { this.location = location; } } ``` -------------------------------- ### HashLocationStrategy Usage Example Source: https://angular.dev/api/common/HashLocationStrategy Demonstrates how to configure the Location service to use HashLocationStrategy in an Angular component. This setup is useful for managing application state within the URL's hash fragment. ```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; } } ``` -------------------------------- ### Multiple Outlets Configuration Source: https://angular.dev/api/router/Route Example demonstrating how to configure routes for multiple outlets, allowing sibling components. ```APIDOC ## Multiple Outlets ```javascript [ { path: 'team/:id', component: Team }, { path: 'chat/:user', component: Chat, outlet: 'aux' } ] ``` ``` -------------------------------- ### Waiting for App Stability Before Starting Task Source: https://angular.dev/api/core/ApplicationRef This example shows how to correctly wait for the application to become stable before initiating a recurrent task. The 'App is stable now' message is logged, followed by the counter 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)); } ``` -------------------------------- ### Usage Example Source: https://angular.dev/api/core/ExistingProvider Demonstrates how to use ExistingProvider to alias one token to another. ```APIDOC ## Usage Example ### Description This example shows how to use `useExisting` to provide an instance of `FormalGreeting` when `Greeting` is requested. ### Code ```typescript class Greeting { salutation = 'Hello'; } class FormalGreeting extends Greeting { override salutation = 'Greetings'; } const injector = Injector.create({ providers: [ {provide: FormalGreeting, deps: []}, {provide: Greeting, useExisting: FormalGreeting}, ], }); expect(injector.get(Greeting).salutation).toEqual('Greetings'); expect(injector.get(FormalGreeting).salutation).toEqual('Greetings'); expect(injector.get(FormalGreeting)).toBe(injector.get(Greeting)); ``` ``` -------------------------------- ### Get Locale Currency Symbol Source: https://angular.dev/api/common/getLocaleCurrencySymbol Retrieves the symbol used to represent the currency for the main country corresponding to a given locale. For example, '$' for `en-US`. This function is deprecated; use the `Intl` API for formatting currencies. ```typescript getLocaleCurrencySymbol(locale: string): string | null; ``` -------------------------------- ### Register Form Array Example Source: https://angular.dev/api/forms/FormArrayDirective Demonstrates how to register a FormArray with first name and last name controls and handle form submission events. This snippet shows the basic setup for using FormArray in a form. ```typescript this.myForm = new FormGroup({ firstName: new FormControl(''), lastName: new FormControl('') }); ``` -------------------------------- ### Usage Example Source: https://angular.dev/api/core/TypeProvider Demonstrates how to use TypeProvider with Injector to provide a class instance. ```APIDOC ## Usage Example ### Description Configures the `Injector` to return an instance of `Type` when `Type` is used as the token. Create an instance by invoking the `new` operator and supplying additional arguments. This form is a short form of `TypeProvider`. ### Code ```typescript @Injectable() class Greeting { salutation = 'Hello'; } const injector = Injector.create({providers: [{provide: Greeting, useClass: Greeting}]}); expect(injector.get(Greeting).salutation).toBe('Hello'); ``` ``` -------------------------------- ### Get Currency Symbol using Intl API Source: https://angular.dev/api/common/getCurrencySymbol This example demonstrates how to retrieve a currency symbol using the Intl.NumberFormat API, which is the recommended approach after getCurrencySymbol was deprecated. It shows how to find the currency part from the formatted parts. ```typescript Intl.NumberFormat('en', {style:'currency', currency: 'USD'}).formatToParts().find(part => part.type === 'currency').value ``` -------------------------------- ### Creating and Using an InjectionToken Source: https://angular.dev/api/core/InjectionToken Demonstrates how to create an InjectionToken, set up a provider with a mock value, and retrieve the value using the same token instance. ```typescript const TOKEN = new InjectionToken('SomeToken'); // Setting up the provider using the same token instance const providers = [ {provide: TOKEN, useValue: {someProperty: 'exampleValue'}}, // Mock value for MyInterface ]; // Creating the injector with the provider const injector = Injector.create({providers}); // Retrieving the value using the same token instance const myInterface = injector.get(TOKEN); // myInterface is inferred to be MyInterface. ``` -------------------------------- ### Get Locale Currency Name Source: https://angular.dev/api/common/getLocaleCurrencyName Retrieves the name of the currency for the main country corresponding to a given locale. For example, 'US Dollar' for `en-US`. This function is deprecated; use the `Intl` API to format a currency with its code. ```typescript function getLocaleCurrencyName(locale: string): string | null; ``` -------------------------------- ### Enable withComponentInputBinding in Router Configuration Source: https://angular.dev/api/router/withComponentInputBinding This example demonstrates how to enable the withComponentInputBinding feature when configuring the router using bootstrapApplication and provideRouter. ```typescript const appRoutes: Routes = []; bootstrapApplication(AppComponent, { providers: [ provideRouter(appRoutes, withComponentInputBinding()) ] } ); ``` -------------------------------- ### Get Owning Component - TypeScript Source: https://angular.dev/api/core/globals/getOwningComponent Use getOwningComponent to retrieve the component instance that contains the provided DOM element or directive. For example, if a child component is used within a parent component's template, calling getOwningComponent on the child's element will return the parent component instance. ```typescript function getOwningComponent(elementOrDir: {} | Element): T | null; ``` -------------------------------- ### constructor Source: https://angular.dev/api/cdk/testing/HarnessEnvironment Initializes a new instance of the HarnessEnvironment class. ```APIDOC ## constructor HarnessEnvironment ### Description Initializes a new instance of the HarnessEnvironment class. ### Parameters #### Path Parameters * **rawRootElement** (E) - Required - The native root element of this `HarnessEnvironment`. ### Returns * **HarnessEnvironment** - A new instance of HarnessEnvironment. ``` -------------------------------- ### Get Locale Specific Day Periods Source: https://angular.dev/api/common/getLocaleExtraDayPeriods Retrieves locale-specific day periods, which indicate roughly how a day is broken up in different languages. For example, for `en-US`, periods are morning, noon, afternoon, evening, and midnight. Angular recommends relying on the `Intl` API for i18n. To extract a day period use `Intl.DateTimeFormat` with the `dayPeriod` option instead. ```typescript function getLocaleExtraDayPeriods( locale: string, formStyle: FormStyle, width: TranslationWidth, ): string[]; ``` -------------------------------- ### Multi-value Example Source: https://angular.dev/api/core/ExistingProvider Illustrates how to use ExistingProvider with the `multi: true` option to collect multiple values for a single token. ```APIDOC ## Multi-value Example ### Description This example demonstrates how to use `multi: true` with `useValue` to collect multiple string values for the `locale` token. ### Code ```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']); ``` ``` -------------------------------- ### HttpClient GET Method Source: https://angular.dev/api/common/http/HttpClient The `get` method is used to make HTTP GET requests. It supports various options for configuring the request, including headers, response observation, and response types. ```APIDOC ## GET /url ### Description Retrieves data from the specified URL. This method is highly configurable, allowing for detailed control over request options and response handling. ### Method GET ### Endpoint /url ### Parameters #### Path Parameters - **url** (string) - Required - The URL to fetch. #### Query Parameters - **options** (object) - Optional - Configuration options for the request. - **headers** (HttpHeaders | Record) - Optional - Sets the HTTP headers. - **observe** ('response' | 'body') - Optional - Specifies how to observe the response. Defaults to 'body'. - **context** (HttpContext) - Optional - Sets the HTTP context. - **params** (HttpParams | Record) - Optional - Sets the HTTP parameters. - **reportProgress** (boolean) - Optional - Whether to report progress. - **responseType** ('blob' | 'text' | 'json') - Optional - The type of the response body. Defaults to 'json' when observe is 'body'. - **withCredentials** (boolean) - Optional - Whether to send credentials. - **credentials** (RequestCredentials) - Optional - Credentials for the request. - **keepalive** (boolean) - Optional - Whether to keep the connection alive. - **priority** (RequestPriority) - Optional - The priority of the request. - **cache** (RequestCache) - Optional - Cache settings for the request. - **mode** (RequestMode) - Optional - The mode of the request. - **redirect** (RequestRedirect) - Optional - The redirect mode. - **referrer** (string) - Optional - The referrer policy. - **integrity** (string) - Optional - The integrity of the resource. - **referrerPolicy** (ReferrerPolicy) - Optional - The referrer policy. - **transferCache** (boolean | { includeHeaders?: string[] | undefined }) - Optional - Transfer cache settings. - **timeout** (number) - Optional - The timeout for the request in milliseconds. ### Response #### Success Response - **Observable>**: When `observe` is 'response' and `responseType` is 'blob'. - **Observable>**: When `observe` is 'response' and `responseType` is 'text'. - **Observable>**: When `observe` is 'response' and `responseType` is 'json' (default). - **Observable**: When `observe` is 'body' and `responseType` is 'json' (default). - **Observable**: When `observe` is 'body' and `responseType` is 'json' (default), with a generic type T. ### Request Example ```json { "url": "https://api.example.com/data", "options": { "headers": { "Authorization": "Bearer YOUR_TOKEN" }, "observe": "response", "responseType": "json" } } ``` ### Response Example ```json { "status": 200, "statusText": "OK", "headers": {}, "body": { "message": "Success" }, "url": "https://api.example.com/data", "ok": true } ``` ``` -------------------------------- ### Usage Example in H3 Source: https://angular.dev/api/ssr/createRequestHandler Example of how to use createRequestHandler within an H3 application. ```APIDOC ### Example usage in a H3 application: ```typescript import { createApp, toWebHandler } from 'h3'; import { createRequestHandler } from '@angular/ssr/node'; const app = createApp(); const handler = toWebHandler(app); export default createRequestHandler(handler); ``` ``` -------------------------------- ### Basic Usage Example Source: https://angular.dev/api/core/StaticClassProvider Demonstrates how to provide a `Shape` token with a `Square` class implementation using `StaticClassProvider`. ```APIDOC ## Basic Usage Example ### Description Provides a `Shape` token with a `Square` class implementation. ### Code ```typescript abstract class Shape { name!: string; } class Square extends Shape { override name = 'square'; } const injector = Injector.create({ providers: [{provide: Shape, useClass: Square, deps: []}], }); const shape: Shape = injector.get(Shape); expect(shape.name).toEqual('square'); expect(shape instanceof Square).toBe(true); ``` ``` -------------------------------- ### Usage Example in Hono Source: https://angular.dev/api/ssr/createRequestHandler Example of how to use createRequestHandler within a Hono application. ```APIDOC ## Usage Notes ### Example usage in a Hono application: ```typescript import { Hono } from 'hono'; import { createRequestHandler } from '@angular/ssr/node'; const app = new Hono(); export default createRequestHandler(app.fetch); ``` ``` -------------------------------- ### Basic ValueProvider Example Source: https://angular.dev/api/core/ValueProvider Demonstrates how to configure an Injector to provide a simple string value for a token. Ensure the token and value are correctly specified. ```typescript const injector = Injector.create({providers: [{provide: String, useValue: 'Hello'}]}); expect(injector.get(String)).toEqual('Hello'); ``` -------------------------------- ### Permissions Class Example Source: https://angular.dev/api/router/CanDeactivate A simple example of a Permissions class with a canDeactivate method. ```typescript class UserToken {} class Permissions { canDeactivate(user: UserToken, id: string): boolean { return true; } } ``` -------------------------------- ### Simple Route Configuration Source: https://angular.dev/api/router/Route Example of a basic route configuration with a parameterized path and child routes. ```APIDOC ## Simple Configuration ```javascript [ { path: 'team/:id', component: Team, children: [{ path: 'user/:name', component: User }] } ] ``` ``` -------------------------------- ### createPlatform Function Source: https://angular.dev/api/core/createPlatform Initializes a new platform. This function must be used when launching the application to set up the platform. ```APIDOC ## createPlatform ### Description Creates a platform. Platforms must be created on launch using this function. ### Function Signature ```typescript function createPlatform(injector: Injector): PlatformRef; ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (PlatformRef) - **PlatformRef** (PlatformRef) - The created platform reference. ### Response Example None ``` -------------------------------- ### Usage Example Source: https://angular.dev/api/core/viewChildren Example of how to use the `viewChildren` function in a component to query for child elements. ```APIDOC ## Usage Notes ```typescript @Component({...}) export class TestComponent { divEls = viewChildren('el'); // Signal> } ``` ``` -------------------------------- ### PATCH Example Source: https://angular.dev/api/common/http/HttpClient Example of performing a PATCH request to update a hero's name. ```APIDOC ## PATCH Hero ### Description Updates a specific hero's name using a PATCH request. ### Method PATCH ### Endpoint /api/heroes/{id} ### Parameters #### Path Parameters - **id** (number) - Required - The ID of the hero to update. #### Query Parameters None #### Request Body - **name** (string) - Required - The new name for the hero. ### Request Example ```typescript // PATCH one of the heroes' name patchHero (id: number, heroName: string): Observable<{}> { const url = `${this.heroesUrl}/${id}`; // PATCH api/heroes/42 return this.httpClient.patch(url, {name: heroName}, httpOptions) .pipe(catchError(this.handleError('patchHero'))); } ``` ### Response #### Success Response (200) - **result** ({}) - An empty object or a success indicator upon successful update. ``` -------------------------------- ### Configure Initialization Function with provideEnvironmentInitializer Source: https://angular.dev/api/core/provideEnvironmentInitializer Illustrates how to set up an initialization function using `provideEnvironmentInitializer` when creating an environment injector. ```typescript createEnvironmentInjector( [ provideEnvironmentInitializer(() => { console.log('environment initialized'); }), ], parentInjector ); ``` -------------------------------- ### Basic Usage Example Source: https://angular.dev/api/core/ClassProvider Demonstrates how to use ClassProvider to inject an instance of `Square` when `Shape` is requested. ```APIDOC ## Basic Usage Example ### Description Configures the `Injector` to return an instance of `Square` for the `Shape` token. ### Code ```typescript abstract class Shape { name!: string; } class Square extends Shape { override name = 'square'; } const injector = Injector.create({providers: [{provide: Shape, useClass: Square}]}); const shape: Shape = injector.get(Shape); // expect(shape.name).toEqual('square'); // expect(shape instanceof Square).toBe(true); ``` ``` -------------------------------- ### get (ArrayBuffer) Source: https://angular.dev/api/common/http/HttpClient Constructs a GET request that interprets the body as an ArrayBuffer and returns the full HttpResponse. ```APIDOC ## GET [url] ### Description Constructs a `GET` request that interprets the body as an `ArrayBuffer` and returns the full `HttpResponse`. ### Method GET ### Endpoint [url] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (200) - **response** (HttpResponse) - The full HTTP response. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### FactoryProvider Usage Example Source: https://angular.dev/api/core/FactoryProvider Demonstrates how to use FactoryProvider to create a dependency based on another provided value. ```APIDOC ## FactoryProvider Usage Example ### Description This example shows how to use `useFactory` with `deps` to create a `Hash` token based on a `Location` token. ### Code ```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'); ``` ``` -------------------------------- ### ActivationStart Source: https://angular.dev/api/router/EventType Represents the start of activating a route. ```APIDOC ## ActivationStart ### Description This event is triggered when the router begins activating a route. ### Event Type EventType.ActivationStart ``` -------------------------------- ### Configuring an Initialization Function with provideAppInitializer Source: https://angular.dev/api/core/provideAppInitializer Illustrates how to use provideAppInitializer within bootstrapApplication to load data asynchronously before the application fully initializes. It injects HttpClient to fetch user data and uses firstValueFrom to convert the Observable to a Promise. ```typescript bootstrapApplication(App, { providers: [ provideAppInitializer(() => { const http = inject(HttpClient); return firstValueFrom( http .get("https://someUrl.com/api/user") .pipe(tap(user => { ... })) ); }), provideHttpClient(), ], }); ``` -------------------------------- ### ResolveStart Source: https://angular.dev/api/router/EventType Represents the start of the route resolver process. ```APIDOC ## ResolveStart ### Description This event is triggered when the router begins resolving route data. ### Event Type EventType.ResolveStart ``` -------------------------------- ### Input Binding Example Source: https://angular.dev/api/core/Binding An example of how to create an input binding using `inputBinding`. This function creates a binding that targets a specific property and can be updated with a new value. ```APIDOC inputBinding('value', () => 123) ``` -------------------------------- ### JSONP Example Source: https://angular.dev/api/common/http/HttpClient Example of making a JSONP request. This method is useful for making cross-domain requests. ```APIDOC ## JSONP Request ### Description Performs a JSONP request to a specified URL. ### Method JSONP ### Endpoint (URL provided in the function argument) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript requestJsonp(url, callback = 'callback') { return this.httpClient.jsonp(this.heroesURL, callback); } ``` ### Response #### Success Response (200) - **data** (any) - The data returned from the JSONP request. ``` -------------------------------- ### Tree-shakable InjectionToken Example Source: https://angular.dev/api/core/InjectionToken Example of creating a tree-shakable InjectionToken with a factory function and `providedIn: 'root'`. ```APIDOC ## Tree-shakable InjectionToken ```typescript class MyService { constructor(readonly myDep: MyDep) {} } const MY_SERVICE_TOKEN = new InjectionToken('Manually constructed MyService', { providedIn: 'root', factory: () => new MyService(inject(MyDep)), }); const instance = injector.get(MY_SERVICE_TOKEN); expect(instance instanceof MyService).toBeTruthy(); expect(instance.myDep instanceof MyDep).toBeTruthy(); ``` ```