### Install Dependencies with pnpm Source: https://github.com/angular/components/blob/main/DEV_ENVIRONMENT.md Installs all project dependencies from the root directory using pnpm package manager. This command must be run after cloning the repository to set up the complete development environment. ```bash pnpm i ``` -------------------------------- ### Component Harness Testing Example Source: https://github.com/angular/components/blob/main/src/cdk/testing/test-harnesses.md Complete example demonstrating how to use TestbedHarnessEnvironment to test a reusable dialog-button component with nested components. Shows loading harnesses for the button inside the fixture and the dialog outside the fixture. ```APIDOC ## Component Harness Testing Example ### Description Complete example demonstrating how to use TestbedHarnessEnvironment to test a reusable dialog-button component with nested components and elements outside the fixture. ### Components Being Tested - **MyDialogButton** - Composes MyButton and MyDialog with a convenient API - **MyButton** - A simple button component - **MyDialog** - A dialog appended to `document.body` by MyDialogButton upon click ### Test Setup ```typescript let fixture: ComponentFixture; let loader: HarnessLoader; let rootLoader: HarnessLoader; beforeEach(() => { fixture = TestBed.createComponent(MyDialogButton); loader = TestbedHarnessEnvironment.loader(fixture); rootLoader = TestbedHarnessEnvironment.documentRootLoader(fixture); }); ``` ### Test Implementation ```typescript it('loads harnesses', async () => { // Load a harness for the bootstrapped component with `harnessForFixture` const 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 }); ``` ### Key Points - Use `harnessForFixture()` for the bootstrapped component - Use `loader()` for elements inside the fixture - Use `documentRootLoader()` for elements outside the fixture (e.g., dialogs) - Harnesses may not behave exactly the same in all environments - CDK makes best effort to normalize behavior and simulate important events ``` -------------------------------- ### ComponentHarness with TestElement Example Source: https://github.com/angular/components/blob/main/src/cdk/testing/test-harnesses.md Example implementation of a ComponentHarness that properly encapsulates TestElement interactions. Demonstrates best practices for creating focused harness methods that abstract away internal DOM structure. ```APIDOC ## ComponentHarness Implementation Example ### Description This example shows how to properly use TestElement within a ComponentHarness by encapsulating DOM interactions into focused, user-facing methods. ### Code Example ```typescript class MyPopupHarness extends ComponentHarness { static hostSelector = 'my-popup'; protected getTriggerElement = this.locatorFor('button'); protected getContentElement = this.locatorForOptional('.my-popup-content'); /** Toggles the open state of the popup. */ async toggle() { const trigger = await this.getTriggerElement(); return trigger.click(); } /** Checks if the popup is open. */ async isOpen() { const content = await this.getContentElement(); return !!content; } } ``` ### Key Concepts **Locator Methods** - `this.locatorFor(selector)` - Returns a function that locates a required element - `this.locatorForOptional(selector)` - Returns a function that locates an optional element **Encapsulation Pattern** - Internal TestElement instances are kept private (protected getTriggerElement) - Public methods (toggle, isOpen) provide the user-facing API - Users interact with the harness methods, not directly with TestElement **Benefits** - Component internal DOM structure can change without breaking user tests - Provides clear, semantic API for component interaction - Reduces coupling between tests and component implementation - Makes tests more maintainable and readable ``` -------------------------------- ### Install Angular Material Experimental Package Source: https://github.com/angular/components/blob/main/src/material-experimental/README.md Install the experimental components package via npm. This package contains prototypes and experiments that may have breaking changes with any release. ```bash npm i @angular/material-experimental ``` -------------------------------- ### Install Angular Google Maps via CLI Source: https://github.com/angular/components/blob/main/src/google-maps/README.md Uses the Angular CLI to add the @angular/google-maps package to your project, handling initial setup and dependency management. ```bash ng add @angular/google-maps ``` -------------------------------- ### Creating and Attaching Content to a CDK Overlay (TypeScript) Source: https://github.com/angular/components/blob/main/src/cdk/overlay/overlay.md Use `overlay.create()` to get an `OverlayRef` and then attach a `Portal` (e.g., `ComponentPortal`) to display content within the overlay. ```ts const overlayRef = overlay.create(); const userProfilePortal = new ComponentPortal(UserProfile); overlayRef.attach(userProfilePortal); ``` -------------------------------- ### Configure CDK Tree with DataSource and TrackBy Source: https://github.com/angular/components/blob/main/src/cdk/tree/tree.md Demonstrates the basic setup of a cdk-tree component, binding it to a data source and providing a trackBy function to optimize rendering performance. ```html ``` -------------------------------- ### Complete CDK Table Implementation Source: https://github.com/angular/components/blob/main/src/cdk/table/table.md A full example of a CDK table with three columns (username, age, title). It includes the table container, column definitions, and row declarations. ```html
User name {{row.username}} Age {{row.age}} Title {{row.title}}
``` -------------------------------- ### COMPONENT / mat-datepicker Starting View Source: https://github.com/angular/components/blob/main/src/material/datepicker/datepicker.md Configures the initial view of the calendar pop-up using startView and startAt properties of the mat-datepicker component. ```APIDOC ## COMPONENT / mat-datepicker Starting View ### Description Controls the initial display of the calendar when it opens, allowing to set the view to month, year, or multi-year, and specify a starting date. ### Method COMPONENT ### Endpoint `` ### Parameters #### Input Properties - **startView** (string) - Optional - Default: "month" - Sets the calendar's initial view: "month", "year", or "multi-year". - **startAt** (Date) - Optional - Overrides the default starting date for the calendar view. ### Request Example (HTML Usage) ```html ``` ```typescript // In your component startDate = new Date(2020, 0, 1); // January 1, 2020 ``` ### Response N/A ``` -------------------------------- ### Run Angular Development Server Source: https://github.com/angular/components/blob/main/guides/getting-started.md This command starts the local development server for your Angular application, allowing you to view changes in your browser at http://localhost:4200. ```bash ng serve ``` -------------------------------- ### Navigation and Action Lists Source: https://github.com/angular/components/blob/main/src/dev-app/list/list-demo.html Implementation of interactive lists used for navigation or triggering actions. Includes examples of icons and conditional 'more info' blocks. ```html @for (link of links; track link) { {{ link.name }} } @if (infoClicked) { More info! } @for (link of links; track link) { {{link.name}} } ``` -------------------------------- ### Set up HarnessLoader and load component harnesses in Angular unit tests Source: https://github.com/angular/components/blob/main/src/cdk/testing/test-harnesses.md Demonstrates how to initialize TestbedHarnessEnvironment with a component fixture in the beforeEach block and load harnesses for components at different DOM levels. Shows usage of loader() for elements inside the fixture, documentRootLoader() for elements outside, and harnessForFixture() for bootstrapped components. ```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 tslib Peer Dependency for Angular Components Source: https://github.com/angular/components/blob/main/CHANGELOG_ARCHIVE.md This code snippet provides commands to manually install `tslib`, which is now a peer dependency for Angular Components. This step is necessary for users who are not utilizing the Angular CLI for their project setup. ```bash yarn add tslib ``` ```bash npm install tslib --save ``` -------------------------------- ### Start Local Development Server Source: https://github.com/angular/components/blob/main/DEV_ENVIRONMENT.md Launches a local development server that automatically watches for file changes and rebuilds the project. The browser automatically refreshes when changes are detected, enabling rapid development iteration. ```bash pnpm dev-app ``` -------------------------------- ### Implement Range Selection in Angular Material Slider Source: https://github.com/angular/components/blob/main/src/material/slider/slider.md This example shows how to transform a standard slider into a range slider. By projecting both matSliderStartThumb and matSliderEndThumb, users can select a start and end value within the defined range. ```html ``` -------------------------------- ### Position Icons on Both Sides of Text in an Angular Material Button Source: https://github.com/angular/components/blob/main/src/material/button/button.md This HTML snippet illustrates how to place icons both before and after the text label within an Angular Material button. A `mat-icon` without `iconPositionEnd` will appear at the start, while one with `iconPositionEnd` will appear at the end. This example creates a 'Navigate' button with forward and backward arrows. ```html ``` -------------------------------- ### Enable Strong Focus Indicators with Angular Material Theme Source: https://github.com/angular/components/blob/main/guides/theming.md Demonstrates how to enable strong focus indicators in Angular Material by including the mat.strong-focus-indicators() mixin within the theme configuration. This provides highly visible outlines on focused elements to meet accessibility requirements like WCAG 4.5:1. The example shows a complete theme setup with color, typography, and density settings alongside the focus indicators mixin. ```scss @use '@angular/material' as mat; html { color-scheme: light dark; @include mat.theme(( color: mat.$violet-palette, typography: Roboto, density: 0 )); @include mat.strong-focus-indicators(); } ``` -------------------------------- ### Handle Mat-Tree node activation and click events Source: https://github.com/angular/components/blob/main/src/material/tree/tree.md This example shows how to listen for `(click)` and `(activation)` events on a `mat-tree-node`. The `(activation)` event is triggered by keyboard interaction, providing the node's data as `$event`, allowing for consistent action handling regardless of input method. ```html ``` -------------------------------- ### Listing Guide Items in Angular Template Source: https://github.com/angular/components/blob/main/docs/src/app/pages/homepage/homepage.html This Angular template snippet iterates over a collection of 'guideItems' obtained from 'guideItems.getAllItems()'. For each guide, it displays its name and a brief overview, providing a simple way to list documentation guides. ```html @for (guide of guideItems.getAllItems(); track guide) { {{guide.name}} {{guide.overview}} } ``` -------------------------------- ### Install Packages from CI Build Artifacts Source: https://github.com/angular/components/blob/main/DEV_ENVIRONMENT.md Configures package.json to install Angular packages from CircleCI build artifacts using URLs to compressed .tgz files. This allows testing Pull Request changes by pointing dependencies to artifact URLs and running pnpm install. ```json "dependencies": { "@angular/cdk": "https://<...>.circle-artifacts.com<...>/cdk-pr12345-a1b2c3d.tgz", "@angular/material": "https://<...>.circle-artifacts.com<...>/material-pr12345-a1b2c3d.tgz" } ``` -------------------------------- ### FocusKeyManager with Wrapping Configuration Source: https://github.com/angular/components/blob/main/src/cdk/a11y/a11y.md Demonstrates initializing a FocusKeyManager with wrapping enabled. The withWrap() method allows keyboard navigation to wrap around from the last to first item and vice versa. ```TypeScript this.keyManager = new FocusKeyManager(...).withWrap(); ``` -------------------------------- ### Displaying MapInfoWindow in Angular Source: https://github.com/angular/components/blob/main/src/google-maps/map-info-window/README.md This example demonstrates how to set up a MapInfoWindow within an Angular component. It shows how to use ViewChild to reference the info window and open it when a marker is clicked, including both the TypeScript logic and the HTML template structure. ```typescript // google-maps-demo.component.ts import {Component, ViewChild} from '@angular/core'; import {GoogleMap, MapInfoWindow, MapMarker} from '@angular/google-maps'; @Component({ selector: 'google-map-demo', templateUrl: 'google-map-demo.html', imports: [GoogleMap, MapInfoWindow, MapMarker], }) export class GoogleMapDemo { @ViewChild(MapInfoWindow) infoWindow: MapInfoWindow; center: google.maps.LatLngLiteral = {lat: 24, lng: 12}; markerPositions: google.maps.LatLngLiteral[] = []; zoom = 4; addMarker(event: google.maps.MapMouseEvent) { this.markerPositions.push(event.latLng.toJSON()); } openInfoWindow(marker: MapMarker) { this.infoWindow.open(marker); } } ``` ```html @for (position of markerPositions; track position) { } Info Window content ``` -------------------------------- ### Configure GoogleMap Component with Options Object Source: https://github.com/angular/components/blob/main/src/google-maps/README.md Shows how to initialize the GoogleMap component by binding a google.maps.MapOptions object to the [options] input. This is useful for passing complex configurations in a single binding. ```html ``` ```typescript options: google.maps.MapOptions = { center: {lat: 40, lng: -20}, zoom: 4 }; ``` -------------------------------- ### Install Angular CDK with ng add command Source: https://github.com/angular/components/blob/main/guides/schematics.md Installs only the Component Dev Kit (CDK) package when Material components are not needed. CDK provides low-level utility functions and directives for building custom components. ```bash ng add @angular/cdk ``` -------------------------------- ### Prefer Granular and Focused HTML Components Source: https://github.com/angular/components/blob/main/CODING_STANDARDS.md This example demonstrates the preferred practice of using distinct, focused HTML components (e.g., , ) for different functionalities or appearances. This improves clarity, testability, and maintainability by adhering to the single responsibility principle. ```html Basic button FAB pony ``` -------------------------------- ### METHODS show() and hide() Source: https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.md Programmatic methods to manually control the visibility of the tooltip instance. ```APIDOC ## METHODS show() / hide() ### Description Manually causes the tooltip to show or hide with an optional delay. ### Method FUNCTION ### Endpoint MatTooltip.show(delay?: number) / MatTooltip.hide(delay?: number) ### Parameters #### Arguments - **delay** (number) - Optional - The amount of time in milliseconds to wait before applying the display change. ### Request Example // In component class @ViewChild(MatTooltip) tooltip: MatTooltip; openTooltip() { this.tooltip.show(200); } ### Response #### Success Response (void) - **void** - The method triggers a UI state change without returning a value. ``` -------------------------------- ### MatMenuItem.getLabel() Source: https://github.com/angular/components/blob/main/goldens/material/menu/index.api.md Gets the label of the menu item. ```APIDOC ## METHOD MatMenuItem.getLabel() ### Description Gets the label of the menu item. ### Method getLabel ### Parameters (None) ### Return Value string ``` -------------------------------- ### Supporting Windows High-Contrast Mode in CSS Source: https://github.com/angular/components/blob/main/CODING_STANDARDS.md Implement styles to support Windows high-contrast mode, which significantly improves accessibility for low-vision users. This is a low-effort task with a high impact. The example shows how to use the `cdk-high-contrast` mixin to apply specific styles for active high-contrast mode. ```css @include cdk-high-contrast(active, off) { .unicorn-motocycle { border: 1px solid #fff !important; } } ``` -------------------------------- ### GET MatOptionHarness.isDisabled Source: https://github.com/angular/components/blob/main/goldens/material/core/testing/index.api.md Checks if the option is disabled. ```APIDOC ## GET MatOptionHarness.isDisabled ### Description Checks if the option is disabled. ### Method GET (conceptual) ### Endpoint MatOptionHarness.isDisabled() ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (N/A) ### Response #### Success Response (Promise) - **isDisabled** (boolean) - True if the option is disabled, false otherwise. #### Response Example true ``` -------------------------------- ### GET MatOptionHarness.isSelected Source: https://github.com/angular/components/blob/main/goldens/material/core/testing/index.api.md Checks if the option is currently selected. ```APIDOC ## GET MatOptionHarness.isSelected ### Description Checks if the option is currently selected. ### Method GET (conceptual) ### Endpoint MatOptionHarness.isSelected() ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (N/A) ### Response #### Success Response (Promise) - **isSelected** (boolean) - True if the option is selected, false otherwise. #### Response Example true ``` -------------------------------- ### Generate and Apply System Utility Classes Source: https://github.com/angular/components/blob/main/guides/theming.md Includes the mat.system-classes mixin to generate CSS utility classes and demonstrates how to apply them to HTML elements for consistent styling. ```scss html { @include mat.system-classes(); } ``` ```html ``` -------------------------------- ### GET MatOptgroupHarness.isDisabled Source: https://github.com/angular/components/blob/main/goldens/material/core/testing/index.api.md Checks if the option group is disabled. ```APIDOC ## GET MatOptgroupHarness.isDisabled ### Description Checks if the option group is disabled. ### Method GET (conceptual) ### Endpoint MatOptgroupHarness.isDisabled() ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (N/A) ### Response #### Success Response (Promise) - **isDisabled** (boolean) - True if the option group is disabled, false otherwise. #### Response Example true ``` -------------------------------- ### ToolbarWidgetHarness.click() Source: https://github.com/angular/components/blob/main/goldens/aria/toolbar/testing/index.api.md Clicks the toolbar widget. ```APIDOC ## Class: ToolbarWidgetHarness ### Method: click(): Promise ### Description Clicks the toolbar widget. ### Parameters (None) ### Returns `Promise` - A promise that resolves when the click action is complete. ``` -------------------------------- ### ToolbarWidgetHarness.getText() Source: https://github.com/angular/components/blob/main/goldens/aria/toolbar/testing/index.api.md Gets the text content of the toolbar widget. ```APIDOC ## Class: ToolbarWidgetHarness ### Method: getText(): Promise ### Description Gets the text content of the toolbar widget. ### Parameters (None) ### Returns `Promise` - A promise that resolves to the text content of the widget. ``` -------------------------------- ### ToolbarHarness.getOrientation() Source: https://github.com/angular/components/blob/main/goldens/aria/toolbar/testing/index.api.md Gets the orientation of the toolbar (vertical or horizontal). ```APIDOC ## Class: ToolbarHarness ### Method: getOrientation(): Promise<'vertical' | 'horizontal'> ### Description Gets the orientation of the toolbar (vertical or horizontal). ### Parameters (None) ### Returns `Promise<'vertical' | 'horizontal'>` - A promise that resolves to the orientation of the toolbar. ``` -------------------------------- ### MapKmlLayer Component Setup - TypeScript Source: https://github.com/angular/components/blob/main/src/google-maps/map-kml-layer/README.md Demonstrates how to set up the MapKmlLayer component in an Angular component class. Imports the necessary GoogleMap and MapKmlLayer components, defines the map center coordinates and zoom level, and specifies the KML file URL to be displayed on the map. ```typescript import {Component} from '@angular/core'; import {GoogleMap, MapKmlLayer} from '@angular/google-maps'; @Component({ selector: 'google-map-demo', templateUrl: 'google-map-demo.html', imports: [GoogleMap, MapKmlLayer], }) export class GoogleMapDemo { center: google.maps.LatLngLiteral = {lat: 24, lng: 12}; zoom = 4; kmlUrl = 'https://developers.google.com/maps/documentation/javascript/examples/kml/westcampus.kml'; } ``` -------------------------------- ### Implement Explicit Dark Theme with High Contrast Overrides Source: https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/README.md This SCSS example shows how to define a dark theme explicitly and apply high contrast overrides for it. The theme is applied by default, and a media query ensures high contrast colors are used when the user's system preferences indicate a preference for more contrast. ```scss @use '@angular/material'; @use './path/to/my-theme'; // location of generated file html { // Apply the dark theme by default @include material.theme(( color: ( primary: my-theme.$primary-palette, tertiary: my-theme.$tertiary-palette, theme-type: dark, ), typography: Roboto, density: 0, )); // Use high contrast dark theme colors when users prefer contrast @media (prefers-contrast: more) { @include my-theme.high-contrast-overrides(dark); } } ``` -------------------------------- ### MyMenuHarness with Sub-harness Locators Source: https://github.com/angular/components/blob/main/src/cdk/testing/test-harnesses.md Implements a ComponentHarness for MyMenu that uses locatorFor to get a single MyPopupHarness and locatorForAll to get all MyMenuItemHarness instances. Provides a toggle method that delegates to the popup harness. Demonstrates composition of harnesses for testing nested component hierarchies. ```TypeScript class MyMenuHarness extends ComponentHarness { static hostSelector = 'my-menu'; protected getPopupHarness = this.locatorFor(MyPopupHarness); /** Gets the currently shown menu items (empty list if menu is closed). */ getItems = this.locatorForAll(MyMenuItemHarness); /** Toggles open state of the menu. */ async toggle() { const popupHarness = await this.getPopupHarness(); return popupHarness.toggle(); } } class MyMenuItemHarness extends ComponentHarness { static hostSelector = 'my-menu-item'; } ``` -------------------------------- ### GET MatOptionHarness.isMultiple Source: https://github.com/angular/components/blob/main/goldens/material/core/testing/index.api.md Checks if the option is part of a multiple-selection control. ```APIDOC ## GET MatOptionHarness.isMultiple ### Description Checks if the option is part of a multiple-selection control. ### Method GET (conceptual) ### Endpoint MatOptionHarness.isMultiple() ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (N/A) ### Response #### Success Response (Promise) - **isMultiple** (boolean) - True if the option is for a multiple-selection control, false otherwise. #### Response Example false ``` -------------------------------- ### Implement Lazy Rendering for Mat Expansion Panel Content Source: https://github.com/angular/components/blob/main/src/material/expansion/expansion.md This snippet demonstrates how to defer the initialization of an expansion panel's content until the panel is opened. By wrapping the content in an `` with the `matExpansionPanelContent` directive, the content is only rendered when the panel expands, improving performance for complex panels. ```html This is the expansion title Some deferred content ``` -------------------------------- ### GET MatOptionHarness.getText Source: https://github.com/angular/components/blob/main/goldens/material/core/testing/index.api.md Retrieves the text content of the option harness. ```APIDOC ## GET MatOptionHarness.getText ### Description Retrieves the text content of the option harness. ### Method GET (conceptual) ### Endpoint MatOptionHarness.getText() ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (N/A) ### Response #### Success Response (Promise) - **text** (string) - The text content of the option. #### Response Example "Option 1" ``` -------------------------------- ### Create Adaptive Theme with High Contrast Support Source: https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/README.md This SCSS snippet demonstrates creating a single theme that adapts to both light and dark modes based on user preferences, including high contrast support. By setting `color-scheme: light dark` and using `high-contrast-overrides(color-scheme)`, the theme automatically adjusts for various user settings. ```scss @use '@angular/material'; @use './path/to/my-theme'; // location of generated file html { // Must specify color-scheme for theme mixin to automatically work color-scheme: light dark; // Create one theme that works automatically for light and dark theme @include material.theme(( color: ( primary: my-theme.$primary-palette, tertiary: my-theme.$tertiary-palette, ), typography: Roboto, density: 0, )); // Use high contrast values when users prefer contrast @media (prefers-contrast: more) { @include my-theme.high-contrast-overrides(color-scheme); } } ``` -------------------------------- ### Angular Material mat-checkbox Basic Example Source: https://github.com/angular/components/blob/main/src/dev-app/checkbox/checkbox-demo.html Demonstrates basic mat-checkbox usage with label, checked state binding, and change event handling. The example shows a checkbox with a question prompt that displays results through a printResult() function. This is the foundational pattern for implementing checkboxes in Angular Material applications. ```HTML Do you want to _foobar_ the _bazquux_? - **{{printResult()}} ``` -------------------------------- ### Basic Table Setup with Data Source Source: https://github.com/angular/components/blob/main/src/material/table/table.md Initialize a mat-table component with a data array. The table renders one row for each object in the data array and requires calling renderRows() method to trigger updates when data changes. ```APIDOC ## mat-table Component ### Description Provides a Material Design styled data-table for displaying rows of data. Builds on the CDK data-table foundation with mat- prefixed selectors. ### Selector `` ### Inputs - **dataSource** (Array | DataSource | Observable) - Required - The data source for the table. Can be a simple array, DataSource instance, or Observable stream. ### Methods - **renderRows()** - Triggers an update to the table's rendered rows. Call this method when objects are added, removed, or moved in the data array. ### Basic Usage Example ```html
...
``` ### Component TypeScript ```typescript export class MyTableComponent { myDataArray = [ { userName: 'John', age: 30 }, { userName: 'Jane', age: 25 } ]; } ``` ### Notes - The table optimizes for performance and does not automatically check for data array changes - For complex applications, using a DataSource instance is recommended over simple arrays - Column definitions must be provided separately using ng-container with matColumnDef ``` -------------------------------- ### MatExpansionPanelHarness for Panel Interaction Source: https://github.com/angular/components/blob/main/goldens/material/expansion/testing/index.api.md A harness class for interacting with mat-expansion-panel. It supports actions like expand, collapse, toggle, and focus, as well as state queries for title, description, and visibility. ```typescript export class MatExpansionPanelHarness extends ContentContainerComponentHarness { blur(): Promise; collapse(): Promise; expand(): Promise; focus(): Promise; getDescription(): Promise; getHarnessLoaderForContent(): Promise; getTextContent(): Promise; getTitle(): Promise; getToggleIndicatorPosition(): Promise<'before' | 'after'>; hasToggleIndicator(): Promise; static hostSelector: string; isDisabled(): Promise; isExpanded(): Promise; isFocused(): Promise; toggle(): Promise; static with(options?: ExpansionPanelHarnessFilters): HarnessPredicate; } ``` -------------------------------- ### MatBottomSheetRef.afterOpened(): Observable Source: https://github.com/angular/components/blob/main/goldens/material/bottom-sheet/index.api.md Gets an observable that is emitted when the bottom sheet is opened. ```APIDOC ## MatBottomSheetRef.afterOpened ### Description Gets an observable that is emitted when the bottom sheet has finished opening. ### Method `afterOpened` ### Response #### Success Response - **Observable** - An observable that emits when the bottom sheet is opened. ``` -------------------------------- ### GET MatOptionHarness.isActive Source: https://github.com/angular/components/blob/main/goldens/material/core/testing/index.api.md Checks if the option is currently active (e.g., focused or hovered). ```APIDOC ## GET MatOptionHarness.isActive ### Description Checks if the option is currently active (e.g., focused or hovered). ### Method GET (conceptual) ### Endpoint MatOptionHarness.isActive() ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (N/A) ### Response #### Success Response (Promise) - **isActive** (boolean) - True if the option is active, false otherwise. #### Response Example true ``` -------------------------------- ### TestbedHarnessEnvironment.documentRootLoader() Source: https://github.com/angular/components/blob/main/src/cdk/testing/test-harnesses.md Gets a HarnessLoader instance for the given fixture, rooted at the HTML document's root element. This method is used to create harnesses for elements that fall outside of the fixture, such as dialogs appended to document.body. ```APIDOC ## TestbedHarnessEnvironment.documentRootLoader() ### Description Gets a `HarnessLoader` instance for the given fixture, rooted at the HTML document's root element. Can be used to create harnesses for elements that fall outside of the fixture. ### Method Static Method ### Signature ```typescript documentRootLoader(fixture: ComponentFixture): HarnessLoader ``` ### Parameters #### Method Parameters - **fixture** (ComponentFixture) - Required - The component fixture for which to create a document-rooted HarnessLoader ### Return Value - **HarnessLoader** - A loader instance rooted at the document's root element ### Usage Example ```typescript let fixture: ComponentFixture; let rootLoader: HarnessLoader; beforeEach(() => { fixture = TestBed.createComponent(MyDialogButton); rootLoader = TestbedHarnessEnvironment.documentRootLoader(fixture); }); it('loads dialog harness', async () => { // Dialog is appended to document.body, outside fixture const dialogHarness = await rootLoader.getHarness(MyDialogHarness); }); ``` ### Use Cases - Loading harnesses for dialogs appended to `document.body` - Testing elements rendered outside the component fixture - Accessing elements in the document root that are not children of the fixture ``` -------------------------------- ### GET MatOptgroupHarness.getLabelText Source: https://github.com/angular/components/blob/main/goldens/material/core/testing/index.api.md Retrieves the text content of the label for the option group harness. ```APIDOC ## GET MatOptgroupHarness.getLabelText ### Description Retrieves the text content of the label for the option group harness. ### Method GET (conceptual) ### Endpoint MatOptgroupHarness.getLabelText() ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (N/A) ### Response #### Success Response (Promise) - **label** (string) - The text content of the option group's label. #### Response Example "Group 1" ``` -------------------------------- ### ListboxHarness.getActiveDescendantId() Source: https://github.com/angular/components/blob/main/goldens/aria/listbox/testing/index.api.md Gets the ID of the currently active descendant element within the listbox. ```APIDOC ## ListboxHarness.getActiveDescendantId() ### Description Retrieves the ID of the currently active descendant element within the listbox. This is typically used for ARIA `aria-activedescendant` attribute. ### Method `getActiveDescendantId()` ### Parameters None ### Returns `Promise` - A promise that resolves with the active descendant's ID, or `null` if none is active. ``` -------------------------------- ### Access Native MediaQueryList with MediaMatcher Source: https://github.com/angular/components/blob/main/src/cdk/layout/layout.md Demonstrates the low-level MediaMatcher service which wraps the native matchMedia API. It is used to obtain a MediaQueryList while normalizing browser differences and facilitating unit testing. ```typescript @Component({...}) class MyComponent { private mediaMatcher = inject(MediaMatcher); private mediaQueryList = this.mediaMatcher.matchMedia('(min-width: 1px)'); } ``` -------------------------------- ### POST MatOptionHarness.click Source: https://github.com/angular/components/blob/main/goldens/material/core/testing/index.api.md Performs a click action on the option harness. ```APIDOC ## POST MatOptionHarness.click ### Description Performs a click action on the option harness. ### Method POST (conceptual) ### Endpoint MatOptionHarness.click() ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Request Example (N/A) ### Response #### Success Response (Promise) (No content) #### Response Example (No content) ``` -------------------------------- ### PROPERTY alignTabs Source: https://github.com/angular/components/blob/main/goldens/material/tabs/index.api.md Aligns the tab header content. Can be 'start', 'center', or 'end'. ```APIDOC ## PROPERTY alignTabs ### Description Aligns the tab header content. Can be 'start', 'center', or 'end'. ### Type Input ### Property Name `alignTabs` (alias `mat-align-tabs`) ### Data Type `string` ### Example Usage ```html ``` ``` -------------------------------- ### CdkDragStart Source: https://github.com/angular/components/blob/main/goldens/cdk/drag-drop/index.api.md Interface representing the event data emitted when a drag sequence starts. ```APIDOC ## Interface: CdkDragStart ### Description Interface representing the event data emitted when a drag sequence starts. ### Properties - **event** (MouseEvent | TouchEvent) - The event that triggered the start of the drag. - **source** (CdkDrag) - The draggable item that started dragging. ``` -------------------------------- ### Initialize Basic Theme with mat.theme Mixin Source: https://github.com/angular/components/blob/main/guides/theming.md Defines a basic theme using the mat.theme mixin with a violet palette and Roboto font. It utilizes the color-scheme property to enable automatic light/dark mode switching based on system preferences. ```scss @use '@angular/material' as mat; html { color-scheme: light dark; @include mat.theme(( color: mat.$violet-palette, typography: Roboto, density: 0 )); } ``` -------------------------------- ### Apply Material Styles using Utility Classes in HTML Source: https://github.com/angular/components/blob/main/guides/theming-your-components.md Shows how to apply Material Design 2 styles directly in HTML templates using predefined utility classes. This approach provides a declarative way to handle background colors, text colors, and typography. ```html ``` -------------------------------- ### ListboxHarness and ListboxOptionHarness API Source: https://github.com/angular/components/blob/main/goldens/aria/listbox/testing/index.api.md Complete API definitions for testing listbox components. ListboxHarness provides methods to interact with the listbox container (focus, blur, get options, check orientation and disabled state), while ListboxOptionHarness provides methods for individual options (click, get text, check selection and disabled state). ```typescript import { BaseHarnessFilters } from '@angular/cdk/testing'; import { ComponentHarness } from '@angular/cdk/testing'; import { HarnessPredicate } from '@angular/cdk/testing'; // @public export class ListboxHarness extends ComponentHarness { blur(): Promise; focus(): Promise; getActiveDescendantId(): Promise; getOptions(filters?: ListboxOptionHarnessFilters): Promise; getOrientation(): Promise<'vertical' | 'horizontal'>; // (undocumented) static hostSelector: string; isDisabled(): Promise; isMulti(): Promise; static with(options?: ListboxHarnessFilters): HarnessPredicate; } // @public export interface ListboxHarnessFilters extends BaseHarnessFilters { disabled?: boolean; } // @public export class ListboxOptionHarness extends ComponentHarness { click(): Promise; getText(): Promise; // (undocumented) static hostSelector: string; isDisabled(): Promise; isSelected(): Promise; static with(options?: ListboxOptionHarnessFilters): HarnessPredicate; } // @public export interface ListboxOptionHarnessFilters extends BaseHarnessFilters { disabled?: boolean; selected?: boolean; text?: string | RegExp; } ``` -------------------------------- ### METHOD getAllChildLoaders(selector: string) Source: https://github.com/angular/components/blob/main/src/cdk/testing/test-harnesses.md Acts like `getChildLoader`, but returns an array of `HarnessLoader` instances, one for each matching element, rather than just the first matching element. ```APIDOC ## METHOD getAllChildLoaders(selector: string) ### Description Acts like `getChildLoader`, but returns an array of `HarnessLoader` instances, one for each matching element, rather than just the first matching element. ### Method Function ### Endpoint getAllChildLoaders(selector: string): Promise ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body - **selector** (string) - Required - The CSS selector to search for. ### Request Example (Not applicable for this type of API call) ### Response #### Success Response (200) - **Promise** (Promise) - A Promise that resolves to an array of `HarnessLoader` instances, one for each matching element. #### Response Example (Not applicable for this type of API call) ``` -------------------------------- ### MatBottomSheetRef.keydownEvents(): Observable Source: https://github.com/angular/components/blob/main/goldens/material/bottom-sheet/index.api.md Gets an observable of keydown events that are emitted from the bottom sheet. ```APIDOC ## MatBottomSheetRef.keydownEvents ### Description Gets an observable of keydown events that are emitted from the bottom sheet. ### Method `keydownEvents` ### Response #### Success Response - **Observable** - An observable that emits `KeyboardEvent`s from the bottom sheet. ``` -------------------------------- ### MatBottomSheetRef.backdropClick(): Observable Source: https://github.com/angular/components/blob/main/goldens/material/bottom-sheet/index.api.md Gets an observable that is emitted when the backdrop of the bottom sheet is clicked. ```APIDOC ## MatBottomSheetRef.backdropClick ### Description Gets an observable that is emitted when the backdrop of the bottom sheet is clicked. ### Method `backdropClick` ### Response #### Success Response - **Observable** - An observable that emits a `MouseEvent` when the backdrop is clicked. ``` -------------------------------- ### Apply Styles for High Contrast Mode with Angular CDK (SCSS) Source: https://github.com/angular/components/blob/main/src/cdk/a11y/a11y.md This SCSS example illustrates how to use the high-contrast mixin from @angular/cdk to define styles that apply only when the operating system is in High Contrast Mode. It targets the forced-colors media query, ensuring UI elements remain visible and usable for users with specific visual needs. ```scss @use '@angular/cdk'; button { @include cdk.high-contrast { outline: solid 1px; } } ``` -------------------------------- ### MatBottomSheetRef.afterDismissed(): Observable Source: https://github.com/angular/components/blob/main/goldens/material/bottom-sheet/index.api.md Gets an observable that is emitted when the bottom sheet is dismissed. ```APIDOC ## MatBottomSheetRef.afterDismissed ### Description Gets an observable that is emitted when the bottom sheet is dismissed. It will emit the result passed to the `dismiss` method. ### Method `afterDismissed` ### Response #### Success Response - **Observable** - An observable that emits the result when the bottom sheet is dismissed. ``` -------------------------------- ### Handle Node Activation and Click Events Source: https://github.com/angular/components/blob/main/src/cdk/tree/tree.md Shows how to implement interaction handlers on a tree node. The activation event ensures that keyboard-based interactions are captured for accessibility, while the click event handles mouse interactions. ```html ``` -------------------------------- ### Video Player Control Options Source: https://github.com/angular/components/blob/main/src/dev-app/youtube-player/youtube-player-demo.html Outlines configuration options for the video player component including cookie handling, placeholder display, playback start position, and fullscreen capability. These options control user experience aspects such as starting playback at a specific timestamp (30 seconds) and enabling/disabling visual placeholders during loading. ```Angular Configuration Disable cookies Disable placeholder Start at 30s Make fullscreen ``` -------------------------------- ### Initialize HarnessLoader for Angular unit tests Source: https://github.com/angular/components/blob/main/guides/using-component-harnesses.md This code demonstrates how to set up a `HarnessLoader` within an Angular unit test using `TestbedHarnessEnvironment`. It configures the testing module, creates a component fixture, and then initializes the loader to find Angular Material components for testing. ```typescript import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; let loader: HarnessLoader; describe('my-component', () => { beforeEach(async () => { TestBed.configureTestingModule({imports: [MyModule], declarations: [UserProfile]}); fixture = TestBed.createComponent(UserProfile); loader = TestbedHarnessEnvironment.loader(fixture); }); } ``` -------------------------------- ### Example Ambiguous Event Binding in Template Source: https://github.com/angular/components/blob/main/guides/v9-hammerjs-migration.md Shows an example of an ambiguous event binding that the migration tool cannot definitively resolve. The 'rotate' event could be either a HammerJS gesture event from the deprecated GestureConfig or an @Output property from the image-rotator component. Manual verification is required to determine the actual source and whether HammerJS can be safely removed. ```html ``` -------------------------------- ### GET MatOptgroupHarness.getOptions Source: https://github.com/angular/components/blob/main/goldens/material/core/testing/index.api.md Retrieves a list of MatOptionHarness instances belonging to this option group, optionally filtered. ```APIDOC ## GET MatOptgroupHarness.getOptions ### Description Retrieves a list of MatOptionHarness instances belonging to this option group, optionally filtered by `OptionHarnessFilters`. ### Method GET (conceptual) ### Endpoint MatOptgroupHarness.getOptions(filter?: OptionHarnessFilters) ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body - **filter** (OptionHarnessFilters) - Optional - An object to filter the returned options. - **isSelected** (boolean) - Optional - Filters options by their selected state. - **text** (string | RegExp) - Optional - Filters options by their text content. ### Request Example { "filter": { "text": "Option 1" } } ### Response #### Success Response (Promise) - **options** (array) - An array of MatOptionHarness instances. #### Response Example [ // MatOptionHarness objects ] ``` -------------------------------- ### MatTooltipDefaultOptions Interface Source: https://github.com/angular/components/blob/main/goldens/material/tooltip/index.api.md Defines the interface for default options that can be provided for all tooltips. ```APIDOC ## MatTooltipDefaultOptions Interface ### Description Interface for providing default options for all `MatTooltip` instances. These options can be configured globally. ### Properties - **detectHoverCapability** (boolean | (() => boolean)) - Optional - Whether to detect hover capability. - **disableTooltipInteractivity** (boolean) - Optional - Whether to disable tooltip interactivity. - **hideDelay** (number) - Required - Default delay in milliseconds before the tooltip hides. - **position** (TooltipPosition) - Optional - Default position of the tooltip relative to the origin. - **positionAtOrigin** (boolean) - Optional - Default for whether the tooltip should be positioned at the origin element's boundaries. - **showDelay** (number) - Required - Default delay in milliseconds before the tooltip shows. - **tooltipClass** (string | string[]) - Optional - Default custom CSS class(es) to be applied to the tooltip panel. - **touchendHideDelay** (number) - Required - Delay in milliseconds before hiding the tooltip on touchend. - **touchGestures** (TooltipTouchGestures) - Optional - Default for how touch gestures are handled by the tooltip. - **touchLongPressShowDelay** (number) - Optional - Delay in milliseconds before showing the tooltip on a long press. ``` -------------------------------- ### Configuring CDK Overlay Dimensions (TypeScript) Source: https://github.com/angular/components/blob/main/src/cdk/overlay/overlay.md Provide an optional configuration object to `overlay.create()` to set properties like height and width for the overlay panel. ```ts const overlayRef = overlay.create({ height: '400px', width: '600px' }); ```