### Component Harness Setup and Interaction Example Source: https://angular.dev/assets/context/llms-full.txt This example demonstrates setting up a HarnessLoader and interacting with different component harnesses, including a dialog that is appended to document.body. ```typescript let fixture: ComponentFixture; let loader: HarnessLoader; let rootLoader: HarnessLoader; beforeEach(() => { fixture = TestBed.createComponent(MyDialogButton); loader = TestbedHarnessEnvironment.loader(fixture); rootLoader = TestbedHarnessEnvironment.documentRootLoader(fixture); }); it('loads harnesses', async () => { // Load a harness for the bootstrapped component with `harnessForFixture` dialogButtonHarness = await TestbedHarnessEnvironment.harnessForFixture( fixture, MyDialogButtonHarness, ); // The button element is inside the fixture's root element, so we use `loader`. const buttonHarness = await loader.getHarness(MyButtonHarness); // Click the button to open the dialog await buttonHarness.click(); // The dialog is appended to `document.body`, outside of the fixture's root element, // so we use `rootLoader` in this case. const dialogHarness = await rootLoader.getHarness(MyDialogHarness); // ... make some assertions }); ``` -------------------------------- ### Basic Karma Configuration Source: https://angular.dev/assets/context/guide/testing/karma A minimal `karma.conf.js` file to get started with Karma. This configuration sets up the framework, reporters, and browsers. ```typescript module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'src/app/**/*.spec.ts' ], // list of files / patterns to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser instances should be started simultaneously concurrency: Infinity }); }; ``` -------------------------------- ### Basic HttpClient Testing Setup Source: https://angular.dev/assets/context/llms-full.txt Configures TestBed for HttpClient testing and injects HttpTestingController. This is the fundamental setup for most HttpClient tests. ```typescript TestBed.configureTestingModule({ providers: [ // ... other test providers provideHttpClientTesting(), ], }); const httpTesting = TestBed.inject(HttpTestingController); ``` -------------------------------- ### Custom Setup Function Source: https://angular.dev/assets/context/llms-full.txt Create a customizable setup function that can be called within tests. This function configures `TestBed` and creates the component. ```typescript function setup(providers?: StaticProviders[]): ComponentFixture { TestBed.configureTestingModule({providers}); return TestBed.createComponent(Banner); } ``` -------------------------------- ### Install Angular CLI with bun Source: https://angular.dev/assets/context/llms-full.txt Installs the Angular CLI globally using bun. Ensure Node.js and bun are installed and in your PATH. ```shell // bun bun install -g @angular/cli ``` -------------------------------- ### Install Preview Browser Provider (bun) Source: https://angular.dev/assets/context/llms-full.txt Installs the Preview browser provider for Vitest using bun. This is for WebContainer environments like StackBlitz and not for CI/CD. ```shell // bun bun add --dev @vitest/browser-preview ``` -------------------------------- ### Setup with beforeEach Source: https://angular.dev/assets/context/llms-full.txt Refactor test setup into a `beforeEach` block for reusability. Await `fixture.whenStable()` for initial rendering. ```typescript describe('Banner (with beforeEach)', () => { let component: Banner; let fixture: ComponentFixture; beforeEach(async () => { fixture = TestBed.createComponent(Banner); component = fixture.componentInstance; await fixture.whenStable(); // necessary to wait for the initial rendering }); it('should create', () => { expect(component).toBeDefined(); }); }); ``` -------------------------------- ### Basic Component Harness Example Source: https://angular.dev/assets/context/guide/testing/using-component-harnesses A simple example demonstrating the structure of a component harness, including selectors and methods for interacting with component elements. ```typescript import { ComponentHarness, TestElement, } from '@angular/cdk/testing'; export class MyComponentHarness extends ComponentHarness { static hostSelector = 'app-my-component'; async getTitle(): Promise { const titleEl = await this.locatorFor('h1')(); return titleEl.text(); } async clickButton(): Promise { const button = await this.locatorFor('button')(); await button.click(); } async getInput(): Promise { return this.locatorFor('input')(); } } ``` -------------------------------- ### Basic Component Harness Example Source: https://angular.dev/assets/context/api/cdk/testing/ComponentHarness A simple example of a ComponentHarness for a custom button component. It demonstrates how to select elements and interact with them. ```typescript import {ComponentHarness} from '@angular/cdk/testing'; export class MyButtonHarness extends ComponentHarness { static hostSelector = 'my-button'; async click(): Promise { const button = await this.locatorFor('button')(); await button.click(); } async getText(): Promise { const button = await this.locatorFor('button')(); return button.text(); } } ``` -------------------------------- ### Install Preview Browser Provider (pnpm) Source: https://angular.dev/assets/context/llms-full.txt Installs the Preview browser provider for Vitest using pnpm. This is for WebContainer environments like StackBlitz and not for CI/CD. ```shell // pnpm pnpm add -D @vitest/browser-preview ``` -------------------------------- ### Install Preview Browser Provider (npm) Source: https://angular.dev/assets/context/llms-full.txt Installs the Preview browser provider for Vitest using npm. This is for WebContainer environments like StackBlitz and not for CI/CD. ```shell // npm npm install --save-dev @vitest/browser-preview ``` -------------------------------- ### Basic Lightweight Injection Token Setup Source: https://angular.dev/assets/context/llms-full.txt Demonstrates the basic setup of a lightweight injection token using an abstract class and its implementation in a component. This allows for decoupling the parent component from the concrete child implementation. ```typescript abstract class LibHeaderToken {} @Component({ selector: 'lib-header', providers: [{provide: LibHeaderToken, useExisting: LibHeader}], …, }) class LibHeader extends LibHeaderToken {} @Component({ selector: 'lib-card', …, }) class LibCard { readonly header = contentChild(LibHeaderToken); } ``` -------------------------------- ### Install Angular CLI with npm Source: https://angular.dev/assets/context/llms-full.txt Installs the Angular CLI globally using npm. Ensure Node.js is installed and in your PATH. ```shell // npm npm install -g @angular/cli ``` -------------------------------- ### Install Preview Browser Provider (yarn) Source: https://angular.dev/assets/context/llms-full.txt Installs the Preview browser provider for Vitest using yarn. This is for WebContainer environments like StackBlitz and not for CI/CD. ```shell // yarn yarn add --dev @vitest/browser-preview ``` -------------------------------- ### Install Vitest Coverage Package Source: https://angular.dev/assets/context/llms-full.txt Install the `@vitest/coverage-v8` package as a development dependency using your preferred package manager. ```shell // npm npm install --save-dev @vitest/coverage-v8 ``` ```shell // yarn yarn add --dev @vitest/coverage-v8 ``` ```shell // pnpm pnpm add -D @vitest/coverage-v8 ``` ```shell // bun bun add --dev @vitest/coverage-v8 ``` -------------------------------- ### Angular HTTP Testing Providers Setup Source: https://angular.dev/assets/context/llms-full.txt Example of a TypeScript file to provide HttpClientTesting to all Angular tests. Ensure this file is included in your test TypeScript configuration. ```typescript import {EnvironmentProviders, Provider} from '@angular/core'; import {provideHttpClientTesting} from '@angular/common/http/testing'; const testProviders: (Provider | EnvironmentProviders)[] = [provideHttpClientTesting()]; export default testProviders; ``` -------------------------------- ### Install Angular CLI with pnpm Source: https://angular.dev/assets/context/llms-full.txt Installs the Angular CLI globally using pnpm. Ensure Node.js and pnpm are installed and in your PATH. ```shell // pnpm pnpm install -g @angular/cli ``` -------------------------------- ### Install Angular CLI with yarn Source: https://angular.dev/assets/context/llms-full.txt Installs the Angular CLI globally using yarn. Ensure Node.js and yarn are installed and in your PATH. ```shell // yarn yarn global add @angular/cli ``` -------------------------------- ### Get help for a specific schematic Source: https://angular.dev/assets/context/tools/cli/schematics Use the '--help' flag with a specific schematic command to get detailed information about its options and usage. ```bash ng generate component --help ``` -------------------------------- ### Install WebdriverIO Browser Provider (bun) Source: https://angular.dev/assets/context/llms-full.txt Installs the WebdriverIO browser provider for Vitest using bun. This enables running tests in WebdriverIO-supported browsers. ```shell // bun bun add --dev @vitest/browser-webdriverio webdriverio ``` -------------------------------- ### Example Test Using MyButtonComponent Harness Source: https://angular.dev/assets/context/llms-full.txt Demonstrates how a test author can use a component harness to interact with a custom component. This example shows loading the harness and asserting the button's text. ```typescript it('should load button with exact text', async () => { const button = await loader.getHarness(MyButtonComponentHarness); expect(await button.getText()).toBe('Confirm'); }); ``` -------------------------------- ### Creating a Basic GET Request Source: https://angular.dev/assets/context/api/common/http/HttpRequest Demonstrates how to create a simple GET request using the HttpRequest class. This is a fundamental step for making API calls. ```typescript import { HttpRequest } from '@angular/common/http'; const req = new HttpRequest('GET', '/data', { headers: { 'X-Custom-Header': 'value' }, params: { 'queryParam': 'paramValue' }, reportProgress: true, responseType: 'json' }); ``` -------------------------------- ### Install WebdriverIO Browser Provider (npm) Source: https://angular.dev/assets/context/llms-full.txt Installs the WebdriverIO browser provider for Vitest using npm. This enables running tests in WebdriverIO-supported browsers. ```shell // npm npm install --save-dev @vitest/browser-webdriverio webdriverio ``` -------------------------------- ### Install Playwright Browser Provider (bun) Source: https://angular.dev/assets/context/llms-full.txt Installs the Playwright browser provider for Vitest using bun. This enables running tests in Playwright-supported browsers. ```shell // bun bun add --dev @vitest/browser-playwright playwright ``` -------------------------------- ### Class-Based Interceptor Example Source: https://angular.dev/assets/context/llms-full.txt An example of a class-based interceptor that implements the `HttpInterceptor` interface. It also injects `AuthService` to get the authentication token. ```typescript @Injectable() export class AuthInterceptor implements HttpInterceptor { private authService = inject(AuthService); intercept(request: HttpRequest, next: HttpHandler): Observable> { const clonedRequest = request.clone({ headers: request.headers.append('X-Authentication-Token', this.authService.getAuthToken()), }); return next.handle(clonedRequest); } } ``` -------------------------------- ### Component Creation and Setup Source: https://angular.dev/assets/context/llms-full.txt This function creates the component, sets up the testing harness, and initializes the Page object after navigating to the component's URL. ```typescript async function createComponent(id: number) { harness = await RouterTestingHarness.create(); component = await harness.navigateByUrl(`/heroes/${id}`, HeroDetail); page = new Page(); const request = TestBed.inject(HttpTestingController).expectOne(`api/heroes/?id=${id}`); const hero = getTestHeroes().find((h) => h.id === Number(id)); request.flush(hero ? [hero] : []); await harness.fixture.whenStable(); } ``` -------------------------------- ### Functional Interceptor Example Source: https://angular.dev/assets/context/llms-full.txt This is an example of a functional interceptor that adds an authentication token to outgoing requests. It uses the `inject` function to get the `AuthService`. ```typescript export function authInterceptor( request: HttpRequest, next: HttpHandlerFn, ): Observable> { const authService = inject(AuthService); const clonedRequest = request.clone({ headers: request.headers.append('X-Authentication-Token', authService.getAuthToken()), }); return next(clonedRequest); } ``` -------------------------------- ### Get Value of Slider Thumb with MatSliderHarness Source: https://angular.dev/assets/context/llms-full.txt Example of using MatSliderHarness to get the value of a slider's end thumb. Requires the `MatSliderHarness` to be imported. ```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); }); ``` -------------------------------- ### Angular Component Test Setup with TestBed Source: https://angular.dev/assets/context/llms-full.txt Sets up the testing environment for the Welcome component, including creating a fixture and injecting the UserAuthentication service. It also retrieves the DOM element for assertions. ```typescript let fixture: ComponentFixture; let comp: Welcome; let userAuth: UserAuthentication; // the TestBed injected service let el: HTMLElement; // the DOM element with the welcome message beforeEach(() => { fixture = TestBed.createComponent(Welcome); comp = fixture.componentInstance; // UserAuthentication from the root injector userAuth = TestBed.inject(UserAuthentication); // get the "welcome" element by CSS selector (e.g., by class name) el = fixture.nativeElement.querySelector('.welcome'); }); ``` -------------------------------- ### Setting up a Testbed Harness Environment Source: https://angular.dev/assets/context/api/cdk/testing/testbed/TestbedHarnessEnvironment Demonstrates how to create a harness environment for testing Angular components. This setup is crucial for using harness-based testing strategies. ```typescript import { HarnessEnvironment, HarnessLoader, } from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {MyComponent} from './my.component'; describe('MyComponent', () => { let fixture: ComponentFixture; let loader: HarnessLoader; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [MyComponent], }).compileComponents(); fixture = TestBed.createComponent(MyComponent); fixture.detectChanges(); // Initialize the harness environment loader = TestbedHarnessEnvironment.loader(fixture); }); it('should render my component', async () => { // Use the loader to find harnesses // const button = await loader.getHarness(MatButtonHarness); // await button.click(); expect(true).toBe(true); }); }); ``` -------------------------------- ### Override Caching Behavior for a Specific Request Source: https://angular.dev/assets/context/llms-full.txt Use the `transferCache` request option to override default caching behavior for individual HTTP requests. This example includes specific headers for a GET request. ```typescript // Include specific headers for this request http.get('/api/profile', {transferCache: {includeHeaders: ['CustomHeader']}}); ``` -------------------------------- ### @loading with minimum and after parameters Source: https://angular.dev/assets/context/llms-full.txt Provides an example of using the 'minimum' and 'after' parameters with the @loading block. 'after' specifies a delay before showing the loading content, and 'minimum' sets the minimum display time for the loading content, both configurable in ms or s. ```html @defer { } @loading (after 100ms; minimum 1s) { loading... } ``` -------------------------------- ### Define Routes with Multiple Parameters Source: https://angular.dev/assets/context/llms-full.txt This example demonstrates defining routes with multiple dynamic parameters, such as user ID and social media platform. It shows how to map URLs like '/user/leeroy/youtube' to specific components. ```typescript import {Routes} from '@angular/router'; import {UserProfile} from './user-profile'; import {SocialMediaFeed} from './social-media-feed'; const routes: Routes = [ {path: 'user/:id/:social-media', component: SocialMediaFeed}, {path: 'user/:id/', component: UserProfile}, ]; ``` -------------------------------- ### Get Component Harnesses Source: https://angular.dev/assets/context/llms-full.txt Use getHarness to get the first instance of a component's harness, or getAllHarnesses to get all instances. These methods are called on a HarnessLoader instance. ```typescript const myComponentHarness = await loader.getHarness(MyComponent); const myComponentHarnesses = await loader.getAllHarnesses(MyComponent); ``` -------------------------------- ### Mocking a GET Request Source: https://angular.dev/assets/context/guide/http/testing Simulate a GET request and provide a mock response. ```typescript it('should retrieve data', () => { const mockData = { message: 'Hello, world!' }; service.getData().subscribe(data => { expect(data).toEqual(mockData); }); const req = httpMock.expectOne('/api/data'); expect(req.request.method).toBe('GET'); req.flush(mockData); }); ``` -------------------------------- ### Test Bed Setup for Test Host Source: https://angular.dev/assets/context/llms-full.txt Configures the testing module to create the TestHost component. It initializes the fixture and component instance, and queries for the hero element. ```typescript beforeEach(async () => { // create TestHost instead of DashboardHero fixture = TestBed.createComponent(TestHost); testHost = fixture.componentInstance; heroEl = fixture.nativeElement.querySelector('.hero'); await fixture.whenStable(); }); ``` -------------------------------- ### Expecting a GET Request and Mocking Response Source: https://angular.dev/assets/context/llms-full.txt Demonstrates how to expect a specific GET request, assert its properties, flush a mock response, and verify the service's outcome. Use `firstValueFrom` to trigger the observable and get the response as a Promise. ```typescript TestBed.configureTestingModule({ providers: [ConfigService, provideHttpClientTesting()], }); const httpTesting = TestBed.inject(HttpTestingController); // Load `ConfigService` and request the current configuration. const service = TestBed.inject(ConfigService); const config$ = service.getConfig(); // `firstValueFrom` subscribes to the `Observable`, which makes the HTTP request, // and creates a `Promise` of the response. const configPromise = firstValueFrom(config$); // At this point, the request is pending, and we can assert it was made // via the `HttpTestingController`: const req = httpTesting.expectOne('/api/config', 'Request to load the configuration'); // We can assert various properties of the request if desired. expect(req.request.method).toBe('GET'); // Flushing the request causes it to complete, delivering the result. req.flush(DEFAULT_CONFIG); // We can then assert that the response was successfully delivered by the `ConfigService`: expect(await configPromise).toEqual(DEFAULT_CONFIG); // Finally, we can assert that no other requests were made. httpTesting.verify(); ``` -------------------------------- ### Basic Component Test Setup Source: https://angular.dev/assets/context/guide/testing/components-scenarios Sets up a basic test environment for an Angular component using TestBed. This is the foundation for most component tests. ```typescript import { ComponentFixture, TestBed } from '@angular/core/testing'; import { MyComponent } from './my.component'; describe('MyComponent', () => { let component: MyComponent; let fixture: ComponentFixture; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [MyComponent] }) .compileComponents(); fixture = TestBed.createComponent(MyComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); ``` -------------------------------- ### App Component Template Example Source: https://angular.dev/assets/context/llms-full.txt An example of an Angular component template that includes nested components and router directives. ```html ``` -------------------------------- ### Basic Dependency Injection Example Source: https://angular.dev/assets/context/guide/di/dependency-injection-context Demonstrates a simple service and a component that injects and uses it. This is a fundamental pattern for providing services to components. ```typescript import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class Logger { log(msg: string) { console.log(msg); } } @Component({ selector: 'app-my-component', template: '...' }) export class MyComponent { constructor(private logger: Logger) {} doSomething() { this.logger.log('Doing something!'); } } ``` -------------------------------- ### Start the Angular development server Source: https://angular.dev/assets/context/llms-full.txt Builds and serves the Angular application locally, enabling live reloading for development. ```shell npm start ``` -------------------------------- ### Schematic execution with skip install for add Source: https://angular.dev/assets/context/tools/cli/schematics Prevent 'ng add' from installing npm packages using the '--skip-install' option. ```bash ng add @angular/material --skip-install ``` -------------------------------- ### Schematic execution with skip install for run Source: https://angular.dev/assets/context/tools/cli/schematics Prevent 'ng run' from installing npm packages using the '--skip-install' option. ```bash ng run my-app:my-custom-schematic --skip-install ``` -------------------------------- ### Schematic execution with skip install option Source: https://angular.dev/assets/context/tools/cli/schematics Prevent 'ng new' from installing npm packages using the '--skip-install' option. ```bash ng new my-app --skip-install ``` -------------------------------- ### Configure Router and HttpClient Testing Source: https://angular.dev/assets/context/llms-full.txt Sets up the testing module with `provideRouter` for routing and `provideHttpClientTesting` for mocking HTTP requests. This is typically done in a `beforeEach` block. ```typescript beforeEach(async () => { TestBed.configureTestingModule({ providers: [ provideRouter([{path: '**', component: Dashboard}]), provideHttpClientTesting(), HeroService, ], }); harness = await RouterTestingHarness.create(); comp = await harness.navigateByUrl('/', Dashboard); TestBed.inject(HttpTestingController).expectOne('api/heroes').flush(getTestHeroes()); }); ``` -------------------------------- ### Schematic execution with skip install and collection for update Source: https://angular.dev/assets/context/tools/cli/schematics Prevent 'ng update' from installing npm packages, using a schematic from a specific collection. ```bash ng update @angular/core --skip-install --collection=@schematics/angular ``` -------------------------------- ### Admin Page Rendering Example Source: https://angular.dev/assets/context/llms-full.txt Demonstrates how a specific route, such as '/admin', results in its corresponding component (``) being rendered as a sibling to the ``. ```html ``` -------------------------------- ### Schematic execution with skip install option for update Source: https://angular.dev/assets/context/tools/cli/schematics Prevent 'ng update' from installing npm packages using the '--skip-install' option. ```bash ng update @angular/core --skip-install ``` -------------------------------- ### Initialize Theme and CSS Classes Source: https://angular.dev/assets/context/api/core/REQUEST_CONTEXT%20'API%20reference' This script initializes theme preferences and applies CSS classes to the document element for dark or light mode. It also handles a special 'uwu' class based on URL parameters. This logic should execute early to prevent unstyled content. ```typescript const THEME_PREFERENCE_LOCAL_STORAGE_KEY = 'themePreference'; const DARK_MODE_CLASS_NAME = 'docs-dark-mode'; const LIGHT_MODE_CLASS_NAME = 'docs-light-mode'; const PREFERS_COLOR_SCHEME_DARK = '(prefers-color-scheme: dark)'; const theme = localStorage.getItem(THEME_PREFERENCE_LOCAL_STORAGE_KEY) ?? 'auto'; const prefersDark = window.matchMedia && window.matchMedia(PREFERS_COLOR_SCHEME_DARK).matches; const documentClassList = this.document.documentElement.classList; // clearing classes before setting them. this.document.documentElement.className = ''; if (theme === 'dark' || (theme === 'auto' && prefersDark)) { documentClassList.add(DARK_MODE_CLASS_NAME); } else { documentClassList.add(LIGHT_MODE_CLASS_NAME); } if (location.search.includes('uwu')) { documentClassList.add('uwu'); } ``` -------------------------------- ### Using the PercentPipe Source: https://angular.dev/assets/context/guide/testing/pipes Shows how to format numbers as percentages using the built-in PercentPipe. Optional parameters include minimum and maximum decimal places. ```html
{{ ratio | percent:'1.0-2' }}
``` -------------------------------- ### Custom Structural Directive Example Source: https://angular.dev/assets/context/guide/directives/structural-directives Demonstrates the creation of a custom structural directive. This example shows how to create a directive that conditionally applies a class. ```typescript import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[appUnless]' }) export class UnlessDirective { private hasView = false; constructor(private templateRef: TemplateRef, private viewContainer: ViewContainerRef) {} @Input() set appUnless(condition: boolean) { if (!condition && !this.hasView) { this.viewContainer.createEmbeddedView(this.templateRef); this.hasView = true; } else if (condition && this.hasView) { this.viewContainer.clear(); this.hasView = false; } } } ``` ```typescript import { Component } from '@angular/core'; @Component({ selector: 'app-custom-directive-example', template: `
This will be shown if condition is false.
` }) export class CustomDirectiveExampleComponent { condition = false; } ``` -------------------------------- ### Schematic execution with configuration for run Source: https://angular.dev/assets/context/tools/cli/schematics Pass configuration options to a custom schematic using the '--configuration' flag. ```bash ng run my-app:my-custom-schematic --configuration=my-config ``` -------------------------------- ### Create Component Instance Source: https://angular.dev/assets/context/llms-full.txt Use `TestBed.createComponent()` to instantiate a component and obtain a `ComponentFixture`. Do not re-configure `TestBed` after this call. ```typescript const fixture = TestBed.createComponent(Banner); ``` -------------------------------- ### Creating a HarnessPredicate Source: https://angular.dev/assets/context/api/cdk/testing/HarnessPredicate Demonstrates the basic instantiation of a HarnessPredicate. This is the foundation for defining selection logic. ```typescript const predicate = new HarnessPredicate(MatButtonHarness); ``` -------------------------------- ### Harness with Document Root Locator Source: https://angular.dev/assets/context/api/cdk/testing/ComponentHarness Demonstrates using `documentRoot()` to get a `HarnessLoader` for the entire document, useful for modals or overlays. ```typescript import {ComponentHarness, HarnessLoader} from '@angular/cdk/testing'; import {MatDialogHarness} from '@angular/material/dialog/testing'; export class AppComponentHarness extends ComponentHarness { static hostSelector = 'app-root'; async getDialog(): Promise { const loader = await this.documentRoot(); return loader.getHarness(MatDialogHarness); } } ``` -------------------------------- ### Pipe with Parameters Source: https://angular.dev/assets/context/guide/templates/pipes Demonstrates how to create and use a custom pipe that accepts parameters. This example defines a pipe to multiply a number by a given factor. ```typescript import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'multiply' }) export class MultiplyPipe implements PipeTransform { transform(value: number | null, factor: number = 1): number | null { if (value === null) { return null; } return value * factor; } } ``` -------------------------------- ### Install WebdriverIO Browser Provider (pnpm) Source: https://angular.dev/assets/context/llms-full.txt Installs the WebdriverIO browser provider for Vitest using pnpm. This enables running tests in WebdriverIO-supported browsers. ```shell // pnpm pnpm add -D @vitest/browser-webdriverio webdriverio ``` -------------------------------- ### Animating Reordering List Items with Native CSS Source: https://angular.dev/assets/context/llms-full.txt This example demonstrates how to animate items entering and leaving a reordering list using CSS, leveraging `@starting-styles` and `animate.leave`. ```typescript import { Component } from "@angular/core"; @Component({ selector: "app-reorder", templateUrl: "./reorder.html", styleUrls: ["./reorder.css"], animations: [ // animation definitions ] }) export class ReorderComponent { items = [1, 2, 3, 4, 5]; removeItem(item: number) { this.items = this.items.filter(i => i !== item); } } ``` ```html
{{item}}
``` ```css .reorder-container { display: flex; flex-direction: column; align-items: center; } .reorder-item { padding: 10px; margin-bottom: 10px; background-color: lightcoral; border-radius: 5px; animation-name: enter; animation-duration: 0.5s; animation-fill-mode: backwards; } .reorder-item:nth-child(1) { animation-delay: 0s; } .reorder-item:nth-child(2) { animation-delay: 0.1s; } .reorder-item:nth-child(3) { animation-delay: 0.2s; } .reorder-item:nth-child(4) { animation-delay: 0.3s; } .reorder-item:nth-child(5) { animation-delay: 0.4s; } @starting-styles { .reorder-item { opacity: 0; transform: translateY(-20px); } } @keyframes enter { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } } /* Example for leave animation (not directly shown in the provided HTML/TS, but implied by 'animate.leave') */ /* .reorder-item.ng-leave { animation-name: leave; animation-duration: 0.5s; } */ /* @keyframes leave { to { opacity: 0; transform: translateY(20px); } } */ ``` -------------------------------- ### Install WebdriverIO Browser Provider (yarn) Source: https://angular.dev/assets/context/llms-full.txt Installs the WebdriverIO browser provider for Vitest using yarn. This enables running tests in WebdriverIO-supported browsers. ```shell // yarn yarn add --dev @vitest/browser-webdriverio webdriverio ``` -------------------------------- ### App Component Setup Source: https://angular.dev/assets/context/llms-full.txt Configure the root `App` component to use `RouterOutlet` for routing. Import `RouterOutlet` and include it in the component's imports array. ```typescript import {Component} from '@angular/core'; import {RouterOutlet} from '@angular/router'; @Component({ selector: 'app-root', imports: [RouterOutlet], templateUrl: './app.html', styleUrl: './app.css', }) export class App {} ``` -------------------------------- ### Schematic execution with directory option Source: https://angular.dev/assets/context/tools/cli/schematics Specify the directory in which to create the new application using the '--directory' option. ```bash ng new my-app --directory=./projects ``` -------------------------------- ### Install Playwright Browser Provider (pnpm) Source: https://angular.dev/assets/context/llms-full.txt Installs the Playwright browser provider for Vitest using pnpm. This enables running tests in Playwright-supported browsers. ```shell // pnpm pnpm add -D @vitest/browser-playwright playwright ``` -------------------------------- ### Install Playwright Browser Provider (yarn) Source: https://angular.dev/assets/context/llms-full.txt Installs the Playwright browser provider for Vitest using yarn. This enables running tests in Playwright-supported browsers. ```shell // yarn yarn add --dev @vitest/browser-playwright playwright ``` -------------------------------- ### Schematic execution with dry run and force Source: https://angular.dev/assets/context/tools/cli/schematics Combine '--dry-run' and '--force' to preview changes that would overwrite existing files. ```bash ng generate component my-component --dry-run --force ``` -------------------------------- ### Install Playwright Browser Provider (npm) Source: https://angular.dev/assets/context/llms-full.txt Installs the Playwright browser provider for Vitest using npm. This enables running tests in Playwright-supported browsers. ```shell // npm npm install --save-dev @vitest/browser-playwright playwright ``` -------------------------------- ### Basic FormGroup Initialization Source: https://angular.dev/assets/context/api/forms/FormGroup Demonstrates how to create a FormGroup with predefined form controls. This is the most common way to initialize a form group. ```typescript import {Component} from '@angular/core'; import {FormBuilder, FormGroup, Validators} from '@angular/forms'; @Component({ selector: 'app-name-editor', templateUrl: './name-editor.component.html', styleUrls: ['./name-editor.component.css'] }) export class NameEditorComponent { name = new FormControl(''); updateName() { this.name.setValue('Nancy'); } } ``` -------------------------------- ### Creating a HarnessLoader for the Document Root Source: https://angular.dev/assets/context/api/cdk/testing/testbed/TestbedHarnessEnvironment Illustrates how to create a HarnessLoader that targets the entire document root, useful for testing components that are outside the direct scope of a specific fixture. ```typescript const loader = TestbedHarnessEnvironment.documentRootLoader(fixture); ``` -------------------------------- ### Getting Parameter Values Source: https://angular.dev/assets/context/api/common/http/HttpParams Use the `get` method to retrieve the first value associated with a given parameter name. Returns null if the parameter is not found. ```typescript const params = new HttpParams().append('key', 'value'); console.log(params.get('key')); // 'value' console.log(params.get('otherKey')); // null ``` -------------------------------- ### Custom HttpParameterCodec Example Source: https://angular.dev/assets/context/api/common/http/HttpParameterCodec This example demonstrates how to create a custom HttpParameterCodec to handle specific encoding/decoding logic, such as encoding spaces as '+' instead of '%20'. ```typescript export class CustomHttpParamCodec implements HttpParameterCodec { encodeKey(key: string): string { return encodeURIComponent(key); } encodeValue(value: string): string { return encodeURIComponent(value).replace(/%20/g, '+'); } decodeKey(key: string): string { return decodeURIComponent(key); } decodeValue(value: string): string { return decodeURIComponent(value.replace(/ eceived+/g, '%20')); } } ```