### Install and Configure Angular In-memory Web API Source: https://devdocs.io/angular~15/tutorial/tour-of-heroes/toh-pt6 This section shows how to install the `angular-in-memory-web-api` package and configure the `HttpClientInMemoryWebApiModule` in the `AppModule` to simulate a data server. ```bash npm install angular-in-memory-web-api --save ``` ```typescript import { HttpClientModule } from '@angular/common/http'; import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api'; import { InMemoryDataService } from './in-memory-data.service'; @NgModule({ imports: [ HttpClientModule, HttpClientInMemoryWebApiModule.forRoot( InMemoryDataService, { dataEncapsulation: false } ) ], }) ``` -------------------------------- ### Install Angular Documentation Dependencies Source: https://devdocs.io/angular~15/guide/doc-prepare-to-edit Commands to navigate into the project and documentation directories, and install required npm modules using yarn. ```bash cd personal/angular yarn cd aio yarn ``` -------------------------------- ### Install systemjs-plugin-babel (npm) Source: https://devdocs.io/angular~15/guide/upgrade-setup Installs the `systemjs-plugin-babel` package, which is required for loading Angular framework files in ES2015 format using SystemJS. ```bash npm install --save systemjs-plugin-babel@latest ``` -------------------------------- ### Installing Library Typings Source: https://devdocs.io/angular~15/guide/using-libraries Commands to install a library and its corresponding TypeScript definition package via npm to ensure IDE support and type safety. ```bash npm install d3 --save npm install @types/d3 --save-dev ``` -------------------------------- ### Install TypeScript Compiler Source: https://devdocs.io/angular~15/guide/upgrade Installs the TypeScript compiler as a development dependency for the project using npm. ```bash npm i typescript --save-dev ``` -------------------------------- ### Matrix URL Notation Example in Browser Source: https://devdocs.io/angular~15/guide/router-tutorial-toh This example shows how the browser's address bar might look when using matrix URL notation for optional parameters. The parameters 'id' and 'foo' are appended to the URL path using semicolons. ```url localhost:4200/heroes;id=15;foo=foo ``` ``` -------------------------------- ### Install Project Dependencies Source: https://devdocs.io/angular~15/guide/upgrade Installs the necessary Angular dependencies defined in the package.json file using the npm package manager. ```bash npm install ``` -------------------------------- ### Install Schematics CLI Source: https://devdocs.io/angular~15/guide/glossary/index Installs the global command-line interface for managing and creating Angular schematics. Requires Node 6.9 or higher. ```bash npm install -g @angular-devkit/schematics-cli ``` -------------------------------- ### Install Angular Elements Package Source: https://devdocs.io/angular~15/guide/elements This command installs the `@angular/elements` package, which is required for converting Angular components into custom elements. This package provides the necessary tools and APIs for the conversion process. ```bash npm install @angular/elements --save ``` -------------------------------- ### Install Angular CLI Globally Source: https://devdocs.io/angular~15/cli/completion Command to install the Angular CLI globally via npm, ensuring the 'ng' binary is available in the system PATH for autocompletion and general usage. ```bash npm install -g @angular/cli ``` -------------------------------- ### Configure Live Example Components Source: https://devdocs.io/angular~15/guide/docs-style-guide Demonstrates various configurations for the component, including named StackBlitz files, custom labels, cross-guide linking, and display toggles like noDownload or embedded mode. ```html Tests Live example with content label Live example from the Router guide Just the StackBlitz Download only ``` -------------------------------- ### Downgrade Angular Component Example - TypeScript Source: https://devdocs.io/angular~15/api/upgrade/upgradeadapter Demonstrates how to downgrade an Angular component (Greeter) so it can be used within an AngularJS template. This example shows setting up the UpgradeAdapter, creating an AngularJS module, and bootstrapping the hybrid application. ```typescript const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module)); const module = angular.module('myExample', []); module.directive('greet', adapter.downgradeNg2Component(Greeter)); @Component({ selector: 'greet', template: '{{salutation}} {{name}}! - ' }) class Greeter { @Input() salutation: string; @Input() name: string; } @NgModule({ declarations: [Greeter], imports: [BrowserModule] }) class MyNg2Module {} document.body.innerHTML = 'ng1 template: text'; adapter.bootstrap(document.body, ['myExample']).ready(function() { expect(document.body.textContent).toEqual("ng1 template: Hello world! - text"); }); ``` -------------------------------- ### Configure Development Server Source: https://devdocs.io/angular~15/guide/upgrade Updates the start script in package.json to serve the application from the project root directory instead of the app subdirectory. ```json "start": "http-server ./ -a localhost -p 8000 -c-1" ``` -------------------------------- ### Create New Angular Project with CLI Source: https://devdocs.io/angular~15/guide/router-tutorial This command initializes a new Angular project named 'angular-router-sample'. It prompts the user to configure routing and stylesheet format. Ensure to select 'N' for routing and 'CSS' for stylesheets during setup. ```bash ng new angular-router-sample ``` -------------------------------- ### Get and Set URL Path - AngularJS $location Source: https://devdocs.io/angular~15/api/common/upgrade/%24locationshim Retrieves the path of the current URL or sets a new path. If the path does not start with a forward slash, it will be added automatically. ```javascript // given URL http://example.com/#/some/path?foo=bar&baz=xoxo let path = $location.path(); // => "/some/path" ``` -------------------------------- ### Navigate to Project Directory (Bash) Source: https://devdocs.io/angular~15/guide/doc-editing Changes the current directory to the 'aio' folder within your Angular project. This is the first step to start working with your local documentation files. ```bash cd personal/angular/aio ``` -------------------------------- ### Clone and Setup Angular Repository Source: https://devdocs.io/angular~15/guide/doc-prepare-to-edit Commands to create a local workspace directory, clone the forked Angular repository, and navigate to the project directories. ```bash mkdir personal git clone https://github.com/personal/angular personal/angular ``` -------------------------------- ### Angular CLI Command Syntax Example Source: https://devdocs.io/angular~15/cli Demonstrates the typical syntax for Angular CLI commands, including arguments, options, and aliases. It shows how to use the `build` command with a specific configuration. ```bash ng build my-app -c production ``` -------------------------------- ### Commit Staged Changes (Bash) Source: https://devdocs.io/angular~15/guide/doc-editing Records the staged changes to your local repository with a descriptive message. The message must start with 'docs:' followed by a space and your detailed explanation of the changes. ```bash git commit -m 'docs: detailed commit message' ``` -------------------------------- ### Add External Library using ng add (Angular CLI) Source: https://devdocs.io/angular~15/cli/add The 'ng add' command installs an npm package for a library and configures your Angular project to use it. It utilizes schematics defined by the library. For example, 'ng add @angular/pwa' sets up PWA support. This command requires the Angular CLI to be installed. ```bash ng add @angular/pwa ``` -------------------------------- ### Serve Angular Application with CLI Source: https://devdocs.io/angular~15/tutorial/tour-of-heroes/toh-pt0 Navigate to the project directory and use the 'ng serve' command to build the application, start the development server, and watch for source file changes. The '--open' flag automatically opens the application in a browser. ```bash cd angular-tour-of-heroes ng serve --open ``` -------------------------------- ### Angular Component Usage of QueryList Source: https://devdocs.io/angular~15/api/core/querylist This example demonstrates how to use `@ViewChildren` decorator in an Angular component to get a `QueryList` of child components or elements. The `QueryList` can then be used to interact with the queried items. ```typescript @Component({...}) class Container { @ViewChildren(Item) items:QueryList; } ``` -------------------------------- ### Create and Initialize a Schematic Collection Source: https://devdocs.io/angular~15/guide/schematics-authoring Commands to generate a new blank schematic collection and prepare the project environment. Includes installing dependencies and opening the project in an editor. ```bash schematics blank --name=hello-world cd hello-world npm install npm run build code . ``` -------------------------------- ### Create Hero Instance and Log (TypeScript) Source: https://devdocs.io/angular~15/guide/forms Demonstrates creating a new instance of the Hero class and logging its name to the console. This is a simple example of how to instantiate the data model. ```typescript const myHero = new Hero(42, 'SkyDog', 'Fetch any object at any distance', 'Leslie Rollover'); console.log('My hero is called ' + myHero.name); // "My hero is called SkyDog" ``` -------------------------------- ### Styling code snippets as 'avoid' examples Source: https://devdocs.io/angular~15/guide/docs-style-guide Apply the 'avoid' class or include 'avoid' in the filename to render a code snippet with a red border and header. This is used to highlight discouraged coding patterns in the Angular Style Guide. ```html ``` ```typescript export class NotGreatComponent { buggyFunction() { // things could be better here... } } ``` -------------------------------- ### Angular Observable Multicasting Example Source: https://devdocs.io/angular~15/guide/observables Demonstrates how to create a multicasting Observable in Angular. This allows multiple subscribers to share the same execution of the Observable, ensuring they all receive the same values emitted after they subscribe. It includes setup for delayed emissions and subsequent subscriptions. ```typescript const multicastSequence = new Observable(multicastSequenceSubscriber()); multicastSequence.subscribe({ next(num) { console.log('1st subscribe: ' + num); }, complete() { console.log('1st sequence finished.'); } }); setTimeout(() => { multicastSequence.subscribe({ next(num) { console.log('2nd subscribe: ' + num); }, complete() { console.log('2nd sequence finished.'); } }); }, 1500); ``` -------------------------------- ### Configure Class Providers with useClass Source: https://devdocs.io/angular~15/guide/dependency-injection-in-action Demonstrates how to use the useClass provider key to instantiate specific classes or substitute a default service with an alternative implementation. ```TypeScript { provide: HeroService, useClass: HeroService }, { provide: LoggerService, useClass: DateLoggerService }, ``` -------------------------------- ### Format Git commit messages for Angular Source: https://devdocs.io/angular~15/guide/doc-pr-prep Examples of single-line and multi-line commit messages following the Angular documentation contribution standards. These messages must start with 'docs:' and follow specific structural requirements for summaries, bodies, and footers. ```text docs: a short summary in present tense without capitalization or ending period ``` ```text docs: a short summary in present tense without capitalization or ending period A description of what was fixed, and why. This description can be as detailed as necessary and can be written with appropriate capitalization and punctuation Fixes #34353 ``` -------------------------------- ### Test WelcomeComponent with Mocked Service (TypeScript) Source: https://devdocs.io/angular~15/guide/testing-components-basics Tests the `WelcomeComponent` which depends on `UserService`. It uses `TestBed` to configure the testing module, providing a mock `UserService` and the `WelcomeComponent` itself. Tests verify the welcome message based on the user's login status after `ngOnInit` is called. ```typescript export class WelcomeComponent implements OnInit { welcome = ''; constructor(private userService: UserService) { } ngOnInit(): void { this.welcome = this.userService.isLoggedIn ? 'Welcome, ' + this.userService.user.name : 'Please log in.'; } } class MockUserService { isLoggedIn = true; user = { name: 'Test User'}; } beforeEach(() => { TestBed.configureTestingModule({ // provide the component-under-test and dependent service providers: [ WelcomeComponent, { provide: UserService, useClass: MockUserService } ] }); // inject both the component and the dependent service. comp = TestBed.inject(WelcomeComponent); userService = TestBed.inject(UserService); }); it('should not have welcome message after construction', () => { expect(comp.welcome).toBe(''); }); it('should welcome logged in user after Angular calls ngOnInit', () => { comp.ngOnInit(); expect(comp.welcome).toContain(userService.user.name); }); it('should ask user to log in if not logged in after ngOnInit', () => { userService.isLoggedIn = false; comp.ngOnInit(); expect(comp.welcome).not.toContain(userService.user.name); expect(comp.welcome).toContain('log in'); }); ``` -------------------------------- ### Angular Application Module Setup Source: https://devdocs.io/angular~15/guide/i18n-example This TypeScript file defines the root Angular module (`AppModule`). It imports necessary browser modules and declares the main application component (`AppComponent`), specifying it as the bootstrap component. ```typescript import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } ``` -------------------------------- ### Serve Angular Universal Locally (npm) Source: https://devdocs.io/angular~15/guide/universal Starts the server script for serving the application locally with server-side rendering. It relies on build artifacts from `ng run build:ssr`. This is for local testing only, not production. ```bash npm run serve:ssr ``` -------------------------------- ### Hybrid Application Component Interoperability Source: https://devdocs.io/angular~15/api/upgrade/upgradeadapter Provides a comprehensive example of a hybrid application where an Angular component is downgraded to an AngularJS directive and an AngularJS component is upgraded to an Angular component, allowing them to be nested and share data. ```typescript const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module), myCompilerOptions); const module = angular.module('myExample', []); module.directive('ng2Comp', adapter.downgradeNg2Component(Ng2Component)); module.directive('ng1Hello', function() { return { scope: { title: '=' }, template: 'ng1[Hello {{title}}!]()' }; }); @Component({ selector: 'ng2-comp', inputs: ['name'], template: 'ng2[transclude]()', directives: [] }) class Ng2Component {} @NgModule({ declarations: [Ng2Component, adapter.upgradeNg1Component('ng1Hello')], imports: [BrowserModule] }) class MyNg2Module {} document.body.innerHTML = 'project'; adapter.bootstrap(document.body, ['myExample']).ready(function() { expect(document.body.textContent).toEqual( "ng2[ng1[Hello World!](transclude)](project)"); }); ``` -------------------------------- ### Inject Service from Parent with @SkipSelf() Source: https://devdocs.io/angular~15/guide/hierarchical-dependency-injection Illustrates the @SkipSelf() decorator, which makes Angular start searching for a service in the parent injector, bypassing the current one. This is useful when a component needs to access a service provided by an ancestor. The example shows overriding a parent's LeafService. ```typescript export class LeafService { emoji = '🌿'; } @Component({ selector: 'app-skipself', templateUrl: './skipself.component.html', styleUrls: ['./skipself.component.css'], // Angular would ignore this LeafService instance providers: [{ provide: LeafService, useValue: { emoji: '🍁' } }] }) export class SkipselfComponent { // Use @SkipSelf() in the constructor constructor(@SkipSelf() public leaf: LeafService) { } } ``` -------------------------------- ### Serve Angular Application Source: https://devdocs.io/angular~15/guide/router-tutorial This command compiles the Angular application and starts a development server. The application will be accessible at http://localhost:4200 in your browser. ```bash ng serve ``` -------------------------------- ### Angular TestBed Setup and Component Testing Source: https://devdocs.io/angular~15/guide/testing-components-scenarios Demonstrates the setup of Angular's TestBed for component testing, including configuring modules, providing stubbed services, and creating component instances. It shows how to inject services and query DOM elements for assertions. ```typescript let userServiceStub: Partial; beforeEach(() => { // stub UserService for test purposes userServiceStub = { isLoggedIn: true, user: { name: 'Test User' }, }; TestBed.configureTestingModule({ declarations: [ WelcomeComponent ], providers: [ { provide: UserService, useValue: userServiceStub } ], }); fixture = TestBed.createComponent(WelcomeComponent); comp = fixture.componentInstance; // UserService from the root injector userService = TestBed.inject(UserService); // get the "welcome" element by CSS selector (e.g., by class name) el = fixture.nativeElement.querySelector('.welcome'); }); it('should welcome the user', () => { fixture.detectChanges(); const content = el.textContent; expect(content) .withContext('"Welcome ..."') .toContain('Welcome'); expect(content) .withContext('expected name') .toContain('Test User'); }); it('should welcome "Bubba"', () => { userService.user.name = 'Bubba'; // welcome message hasn't been shown yet fixture.detectChanges(); expect(el.textContent).toContain('Bubba'); }); it('should request login if not logged in', () => { userService.isLoggedIn = false; // welcome message hasn't been shown yet fixture.detectChanges(); const content = el.textContent; expect(content) .withContext('not welcomed') .not.toContain('Welcome'); expect(content) .withContext('"log in"') .toMatch(/log in/i); }); ``` -------------------------------- ### Hybrid Application Component Interoperability Source: https://devdocs.io/angular~15/api/upgrade/upgradeadapter Demonstrates how to use UpgradeAdapter to downgrade an Angular component for use in AngularJS and upgrade an AngularJS directive for use in Angular. This setup allows for seamless template integration and transclusion between the two frameworks. ```TypeScript const adapter = new UpgradeAdapter(forwardRef(() => MyNg2Module)); const module = angular.module('myExample', []); module.directive('greet', function() { return { scope: {salutation: '=', name: '=' }, template: '{{salutation}} {{name}}! - ' }; }); module.directive('ng2', adapter.downgradeNg2Component(Ng2Component)); @Component({ selector: 'ng2', template: 'ng2 template: text' }) class Ng2Component { } @NgModule({ declarations: [Ng2Component, adapter.upgradeNg1Component('greet')], imports: [BrowserModule] }) class MyNg2Module {} document.body.innerHTML = ''; adapter.bootstrap(document.body, ['myExample']).ready(function() { expect(document.body.textContent).toEqual("ng2 template: Hello world! - text"); }); ``` -------------------------------- ### Configure Rebase Squash Commands Source: https://devdocs.io/angular~15/guide/doc-pr-update Example configuration for the interactive rebase editor, where the first commit is kept with 'pick' and subsequent commits are merged using 'squash'. ```text pick bb0ff71891 docs: update of documentation contrib. guide squash c040d76685 docs: more content for doc updates squash 472585c43f docs: fix links that were broken by renamed files squash 3e6f4c73ac docs: add more info about open PR squash 8e50fad064 docs: more pr docs ``` -------------------------------- ### Get Locale Weekend Range Function in Angular Source: https://devdocs.io/angular~15/api/common/getlocaleweekendrange The getLocaleWeekEndRange function retrieves the range of days considered the weekend for a given locale. It takes a locale code as input and returns a tuple representing the start and end days of the weekend. ```typescript import { getLocaleWeekEndRange, WeekDay } from '@angular/common'; const locale = 'en-US'; const weekendRange: [WeekDay, WeekDay] = getLocaleWeekEndRange(locale); console.log(`The weekend for ${locale} is from day ${weekendRange[0]} to day ${weekendRange[1]}.`); ``` -------------------------------- ### Implement Radio Buttons with Reactive Forms in Angular Source: https://devdocs.io/angular~15/api/forms/radiocontrolvalueaccessor Demonstrates how to bind multiple radio buttons to a single FormControl using the formControlName directive within a FormGroup. The example shows the component setup and the corresponding HTML template for reactive form management. ```typescript import {Component} from '@angular/core'; import {FormControl, FormGroup} from '@angular/forms'; @Component({ selector: 'example-app', template: `
Beef Lamb Fish

