### Basic Connected Overlay Example Source: https://angular.dev/guide/aria/api/cdk/overlay/CdkConnectedOverlay Demonstrates the basic setup of a connected overlay using CdkConnectedOverlay. This example shows how to connect an overlay to a button, allowing it to open and close on click. ```html
Content to display in the overlay
``` -------------------------------- ### Customizable Setup Function Source: https://angular.dev/guide/testing/components-basics Define a reusable `setup` function to configure `TestBed` and create components, allowing for parameter customization. ```typescript function setup(providers?: StaticProviders[]): ComponentFixture { TestBed.configureTestingModule({providers}); return TestBed.createComponent(Banner); } ``` -------------------------------- ### Install Vitest Browser Preview Provider Source: https://angular.dev/guide/testing Install the `@vitest/browser-preview` provider for use in WebContainer environments like StackBlitz. This provider is not intended for CI/CD. ```bash npm install --save-dev @vitest/browser-preview ``` -------------------------------- ### Load Component Harnesses in Tests Source: https://angular.dev/guide/testing/using-component-harnesses This example demonstrates loading harnesses for different components within a test setup. It shows how to use `harnessForFixture` for the root component and `loader` or `rootLoader` for child components based on their DOM location. ```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 }); ``` -------------------------------- ### Install Vitest and jsdom Source: https://angular.dev/guide/testing/migrating-to-vitest Install Vitest and a DOM emulation library like jsdom for faster test execution in a simulated browser environment within Node.js. ```bash npm install --save-dev vitest jsdom ``` -------------------------------- ### Install Karma and Jasmine Packages Source: https://angular.dev/guide/testing/karma Install the necessary npm packages for Karma and Jasmine testing in an existing project. ```bash npm install --save-dev karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine ``` -------------------------------- ### Install Vitest Coverage Package Source: https://angular.dev/guide/testing/code-coverage Install the `@vitest/coverage-v8` package as a development dependency to enable code coverage reporting with Vitest. ```bash npm install --save-dev @vitest/coverage-v8 ``` -------------------------------- ### Basic Menu Item Example Source: https://angular.dev/guide/aria/menubar Demonstrates a simple menu item with a label and shortcut. Use this for basic actions within a menu. ```html
Strikethrough β‡§βŒ˜X
``` -------------------------------- ### Basic FormGroup Example Source: https://angular.dev/guide/forms/typed-forms A simple example of a `FormGroup` for a user login form. This demonstrates the basic structure for typed reactive forms. ```typescript const login = new FormGroup({ email: new FormControl(''), password: new FormControl(''), }); ``` -------------------------------- ### Practical Example: Logger Substitution Source: https://angular.dev/guide/di/defining-dependency-providers Demonstrates how to substitute logger implementations to extend functionality. This example shows a base logger, an enhanced logger with timestamps, and a logger that includes user context, all provided via useClass. ```typescript import {Injectable, Component, inject} from '@angular/core'; // Base logger @Injectable() export class Logger { log(message: string) { console.log(message); } } // Enhanced logger with timestamp @Injectable() export class BetterLogger extends Logger { override log(message: string) { super.log(`[${new Date().toISOString()}] ${message}`); } } // Logger that includes user context @Injectable() export class EvenBetterLogger extends Logger { private userService = inject(UserService); override log(message: string) { const name = this.userService.user.name; super.log(`Message to ${name}: ${message}`); } } // In your component @Component({ selector: 'app-example', providers: [ UserService, // EvenBetterLogger needs this {provide: Logger, useClass: EvenBetterLogger}, ], }) export class Example { private logger = inject(Logger); // Gets EvenBetterLogger instance } ``` -------------------------------- ### Standalone DashboardHero Component Setup Source: https://angular.dev/guide/testing/components-scenarios Sets up a test environment for the DashboardHero component. It creates a component fixture, gets the instance, finds the hero element, mocks a hero object, and sets the input property. ```typescript let fixture: ComponentFixture; let comp: DashboardHero; let heroDe: DebugElement; let heroEl: HTMLElement; let expectedHero: Hero; beforeEach(async () => { fixture = TestBed.createComponent(DashboardHero); comp = fixture.componentInstance; // find the hero's DebugElement and element heroDe = fixture.debugElement.query(By.css('.hero')); heroEl = heroDe.nativeElement; // mock the hero supplied by the parent component expectedHero = {id: 42, name: 'Test Name'}; // simulate the parent setting the input property with that hero fixture.componentRef.setInput('hero', expectedHero); // wait for initial data binding await fixture.whenStable(); }); ``` -------------------------------- ### Install Tailwind CSS and PostCSS Dependencies Source: https://angular.dev/guide/tailwind Install Tailwind CSS and its peer dependencies using npm, yarn, pnpm, or bun. ```bash npm install tailwindcss @tailwindcss/postcss postcss ``` -------------------------------- ### Test Host Component Setup Source: https://angular.dev/guide/testing/components-scenarios Define a test host component to bind inputs and events to the component under test. This setup is useful for verifying component interactions. ```typescript @Component({ imports: [DashboardHero], template: ` `, }) class TestHost { hero: Hero = {id: 42, name: 'Test Name'}; selectedHero: Hero | undefined; onSelected(hero: Hero) { this.selectedHero = hero; } } ``` -------------------------------- ### Install Angular CDK Source: https://angular.dev/guide/drag-drop Install the Angular Component Dev Kit (CDK) from npm using the Angular CLI. This is a prerequisite for using the drag and drop directives. ```bash ng add @angular/cdk ``` -------------------------------- ### Setup for Banner Component Tests Source: https://angular.dev/guide/testing/components-scenarios Initializes the testing environment for the Banner component. It sets up component fixture, instance, and queries the H1 element for assertions. This setup is crucial before running individual tests. ```typescript let component: Banner; let fixture: ComponentFixture; let h1: HTMLElement; beforeEach(() => { fixture = TestBed.createComponent(Banner); component = fixture.componentInstance; // Banner test instance h1 = fixture.nativeElement.querySelector('h1'); }); ``` -------------------------------- ### Basic Menu with Submenu Example Source: https://angular.dev/guide/aria/menu This example demonstrates how to create a basic menu with a submenu using Angular Material's CDK overlay and menu directives. It includes items like 'Mark as read', 'Snooze', 'Categorize', and 'Archive'. The 'Categorize' item features a submenu. ```html ``` -------------------------------- ### Rendering Example: Visiting /products Source: https://angular.dev/guide/routing/show-routes-with-outlets When a user navigates to '/products', Angular renders the `Products` component within the `router-outlet`. ```html ``` -------------------------------- ### Basic Grid Structure Source: https://angular.dev/guide/aria/grid This example shows the basic structure of a grid with emojis, demonstrating a two-dimensional layout. ```html 🀯| 🀯| 🀯| ✨| πŸŽ‰ ---|---|---|---|--- πŸŽ‰| πŸ’£| πŸ”₯ πŸ”₯| πŸ’― πŸ”₯| πŸ’– πŸŽ‰| πŸ’–| πŸ’£ πŸ”₯| 🀯| πŸ’£ ``` -------------------------------- ### Route Definitions Example Source: https://angular.dev/guide/routing/show-routes-with-outlets Define your application's routes with paths and associated components. This configuration determines which component is rendered for a given URL. ```typescript import {Routes} from '@angular/router'; import {Home} from './home'; import {Products} from './products'; const routes: Routes = [ { path: '', component: Home, title: 'Home Page', }, { path: 'products', component: Products, title: 'Our Products', }, ]; ``` -------------------------------- ### Debugging with Dependency Path Example Source: https://angular.dev/guide/di/debugging-and-troubleshooting-di Shows how to interpret a dependency path in an error message to trace the injection chain and identify where a provider is missing. ```typescript NullInjectorError: No provider for LoggerStore! Dependency path: App -> DataStore -> ApiClient -> LoggerStore ``` -------------------------------- ### Configuring Overlay Position Source: https://angular.dev/guide/aria/api/cdk/overlay/CdkConnectedOverlay Shows how to configure the position of the connected overlay. This example uses `cdkConnectedOverlayPositions` to define fallback positions when the preferred position is not available. ```html
Content to display in the overlay
``` -------------------------------- ### Create Actor Instance Source: https://angular.dev/guide/forms/template-driven-forms Demonstrates creating a new instance of the `Actor` class and logging its name to the console. This is a basic example of using the data model. ```typescript const myActress = new Actor(42, 'Marilyn Monroe', 'Singing'); console.log('My actress is called ' + myActress.name); // "My actress is called Marilyn" ``` -------------------------------- ### Vertical Tabs Example Source: https://angular.dev/guide/aria/tabs Arranges tabs vertically, suitable for sidebars or settings panels. Includes the TypeScript component setup. ```html videocam theater_comedy reviews Panel 1 ``` ```typescript import {Component} from '@angular/core'; import {Tab, Tabs, TabList, TabPanel, TabContent} from '@angular/aria/tabs'; @Component({ selector: 'app-root', templateUrl: './app.html', styleUrl: './app.css', imports: [TabList, Tab, Tabs, TabPanel, TabContent], }) export class App {} ``` -------------------------------- ### Creating Components Source: https://angular.dev/guide/testing/utility-apis Create a component instance based on the current TestBed configuration. ```APIDOC ## createComponent ### Description Creates an instance of a component of type `T` based on the current `TestBed` configuration. After calling this method, the `TestBed` configuration is frozen for the duration of the current spec. Returns a `ComponentFixture`. ### Method `TestBed.createComponent(component: Type): ComponentFixture` ### Parameters #### Path Parameters - **component** (Type) - Required - The component type to create. ### Response #### Success Response (ComponentFixture) - **fixture** (ComponentFixture) - The created component fixture. ``` -------------------------------- ### Add Tailwind CSS to Angular Project Source: https://angular.dev/guide/tailwind Use the Angular CLI's `ng add` command for an automated setup. This installs necessary packages and configures your project. ```bash ng add tailwindcss ``` -------------------------------- ### Toolbar Example Source: https://angular.dev/guide/aria/api/cdk/overlay/guide/aria/toolbar Demonstrates a toolbar with common controls. Implementing this requires careful consideration of keyboard navigation, screen reader announcements, focus management, and right-to-left language support. ```html undo redo format_bold format_italic format_underlined format_align_left format_align_center format_align_right ``` -------------------------------- ### Get Component Harness Instances Source: https://angular.dev/guide/testing/using-component-harnesses Use `getHarness()` to get the first instance of a component harness or `getAllHarnesses()` to get all instances. These methods are called on a `HarnessLoader` instance. ```typescript // Get harness for first instance of the element const myComponentHarness = await loader.getHarness(MyComponent); // Get harnesses for all instances of the element const myComponentHarnesses = await loader.getAllHarnesses(MyComponent); ``` -------------------------------- ### Practical Example: Application Configuration Source: https://angular.dev/guide/di/defining-dependency-providers Illustrates a common use case for `useValue`: providing application configuration. This includes defining a configuration interface, creating an injection token, defining the configuration object, and providing it during application bootstrap. ```typescript // Define configuration interface export interface AppConfig { apiUrl: string; appTitle: string; features: { darkMode: boolean; analytics: boolean; }; } // Create injection token export const APP_CONFIG = new InjectionToken('app.config'); // Define configuration const appConfig: AppConfig = { apiUrl: 'https://api.example.com', appTitle: 'My Application', features: { darkMode: true, analytics: false, }, }; // Provide in bootstrapootstrapApplication(AppComponent, { providers: [{provide: APP_CONFIG, useValue: appConfig}], }); // Use in component @Component({ selector: 'app-header', template: `

{{ title }}

`, }) export class Header { private config = inject(APP_CONFIG); title = this.config.appTitle; } ``` -------------------------------- ### Configure TestBed for HTTP Client Testing Source: https://angular.dev/guide/http/testing Set up `TestBed` to use a testing backend for `HttpClient`. Ensure `provideHttpClient()` is listed before `provideHttpClientTesting()` to avoid potential test failures. ```typescript TestBed.configureTestingModule({ providers: [ // ... other test providers provideHttpClient(), provideHttpClientTesting(), ], }); const httpTesting = TestBed.inject(HttpTestingController); ``` -------------------------------- ### Karma Test Runner Console Output Example Source: https://angular.dev/guide/testing/karma Example of the console output when Karma and Jasmine tests are running. ```text 02 11 2022 09:08:28.605:INFO [karma-server]: Karma v6.4.1 server started at http://localhost:9876/ 02 11 2022 09:08:28.607:INFO [launcher]: Launching browsers Chrome with concurrency unlimited 02 11 2022 09:08:28.620:INFO [launcher]: Starting browser Chrome 02 11 2022 09:08:31.312:INFO [Chrome]: Connected on socket -LaEYvD2R7MdcS0-AAAB with id 31534482 Chrome: Executed 3 of 3 SUCCESS (0.193 secs / 0.172 secs) TOTAL: 3 SUCCESS ``` -------------------------------- ### Tabs Overview Example Source: https://angular.dev/guide/aria/tabs Basic structure for Angular Aria Tabs. This example demonstrates the default tab layout. ```html Movie Cast Reviews Panel 1 ``` -------------------------------- ### Basic Drag and Drop List Setup Source: https://angular.dev/guide/drag-drop Sets up two connected lists for a drag-and-drop interface. Items can be moved between the 'Available items' and 'Shopping basket' lists. ```html