Form value: {{ form.value | json }}

`, }) export class ReactiveRadioButtonComp { form = new FormGroup({ food: new FormControl('lamb'), }); } ``` -------------------------------- ### Platform and Exception Handling Source: https://devdocs.io/angular~15/api/core Core classes for platform initialization and centralized exception handling. ```APIDOC ## Class: ErrorHandler ### Description Provides a hook for centralized exception handling. ### Method N/A (Class definition) ### Endpoint N/A ## Class: PlatformRef ### Description The Angular platform is the entry point for Angular on a web page. Each page has exactly one platform. Services (such as reflection) which are common to every Angular application running on the page are bound in its scope. A page's platform is initialized implicitly when a platform is created using a platform factory such as `PlatformBrowser`, or explicitly by calling the `createPlatform()` function. ### Method N/A (Class definition) ### Endpoint N/A ``` -------------------------------- ### Angular App Module Setup (TypeScript) Source: https://devdocs.io/angular~15/tutorial/tour-of-heroes/toh-pt6 Configures the root module for an Angular application. It imports necessary modules like BrowserModule, FormsModule, HttpClientModule, and sets up routing and in-memory web API for data simulation. It also declares all components used within the application. ```typescript import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api'; import { InMemoryDataService } from './in-memory-data.service'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { HeroDetailComponent } from './hero-detail/hero-detail.component'; import { HeroesComponent } from './heroes/heroes.component'; import { HeroSearchComponent } from './hero-search/hero-search.component'; import { MessagesComponent } from './messages/messages.component'; @NgModule({ imports: [ BrowserModule, FormsModule, AppRoutingModule, HttpClientModule, // The HttpClientInMemoryWebApiModule module intercepts HTTP requests // and returns simulated server responses. // Remove it when a real server is ready to receive requests. HttpClientInMemoryWebApiModule.forRoot( InMemoryDataService, { dataEncapsulation: false } ) ], declarations: [ AppComponent, DashboardComponent, HeroesComponent, HeroDetailComponent, MessagesComponent, HeroSearchComponent ], bootstrap: [ AppComponent ] }) export class AppModule { } ``` -------------------------------- ### Invoke Reusable Animation with useAnimation() - Angular Source: https://devdocs.io/angular~15/api/animations/animation Demonstrates how to invoke a previously defined reusable animation (e.g., `fadeAnimation`) using the `useAnimation()` function. This example overrides the default parameters for 'time', 'start', and 'end' opacity. If parameters are missing, default values are used, but missing parameters before animation steps will cause an error. ```typescript useAnimation(fadeAnimation, { params: { time: '2s', start: 1, end: 0 } }) ``` -------------------------------- ### Displaying Terminal Commands Source: https://devdocs.io/angular~15/guide/docs-style-guide Use the tag with the language attribute set to shell for displaying command-line interface inputs and outputs. ```shell npm start ``` -------------------------------- ### GET Request - Blob Response Source: https://devdocs.io/angular~15/api/common/http/httpclient This overload of the `get` method constructs an HTTP GET request that expects the response body as a Blob. ```APIDOC ## GET /websites/devdocs_io_angular_15 (Blob) ### Description Constructs an HTTP GET request that interprets the response body as a `Blob`. ### Method GET ### Endpoint /websites/devdocs_io_angular_15 ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Optional - Query parameters to send with the request. #### Request Body None ### Request Example ```typescript this.http.get('/api/image.jpg', { responseType: 'blob' }).subscribe(blob => { console.log(blob); }); ``` ### Response #### Success Response (200) - **Blob** - The response body as a Blob. #### Response Example ``` // Blob object representation ``` ``` -------------------------------- ### GET Request - ArrayBuffer Response Source: https://devdocs.io/angular~15/api/common/http/httpclient This overload of the `get` method constructs an HTTP GET request that expects the response body as an ArrayBuffer. ```APIDOC ## GET /websites/devdocs_io_angular_15 (ArrayBuffer) ### Description Constructs an HTTP GET request that interprets the response body as an `ArrayBuffer`. ### Method GET ### Endpoint /websites/devdocs_io_angular_15 ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Optional - Query parameters to send with the request. #### Request Body None ### Request Example ```typescript this.http.get('/api/binary-data', { responseType: 'arraybuffer' }).subscribe(arrayBuffer => { console.log(arrayBuffer); }); ``` ### Response #### Success Response (200) - **ArrayBuffer** - The response body as an ArrayBuffer. #### Response Example ``` // Binary data representation ``` ``` -------------------------------- ### GET Request - Basic Source: https://devdocs.io/angular~15/api/common/http/httpclient The `get` method constructs an HTTP GET request. This overload returns an Observable of the response body, with the type `T`. ```APIDOC ## GET /websites/devdocs_io_angular_15 ### Description Constructs and sends an HTTP GET request to the specified URL, returning an Observable of the response body. ### Method GET ### Endpoint /websites/devdocs_io_angular_15 ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Optional - Query parameters to send with the request. #### Request Body None ### Request Example ```typescript this.http.get('/api/data').subscribe(data => { console.log(data); }); ``` ### Response #### Success Response (200) - **T** (any) - The response body of type T. #### Response Example ```json [ { "id": 1, "name": "Example Item" } ] ``` ``` -------------------------------- ### Application Bootstrapping (TypeScript) Source: https://devdocs.io/angular~15/guide/styleguide Shows the standard method for bootstrapping an Angular application. The main application logic, including platform setup and module bootstrapping, should reside in a file named 'main.ts'. This file should also include error handling for the bootstrapping process. ```typescript import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; platformBrowserDynamic().bootstrapModule(AppModule) .then(success => console.log(`Bootstrap success`)) .catch(err => console.error(err)); ``` -------------------------------- ### GET Request - Text Response Source: https://devdocs.io/angular~15/api/common/http/httpclient This overload of the `get` method constructs an HTTP GET request that expects the response body as a text string. ```APIDOC ## GET /websites/devdocs_io_angular_15 (Text) ### Description Constructs an HTTP GET request that interprets the response body as a text string. ### Method GET ### Endpoint /websites/devdocs_io_angular_15 ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Optional - Query parameters to send with the request. #### Request Body None ### Request Example ```typescript this.http.get('/api/text-data', { responseType: 'text' }).subscribe(text => { console.log(text); }); ``` ### Response #### Success Response (200) - **string** - The response body as a string. #### Response Example ``` "This is a plain text response." ``` ``` -------------------------------- ### Run Angular Universal Development Server Source: https://devdocs.io/angular~15/guide/universal This command starts the development server for your Angular application configured with Universal. It allows you to test the server-side rendering locally before deploying. ```bash npm run dev:ssr ``` -------------------------------- ### Build for Production and French Locale using ng build command Source: https://devdocs.io/angular~15/guide/i18n-common-merge This command shows how to perform a production build that includes both the production configuration and the French locale configuration. It utilizes configuration composition by listing multiple configurations separated by a comma. ```bash ng build --configuration=production,fr ``` -------------------------------- ### GET Request - Event Stream (Blob) Source: https://devdocs.io/angular~15/api/common/http/httpclient This overload of the `get` method constructs an HTTP GET request that returns the full event stream, with the response body as a Blob. ```APIDOC ## GET /websites/devdocs_io_angular_15 (Event Stream - Blob) ### Description Constructs an HTTP GET request that returns the full event stream, with the response body as a `Blob`. ### Method GET ### Endpoint /websites/devdocs_io_angular_15 ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Optional - Query parameters to send with the request. #### Request Body None ### Request Example ```typescript this.http.get('/api/stream/image.png', { observe: 'events', responseType: 'blob' }).subscribe(event => { console.log(event); }); ``` ### Response #### Success Response (200) - **HttpEvent** - An Observable of all `HttpEvent`s for the request, with the response body as a `Blob`. #### Response Example ```json { "type": 1, // HttpEventType.Response "body": "... Blob data ..." } ``` ``` -------------------------------- ### GET Request - Event Stream (ArrayBuffer) Source: https://devdocs.io/angular~15/api/common/http/httpclient This overload of the `get` method constructs an HTTP GET request that returns the full event stream, with the response body as an ArrayBuffer. ```APIDOC ## GET /websites/devdocs_io_angular_15 (Event Stream - ArrayBuffer) ### Description Constructs an HTTP GET request that returns the full event stream, with the response body as an `ArrayBuffer`. ### Method GET ### Endpoint /websites/devdocs_io_angular_15 ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Optional - Query parameters to send with the request. #### Request Body None ### Request Example ```typescript this.http.get('/api/stream/binary', { observe: 'events', responseType: 'arraybuffer' }).subscribe(event => { console.log(event); }); ``` ### Response #### Success Response (200) - **HttpEvent** - An Observable of all `HttpEvent`s for the request, with the response body as an `ArrayBuffer`. #### Response Example ```json { "type": 1, // HttpEventType.Response "body": "... ArrayBuffer data ..." } ``` ``` -------------------------------- ### Define and Use InjectionToken Source: https://devdocs.io/angular~15/guide/dependency-injection-in-action Demonstrates how to create a unique InjectionToken for non-class dependencies and how to register them in a provider configuration. ```TypeScript import { InjectionToken } from '@angular/core'; export const TITLE = new InjectionToken('title'); // Provider configuration { provide: TITLE, useValue: 'Hero of the Month' }; { provide: RUNNERS_UP, useFactory: runnersUpFactory(2), deps: [Hero, HeroService] }; ``` -------------------------------- ### GET Request - Event Stream (Text) Source: https://devdocs.io/angular~15/api/common/http/httpclient This overload of the `get` method constructs an HTTP GET request that returns the full event stream, with the response body as a text string. ```APIDOC ## GET /websites/devdocs_io_angular_15 (Event Stream - Text) ### Description Constructs an HTTP GET request that returns the full event stream, with the response body as a text string. ### Method GET ### Endpoint /websites/devdocs_io_angular_15 ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Optional - Query parameters to send with the request. #### Request Body None ### Request Example ```typescript this.http.get('/api/stream/log', { observe: 'events', responseType: 'text' }).subscribe(event => { console.log(event); }); ``` ### Response #### Success Response (200) - **HttpEvent** - An Observable of all `HttpEvent`s for the request, with the response body as a string. #### Response Example ```json { "type": 1, // HttpEventType.Response "body": "Log entry 1\nLog entry 2" } ``` ``` -------------------------------- ### Referencing External Source Files Source: https://devdocs.io/angular~15/guide/docs-style-guide Display code directly from a file in the content/examples directory by using the path attribute in the tag. The header attribute provides context for the file location. ```html ``` -------------------------------- ### GET /getTestBed Source: https://devdocs.io/angular~15/api/core/testing/gettestbed Retrieves the singleton instance of the TestBed class used for configuring and initializing environments for unit testing. ```APIDOC ## GET /getTestBed ### Description Returns a singleton of the `TestBed` class, which is the primary API for writing unit tests for Angular applications. ### Method GET ### Endpoint /api/core/testing/getTestBed ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example N/A (Function call) ### Response #### Success Response (200) - **TestBed** (Object) - The singleton instance of the TestBed class. #### Response Example { "instance": "TestBed" } ``` -------------------------------- ### Install Builder Package via NPM Source: https://devdocs.io/angular~15/guide/cli-builder Command to install an external builder package into the Angular project. ```bash npm install @example/copy-file ``` -------------------------------- ### Component and Module Creation Source: https://devdocs.io/angular~15/api/core Functions for creating component and module instances. ```APIDOC ## Component and Module Creation ### Description Utilities for instantiating components and modules within the Angular framework. ### Functions - **`createComponent(component: Type, options?: CreateComponentOptions): ComponentRef`** Creates a `ComponentRef` instance based on provided component type and a set of options. - **`createNgModule(moduleType: Type, parentInjector: Injector): NgModuleRef`** Returns a new NgModuleRef instance based on the NgModule class and parent injector provided. ``` -------------------------------- ### Functional Resolver Example in Angular Source: https://devdocs.io/angular~15/api/router Example of a functional resolver in Angular. This resolver fetches data required for a route before it is activated. ```typescript import { ResolveFn } from "@angular/router"; export const dataResolver: ResolveFn = (route, state) => { // Logic to resolve data for the route console.log('Resolving data for the route...'); return { data: 'some data' }; }; ``` -------------------------------- ### Configure query parameters and fragments Source: https://devdocs.io/angular~15/api/router/routerlinkwithhref Shows how to append query parameters and fragments to a route, and how to control parameter merging or preservation using the queryParamsHandling attribute. ```html link to user component link to user component ``` -------------------------------- ### Angular Component for i18n Example Source: https://devdocs.io/angular~15/guide/i18n-example This TypeScript component defines the logic for the Angular i18n example. It manages state variables like `minutes` and `gender` that are used within the template's ICU expressions for dynamic translation. ```typescript import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { minutes = 0; gender = 'female'; fly = true; logo = 'https://angular.io/assets/images/logos/angular/angular.png'; inc(i: number) { this.minutes = Math.min(5, Math.max(0, this.minutes + i)); } male() { this.gender = 'male'; } female() { this.gender = 'female'; } other() { this.gender = 'other'; } } ``` -------------------------------- ### Build and Serve Angular Application Source: https://devdocs.io/angular~15/guide/service-worker-getting-started Commands to compile the Angular project for production and serve the resulting build artifacts using a local HTTP server with caching disabled. ```bash ng build http-server -p 8080 -c-1 dist/ ``` -------------------------------- ### Implement Lightweight Injection Token Pattern Source: https://devdocs.io/angular~15/guide/lightweight-injection-tokens Demonstrates the basic setup of a lightweight injection token using an abstract class. The component provides itself as the implementation for the token, allowing other components to query the token instead of the concrete class. ```TypeScript abstract class LibHeaderToken {} @Component({ selector: 'lib-header', providers: [ {provide: LibHeaderToken, useExisting: LibHeaderComponent} ] }) class LibHeaderComponent extends LibHeaderToken {} @Component({ selector: 'lib-card' }) class LibCardComponent { @ContentChild(LibHeaderToken) header: LibHeaderToken|null = null; } ``` -------------------------------- ### Testing Services without TestBed and beforeEach Source: https://devdocs.io/angular~15/guide/testing-services An alternative testing pattern that uses a setup function to instantiate classes manually, avoiding TestBed and the beforeEach lifecycle hook. ```typescript function setup() { const valueServiceSpy = jasmine.createSpyObj('ValueService', ['getValue']); const stubValue = 'stub value'; const masterService = new MasterService(valueServiceSpy); valueServiceSpy.getValue.and.returnValue(stubValue); return { masterService, stubValue, valueServiceSpy }; } it('#getValue should return stubbed value from a spy', () => { const { masterService, stubValue, valueServiceSpy } = setup(); expect(masterService.getValue()).toBe(stubValue); }); ``` -------------------------------- ### Generate static and dynamic links with RouterLink Source: https://devdocs.io/angular~15/api/router/routerlinkwithhref Demonstrates how to create static links and dynamic links using arrays of path segments. Dynamic links allow for parameter injection into the URL structure. ```html link to user component link to team user ```