Available items

@for (item of items; track item) {
{{ item }}
}

Shopping basket

@for (item of basket; track item) {
{{ item }}
}
``` -------------------------------- ### TestBed Configuration Source: https://angular.dev/guide/testing/utility-apis Configure the testing module with declarations, imports, and providers. ```APIDOC ## configureTestingModule ### Description Configures the testing module with basic declaratives and service substitutes. Allows refinement by adding/removing imports, declarations, and providers. ### Method `TestBed.configureTestingModule(metadata: TestModuleMetadata)` ### Parameters #### Request Body - **metadata** (TestModuleMetadata) - Required - The metadata to configure the testing module. ```typescript type TestModuleMetadata = { providers?: any[]; declarations?: any[]; imports?: any[]; schemas?: Array; }; ``` ``` -------------------------------- ### Basic Menu with Submenu Example Source: https://angular.dev/guide/aria/menu Demonstrates a basic menu structure with a primary menu and a nested submenu. The submenu is triggered by hovering over a menu item. Ensure cdkConnectedOverlay is imported. ```html ``` -------------------------------- ### Angular Component Setup with TestBed Source: https://angular.dev/guide/testing/components-scenarios Sets up the testing environment for an Angular component using TestBed. This includes creating component fixtures, injecting services, and querying DOM elements. ```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'); }); ``` -------------------------------- ### Angular Menubar Component Setup Source: https://angular.dev/guide/aria/menubar Sets up the main Angular component to use the Menubar and its associated Menu components. Ensure all necessary modules are imported. ```typescript import {Component, signal, viewChild} from '@angular/core'; import {MenuBar, Menu, MenuContent, MenuItem} from '@angular/aria/menu'; import {OverlayModule} from '@angular/cdk/overlay'; @Component({ selector: 'app-root', templateUrl: 'app.html', styleUrl: 'app.css', imports: [MenuBar, Menu, MenuContent, MenuItem, OverlayModule], }) export class App { fileMenu = viewChild>('fileMenu'); shareMenu = viewChild>('shareMenu'); editMenu = viewChild>('editMenu'); viewMenu = viewChild>('viewMenu'); insertMenu = viewChild>('insertMenu'); imageMenu = viewChild>('imageMenu'); chartMenu = viewChild>('chartMenu'); formatMenu = viewChild>('formatMenu'); textMenu = viewChild>('textMenu'); sizeMenu = viewChild>('sizeMenu'); paragraphMenu = viewChild>('paragraphMenu'); alignMenu = viewChild>('alignMenu'); rendered = signal(false); onFocusIn() { this.rendered.set(true); } } ``` -------------------------------- ### Install Angular Aria Source: https://angular.dev/guide/aria/api/cdk/overlay/guide/aria/combobox Install the Angular Aria package using npm. This command adds the necessary library to your project for using its accessibility directives. ```bash npm install @angular/aria ``` -------------------------------- ### Create Component Instance Source: https://angular.dev/guide/testing/components-basics Use `TestBed.createComponent()` to instantiate a component and obtain a `ComponentFixture`. ```typescript const fixture = TestBed.createComponent(Banner); ``` -------------------------------- ### Creating Components with ViewContainerRef.createComponent Source: https://angular.dev/guide/components/programmatic-rendering Demonstrates creating a component dynamically using ViewContainerRef.createComponent. It shows how to bind inputs, outputs, and apply host directives declaratively. ```typescript import { Component, ViewContainerRef, signal, inputBinding, outputBinding, twoWayBinding, inject, } from '@angular/core'; import {FocusTrap} from '@angular/cdk/a11y'; import {ThemeDirective} from '../theme.directive'; @Component({ template: ``, }) export class Host { private vcr = inject(ViewContainerRef); readonly canClose = signal(true); readonly isExpanded = signal(true); showWarning() { const compRef = this.vcr.createComponent(AppWarning, { bindings: [ inputBinding('canClose', this.canClose), twoWayBinding('isExpanded', this.isExpanded), outputBinding('close', (confirmed) => { console.log('Closed with result:', confirmed); }), ], directives: [ FocusTrap, {type: ThemeDirective, bindings: [inputBinding('theme', () => 'warning')}}, ], }); } } ``` -------------------------------- ### Globally available service with providedIn: 'root' Source: https://angular.dev/guide/di/debugging-and-troubleshooting-di Using `providedIn: 'root'` makes a service available application-wide and enables tree-shaking. This is the preferred approach for most services. ```typescript import {Injectable} from '@angular/core'; @Injectable({providedIn: 'root'}) export class DataStore { // Available everywhere } ``` -------------------------------- ### Expect GET Request and Mock Response Source: https://angular.dev/guide/http/testing Use `HttpTestingController` to expect a specific GET request and provide a mock response. This is useful for testing services that fetch data. ```typescript TestBed.configureTestingModule({ providers: [ConfigService, provideHttpClient(), 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 Menu with Submenu Example Source: https://angular.dev/guide/aria/menu Demonstrates a basic menu structure with a trigger button and a nested submenu. It utilizes cdkConnectedOverlay for positioning and ngMenu directives for menu functionality. Ensure cdk and ngMenu modules are imported. ```html ``` -------------------------------- ### Template-Driven Forms: Setup for a Single Control Source: https://angular.dev/guide/forms Use this setup for a single form control in template-driven forms. The NgModel directive implicitly creates and manages the FormControl instance. ```typescript import {Component, signal} from '@angular/core'; import {FormsModule} from '@angular/forms'; @Component({ selector: 'app-template-favorite-color', template: ` Favorite Color: `, imports: [FormsModule], }) export class FavoriteColorTemplate { favoriteColor = signal(''); } ``` -------------------------------- ### Add Preconnect Resource Hint Source: https://angular.dev/guide/image-optimization Manually add a `preconnect` link to `index.html` if an image origin cannot be automatically identified and no preconnect link is detected for the LCP image. ```html ``` -------------------------------- ### Reactive Forms: Setup for a Single Control Source: https://angular.dev/guide/forms Use this setup for a single form control in reactive forms. The form model is an explicit FormControl instance linked via [formControl]. ```typescript import {Component} from '@angular/core'; import {FormControl, ReactiveFormsModule} from '@angular/forms'; @Component({ selector: 'app-reactive-favorite-color', template: ` Favorite Color: `, imports: [ReactiveFormsModule], }) export class FavoriteColorReactive { favoriteColorControl = new FormControl(''); } ``` -------------------------------- ### Library `provide` Pattern for Configuration Source: https://angular.dev/guide/di/defining-dependency-providers Library authors can export functions that return provider configurations, simplifying consumer setup and offering flexible options. ```typescript // πŸ“ /libs/analytics/src/providers.ts import {InjectionToken, Provider, inject} from '@angular/core'; // Configuration interface export interface AnalyticsConfig { trackingId: string; enableDebugMode?: boolean; anonymizeIp?: boolean; } // Internal token for configuration const ANALYTICS_CONFIG = new InjectionToken('analytics.config'); // Main service that uses the configuration export class AnalyticsService { private config = inject(ANALYTICS_CONFIG); track(event: string, properties?: any) { // Implementation using config } } // Provider function for consumers export function provideAnalytics(config: AnalyticsConfig): Provider[] { return [{provide: ANALYTICS_CONFIG, useValue: config}, AnalyticsService]; } ``` ```typescript // Usage in consumer app // main.ts bootstrapApplication(App, { providers: [ provideAnalytics({ trackingId: 'GA-12345', enableDebugMode: !environment.production, }), ], }); ``` -------------------------------- ### Install Vitest Browser Playwright with npm Source: https://angular.dev/guide/testing/migrating-to-vitest Install the Playwright browser provider for Vitest using npm. This enables running tests in real browsers like Chromium, Firefox, and WebKit. ```bash npm install --save-dev @vitest/browser-playwright ``` -------------------------------- ### Import and Setup Angular Aria MenuBar Source: https://angular.dev/guide/aria/menubar Import necessary components and modules for the MenuBar, Menu, MenuContent, MenuItem, and OverlayModule. This setup is required for using the MenuBar functionality in your Angular application. ```typescript import {Component, signal, viewChild} from '@angular/core'; import {MenuBar, Menu, MenuContent, MenuItem} from '@angular/aria/menu'; import {OverlayModule} from '@angular/cdk/overlay'; @Component({ selector: 'app-root', templateUrl: 'app.html', styleUrl: 'app.css', imports: [MenuBar, Menu, MenuContent, MenuItem, OverlayModule], }) export class App { fileMenu = viewChild>('fileMenu'); shareMenu = viewChild>('shareMenu'); editMenu = viewChild>('editMenu'); viewMenu = viewChild>('viewMenu'); insertMenu = viewChild>('insertMenu'); imageMenu = viewChild>('imageMenu'); chartMenu = viewChild>('chartMenu'); formatMenu = viewChild>('formatMenu'); textMenu = viewChild>('textMenu'); sizeMenu = viewChild>('sizeMenu'); paragraphMenu = viewChild>('paragraphMenu'); alignMenu = viewChild>('alignMenu'); rendered = signal(false); onFocusIn() { this.rendered.set(true); } } ``` -------------------------------- ### View Menu Implementation Source: https://angular.dev/guide/aria/menubar Renders a 'View' menu with options like 'Show print layout' and 'Zoom in'. Some items are disabled to demonstrate functionality. ```html
Show print layout
Show ruler
Zoom in ⌘+
Zoom out ⌘-
Full screen
``` -------------------------------- ### Validate End Date After Start Date in Angular Forms Source: https://angular.dev/guide/forms/signals/cross-field-logic Use the `value` and `valueOf()` methods from the field context to ensure the end date is after the start date. This pattern is useful for date range validations. ```typescript import {Component, signal} from '@angular/core'; import {form, validate} from '@angular/forms/signals'; @Component({ /* ... */ }) export class EventForm { eventModel = signal({ startDate: new Date('2026-06-01'), endDate: new Date('2026-06-05'), }); eventForm = form(this.eventModel, (schemaPath) => { validate(schemaPath.endDate, ({value, valueOf}) => { if (value() <= valueOf(schemaPath.startDate)) { return { kind: 'invalidDateRange', message: 'End date must be after start date', }; } return null; }); }); } ``` -------------------------------- ### Select with Custom Display Example Source: https://angular.dev/guide/aria/select Shows how to use custom templates within options to display rich content like icons alongside text. The selected value updates to reflect the chosen option's custom display. ```html
{{ option.icon }} {{ option.label }}
``` ```html
{{ option.icon }} {{ option.label }}
``` ```html
{{ option.icon }} {{ option.label }}
``` -------------------------------- ### Configure Simple and Parameterized Redirects Source: https://angular.dev/guide/routing/redirecting-routes Define redirects using the `redirectTo` property in your route configuration. This example shows a simple redirect, a redirect with path parameters, and a wildcard redirect for unmatched paths. ```typescript import {Routes} from '@angular/router'; const routes: Routes = [ // Simple redirect {path: 'marketing', redirectTo: 'newsletter'}, // Redirect with path parameters {path: 'legacy-user/:id', redirectTo: 'users/:id'}, // Redirect any other URLs that don’t match // (also known as a "wildcard" redirect) {path: '**', redirectTo: '/login'}, ]; ``` -------------------------------- ### Run Angular Tests in Browser with WebdriverIO Source: https://angular.dev/guide/testing Execute Angular tests in a browser using WebdriverIO. Use `--browsers=chrome` for headed mode or `--browsers=chromeHeadless` for headless mode. Install necessary packages with `npm install --save-dev @vitest/browser-webdriverio webdriverio`. ```bash ng test --browsers=chrome ``` ```bash ng test --browsers=chromeHeadless ``` ```bash npm install --save-dev @vitest/browser-webdriverio webdriverio ``` -------------------------------- ### Logical tree structure for components Source: https://angular.dev/guide/di/hierarchical-dependency-injection This example illustrates the logical tree structure of components, showing how nested components form a hierarchy. The `<#VIEW>` pseudo-element represents the location of component templates within this logical tree. ```html <#VIEW> <#VIEW> ...content goes here... ``` -------------------------------- ### Run Angular Tests in Browser with Playwright Source: https://angular.dev/guide/testing Execute Angular tests in a browser using Playwright. Use `--browsers=chromium` for headed mode or `--browsers=chromiumHeadless` for headless mode. Install necessary packages with `npm install --save-dev @vitest/browser-playwright playwright`. ```bash ng test --browsers=chromium ``` ```bash ng test --browsers=chromiumHeadless ``` ```bash npm install --save-dev @vitest/browser-playwright playwright ``` -------------------------------- ### Provide HttpClient with provideHttpClient Source: https://angular.dev/guide/http/setup Configure HttpClient by including `provideHttpClient()` in your application's providers. This is the standard way to set up the client for use throughout your app. ```typescript export const appConfig: ApplicationConfig = { providers: [provideHttpClient()], }; ``` -------------------------------- ### Complete Template-Driven Form Example Source: https://angular.dev/guide/forms/template-driven-forms This example shows a complete template-driven form with two-way data binding for name, studio, and skill. It includes the `name` attribute for each control, which is required when using `[(ngModel)]`, and a diagnostic `json` pipe to display the model's state. ```html {{ model | json }}
```