id
stringlengths
6
6
text
stringlengths
20
17.2k
title
stringclasses
1 value
112789
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>YarnPnpCompat</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body class="mat-typography"> <app-root></app-root> </body> </html>
112791
@use '@angular/material' as mat; $primary: mat.m2-define-palette(mat.$m2-blue-palette); $accent: mat.m2-define-palette(mat.$m2-grey-palette); $theme: mat.m2-define-light-theme(( color: (primary: $primary, accent: $accent), typography: mat.m2-define-typography-config(), density: 0 )); @include mat.all-component-themes($theme); html, body { height: 100%; } body { margin: 0; font-family: Roboto, 'Helvetica Neue', sans-serif; }
112793
/** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes recent versions of Safari, Chrome (including * Opera), Edge on the desktop, and iOS and Chrome on mobile. * * Learn more in https://angular.dev/reference/versions#browser-support */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** * By default, zone.js will patch all possible macroTask and DomEvents * user can disable parts of macroTask/DomEvents patch by setting following flags * because those flags need to be set before `zone.js` being loaded, and webpack * will put import in the top of bundle, so user need to create a separate file * in this directory (for example: zone-flags.ts), and put the following flags * into that file, and then add the following code before importing zone.js. * import './zone-flags'; * * The flags allowed in zone-flags.ts are listed here. * * The following flags will work for all browsers. * * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames * * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js * with the following flag, it will bypass `zone.js` patch for IE/Edge * * (window as any).__Zone_enable_cross_context_check = true; * */ /*************************************************************************************************** * Zone JS is required by default for Angular itself. */ import 'zone.js'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */
112796
import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {MatButtonModule} from '@angular/material/button'; import {AppComponent} from './app.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, BrowserAnimationsModule, MatButtonModule], bootstrap: [AppComponent], }) export class AppModule {}
112803
# Customizing Angular Material component styles Angular Material supports customizing component styles via Sass API as described in the [theming guide][]. This document provides guidance on defining custom CSS rules that directly style Angular Material components. [theming guide]: https://material.angular.io/guide/theming ## Targeting custom styles ### Component host elements For any Angular Material component, you can safely define custom CSS for a component's host element that affect the positioning or layout of that component, such as `margin`, `position`, `top`, `left`, `transform`, and `z-index`. You should apply such styles by defining a custom CSS class and applying that class to the component's host element. Avoid defining custom styles that would affect the size or internal layout of the component, such as `padding`, `height`, `width`, or `overflow`. You can specify `display: none` to hide a component, but avoid specifying any other `display` value. Overriding these properties can break components in unexpected ways as the internal styles change between releases. ### Internal component elements Avoid any custom styles or overrides on internal elements within a Angular Material components. The DOM structure and CSS classes applied for each component may change at any time, causing custom styles to break. ## Applying styles to Angular Material components While Angular Material does not support defining custom styles or CSS overrides on components' internal elements, you might choose to do this anyway. There are three points to consider while customizing styles for Angular Material components: view encapsulation, CSS specificity, and rendering location. ### View encapsulation By default, Angular scopes component styles to exclusively affect that component's view. This means that the styles you author affect only the elements directly within your component template. Encapsulated styles do *not* affect elements that are children of other components within your template. You can read more about view encapsulation in the [Angular documentation](https://angular.dev/guide/components/styling#style-scoping). You may also wish to review [_The State of CSS in Angular_](https://blog.angular.io/the-state-of-css-in-angular-4a52d4bd2700) on the Angular blog. #### Bypassing encapsulation Angular Material disables style encapsulation for all components in the library. However, the default style encapsulation in your own components still prevents custom styles from leaking into Angular Material components. If your component enables view encapsulation, your component styles will only affect the elements explicitly defined in your template. To affect descendants of components used in your template, you can use one of the following approaches: 1. Define custom styles in a global stylesheet declared in the `styles` array of your `angular.json` configuration file. 2. Disable view encapsulation for your component. This approach effectively turns your component styles into global CSS. 3. Apply the deprecated `::ng-deep` pseudo-class to a CSS rule. Any CSS rule with `::ng-deep` becomes a global style. [See the Angular documentation for more on `::ng-deep`][ng-deep]. All of these approaches involve creating global CSS that isn't affected by style encapsulation. Global CSS affects all elements in your application. Global CSS class names may collide with class names defined by components. Global CSS is often a source of hard-to-diagnose bugs and is generally difficult to maintain. [ng-deep]: https://angular.dev/guide/components/styling#ng-deep ### CSS specificity Each CSS declaration has a level of *specificity* based on the type and number of selectors used. More specific styles take precedence over less specific styles. Angular Material generally attempts to use the least specific selectors possible. However, Angular Material may change component style specificity at any time, making custom overrides brittle and prone to breaking. You can read more about specificity and how it is calculated on the [MDN web docs](https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity). ### Rendering location Some Angular Material components render elements that are not direct DOM descendants of the component's host element. In particular, overlay-based components such as `MatDialog`, `MatMenu`, `MatTooltip`, etc. render into an overlay container element directly on the document body. Because these components render elements outside of your application's components, component-specific styles will not apply to these elements. You can define styles for these elements as global styles. #### Styling overlay components Overlay-based components have a `panelClass` property, or similar, that let you target the overlay pane. The following example shows how to add an `outline` style with `MatDialog`. ```scss // Add this to your global stylesheet after including theme mixins. .my-outlined-dialog { outline: 2px solid purple; } ``` ```ts this.dialog.open(MyDialogComponent, {panelClass: 'my-outlined-dialog'}) ``` You should always apply an application-specific prefix to global CSS classes to avoid naming collisions.
112804
# Installation and Code Generation Angular Material comes packaged with Angular CLI schematics to make creating Material applications easier. ## Install Schematics Schematics are included with both `@angular/cdk` and `@angular/material`. Once you install the npm packages, they will be available through the Angular CLI. Using the command below will install Angular Material, the [Component Dev Kit](https://material.angular.io/cdk) (CDK), and [Angular Animations](https://angular.dev/guide/animations) in your project. Then it will run the installation schematic. ``` ng add @angular/material ``` In case you just want to install the `@angular/cdk`, there are also schematics for the [Component Dev Kit](https://material.angular.io/cdk) ``` ng add @angular/cdk ``` The Angular Material `ng add` schematic helps you set up an Angular CLI project that uses Material. Running `ng add` will: - Ensure [project dependencies](./getting-started#step-1-install-angular-material-angular-cdk-and-angular-animations) are placed in `package.json` - Enable the [BrowserAnimationsModule](./getting-started#step-2-configure-animations) in your app module - Add either a [prebuilt theme](./theming#pre-built-themes) or a [custom theme](./theming#defining-a-custom-theme) - Add Roboto fonts to your `index.html` - Add the [Material Icon font](./getting-started#step-6-optional-add-material-icons) to your `index.html` - Add global styles to - Remove margins from `body` - Set `height: 100%` on `html` and `body` - Make Roboto the default font of your app ## Component schematics In addition to the installation schematic, Angular Material comes with multiple schematics that can be used to easily generate Material Design components: | Name | Description | |----------------|--------------------------------------------------------------------------------------------------------| | `address-form` | Component with a form group that uses Material Design form controls to prompt for a shipping address | | `navigation` | Creates a component with a responsive Material Design sidenav and a toolbar for showing the app name | | `dashboard` | Component with multiple Material Design cards and menus which are aligned in a grid layout | | `table` | Generates a component with a Material Design data table that supports sorting and pagination | | `tree` | Component that interactively visualizes a nested folder structure by using the `<mat-tree>` component | Additionally, the Angular CDK also comes with a collection of component schematics: | Name | Description | |----------------|----------------------------------------------------------------------------------------------------| | `drag-drop` | Component that uses the `@angular/cdk/drag-drop` directives for creating an interactive to-do list | ### Address form schematic Running the `address-form` schematic generates a new Angular component that can be used to get started with a Material Design form group consisting of: * Material Design form fields * Material Design radio controls * Material Design buttons ``` ng generate @angular/material:address-form <component-name> ``` ### Navigation schematic The `navigation` schematic will create a new component that includes a toolbar with the app name, and a responsive side nav based on Material breakpoints. ``` ng generate @angular/material:navigation <component-name> ``` ### Table schematic The table schematic will create a component that renders an Angular Material `<table>` which has been pre-configured with a datasource for sorting and pagination. ``` ng generate @angular/material:table <component-name> ``` ### Dashboard schematic The `dashboard` schematic will create a new component that contains a dynamic grid list of Material Design cards. ``` ng generate @angular/material:dashboard <component-name> ``` ### Tree schematic The `tree` schematic can be used to quickly generate an Angular component that uses the Angular Material `<mat-tree>` component to visualize a nested folder structure. ``` ng generate @angular/material:tree <component-name> ``` ### Drag and Drop schematic The `drag-drop` schematic is provided by the `@angular/cdk` and can be used to generate a component that uses the CDK drag and drop directives. ``` ng generate @angular/cdk:drag-drop <component-name> ``` ### Material 3 Theme schematic The `theme-color` schematic will generate a file with Material 3 palettes from the specified colors that can be used in a theme file. It also generates high contrast color override mixins if specified. ``` ng generate @angular/material:theme-color ``` Learn more about this schematic in its [documentation](https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/README.md).
112806
# Theme your own components with Angular Material's theming system You can use Angular Material's Sass-based theming system for your own custom components. **Note: The information on this page is specific to Material 3, for Material 2 information on how to theme your components see the [Material 2 guide][material-2].** [material-2]: https://material.angular.io/guide/material-2-theming#theming-your-components ## Reading values from a theme As described in the [theming guide][theme-map], a theme is a Sass map that contains style values to customize components. Angular Material provides APIs for reading values from this data structure. [theme-map]: https://material.angular.io/guide/theming#defining-a-theme ### Reading tonal palette colors To read a [tonal palette color](https://m3.material.io/styles/color/system/how-the-system-works#3ce9da92-a118-4692-8b2c-c5c52a413fa6) from the theme, use the `get-theme-color` function with three arguments: | Argument | Description | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `$theme` | The M3 theme to read from. | | `$palette` | The name of the palette to read from. This can be any of the standard M3 palettes:<ul><li>`primary`</li><li>`secondary`</li><li>`tertiary`</li><li>`error`</li><li>`neutral`</li><li>`neutral-variant`</li></ul> | | `$hue` | The hue number to read within the palette. This can be any of the standard hues:<ul><li>`0`</li><li>`10`</li><li>`20`</li><li>`30`</li><li>`40`</li><li>`50`</li><li>`60`</li><li>`70`</li><li>`80`</li><li>`90`</li><li>`95`</li><li>`99`</li><li>`100`</li></ul> | <!-- TODO(mmalerba): Illustrate palettes and hues with example. --> ### Reading color roles To read a [color role](https://m3.material.io/styles/color/roles), use `get-theme-color` with two arguments: | Argument | Description | | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `$theme` | The M3 theme to read from. | | `$role` | The name of the color role. This can be any of the M3 color roles:<ul><li>`primary`</li><li>`on-primary`</li><li>`primary-container`</li><li>`on-primary-container`</li><li>`primary-fixed`</li><li>`primary-fixed-dim`</li><li>`on-primary-fixed`</li><li>`on-primary-fixed-variant`</li><li>`secondary`</li><li>`on-secondary`</li><li>`secondary-container`</li><li>`on-secondary-container`</li><li>`secondary-fixed`</li><li>`secondary-fixed-dim`</li><li>`on-secondary-fixed`</li><li>`on-secondary-fixed-variant`</li><li>`tertiary`</li><li>`on-tertiary`</li><li>`tertiary-container`</li><li>`on-tertiary-container`</li><li>`tertiary-fixed`</li><li>`tertiary-fixed-dim`</li><li>`on-tertiary-fixed`</li><li>`on-tertiary-fixed-variant`</li><li>`error`</li><li>`on-error`</li><li>`error-container`</li><li>`on-error-container`</li><li>`surface-dim`</li><li>`surface`</li><li>`surface-bright`</li><li>`surface-container-lowest`</li><li>`surface-container-low`</li><li>`surface-container`</li><li>`surface-container-high`</li><li>`surface-container-highest`</li><li>`on-surface`</li><li>`on-surface-variant`</li><li>`outline`</li><li>`outline-variant`</li><li>`inverse-surface`</li><li>`inverse-on-surface`</li><li>`inverse-primary`</li><li>`scrim`</li><li>`shadow`</li></ul> | <!-- TODO(mmalerba): Illustrate color roles with example. --> ### Reading the theme type To read the theme type (`light` or `dark`), call `get-theme-type` with a single argument: | Argument | Description | | -------- | -------------------------- | | `$theme` | The M3 theme to read from. | ### Reading typescale properties To read a [typescale](https://m3.material.io/styles/typography/type-scale-tokens) property from the theme, call `get-theme-typography` with three arguments: | Argument | Description | | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `$theme` | The M3 theme to read from. | | `$level` | The typescale level. This can be any of the M3 typescale levels:<ul><li>`display-large`</li><li>`display-medium`</li><li>`display-small`</li><li>`headline-large`</li><li>`headline-medium`</li><li>`headline-small`</li><li>`title-large`</li><li>`title-medium`</li><li>`title-small`</li><li>`body-large`</li><li>`body-medium`</li><li>`body-small`</li><li>`label-large`</li><li>`label-medium`</li><li>`label-small`</li></ul> | | `$property` | The CSS font property to get a value for. This can be one of the following CSS properties:<ul><li>`font` (The CSS font shorthand, includes all font properties except letter-spacing)</li><li>`font-family`</li><li>`font-size`</li><li>`font-weight`</li><li>`line-height`</li><li>`letter-spacing`</li></ul> | <!-- TODO(mmalerba): Illustrate typescales with example. --> ### Reading the density scale To read the density scale (`0`, `-1`, `-2`, `-3`, `-4`, or `-5`) from the theme, call `get-theme-density` with a single argument: | Argument | Description | | -------- | -------------------------- | | `$theme` | The M3 theme to read from. | ### Checking what dimensions are configured for a theme Depending on how a theme was created, it may not have configuration data for all theming dimensions (base, color, typography, density). You can check if a theme has a configuration for a particular dimension by calling the `theme-has` Sass function, passing the theme and the dimension to check. See the below example of checking the configured dimensions for a theme: ```scss $theme: mat.define-theme(...); $has-base: mat.theme-has($theme, base); $has-color: mat.theme-has($theme, color); $has-typography: mat.theme-has($theme, typography); $has-density: mat.theme-has($theme, density); ``` ## Separating theme styles Angular Material components each have a Sass file that defines mixins for customizing that component's color and typography. For example, `MatButton` has mixins for `button-color` and `button-typography`. Each mixin emits all color and typography styles for that component, respectively. You can mirror this structure in your components by defining your own mixins. These mixins should accept an Angular Material theme, from which they can read color and typography values. You can then include these mixins in your application along with Angular Material's own mixins.
112807
## Step-by-step example To illustrate participation in Angular Material's theming system, we can look at an example of a custom carousel component. The carousel starts with a single file, `carousel.scss`, that contains structural, color, and typography styles. This file is included in the `styleUrls` of the component. ```scss // carousel.scss .my-carousel { display: flex; font-family: serif; } .my-carousel-button { border-radius: 50%; color: blue; } ``` ### Step 1: Extract theme-based styles to a separate file To change this file to participate in Angular Material's theming system, we split the styles into two files, with the color and typography styles moved into mixins. By convention, the new file name ends with `-theme`. Additionally, the file starts with an underscore (`_`), indicating that this is a Sass partial file. See the [Sass documentation][sass-partials] for more information about partial files. [sass-partials]: https://sass-lang.com/guide#topic-4 ```scss // carousel.scss .my-carousel { display: flex; } .my-carousel-button { border-radius: 50%; } ``` ```scss // _carousel-theme.scss @mixin color($theme) { .my-carousel-button { color: blue; } } @mixin typography($theme) { .my-carousel { font-family: serif; } } ``` ### Step 2: Use values from the theme Now that theme theme-based styles reside in mixins, we can extract the values we need from the theme passed into the mixins. ```scss // _carousel-theme.scss @use 'sass:map'; @use '@angular/material' as mat; @mixin color($theme) { .my-carousel-button { // Read the 50 hue from the primary color palette. color: mat.get-theme-color($theme, primary, 50); } } @mixin typography($theme) { .my-carousel { // Get the large headline font from the theme. font: mat.get-theme-typography($theme, headline-large, font); } } ``` ### Step 3: Add a theme mixin For convenience, we can add a `theme` mixin that includes both color and typography. This theme mixin should only emit the styles for each color and typography, respectively, if they have a config specified. ```scss // _carousel-theme.scss @use 'sass:map'; @use '@angular/material' as mat; @mixin color($theme) { .my-carousel-button { // Read the 50 hue from the primary color palette. color: mat.get-theme-color($theme, primary, 50); } } @mixin typography($theme) { .my-carousel { // Get the large headline font from the theme. font: mat.get-theme-typography($theme, headline-large, font); } } @mixin theme($theme) { @if mat.theme-has($theme, color) { @include color($theme); } @if mat.theme-has($theme, typography) { @include typography($theme); } } ``` ### Step 4: Include the theme mixin in your application Now that you've defined the carousel component's theme mixin, you can include this mixin along with the other theme mixins in your application. ```scss @use '@angular/material' as mat; @use './path/to/carousel-theme' as carousel; $my-theme: mat.define-theme(( color: ( theme-type: light, primary: mat.$red-palette, ), typography: ( brand-family: 'Comic Sans', bold-weight: 900, ), )); html { @include mat.all-component-themes($my-theme); @include carousel.theme($my-theme); } ```
112808
# Getting Started with Angular Material This guide explains how to set up your Angular project to begin using Angular Material. It includes information on prerequisites, installing Angular Material, and optionally displaying a sample Material component in your application to verify your setup. This guide assumes that the [Angular CLI](https://angular.dev/tools/cli/setup-local#install-the-angular-cli) has already been installed. ## Install Angular Material Add Angular Material to your application by running the following command: ```bash ng add @angular/material ``` The `ng add` command will install Angular Material, the [Component Dev Kit (CDK)](https://material.angular.io/cdk/categories), [Angular Animations](https://angular.dev/guide/animations) and ask you the following questions to determine which features to include: 1. Choose a prebuilt theme name, or "custom" for a custom theme: You can choose from [prebuilt material design themes](https://material.angular.io/guide/theming#pre-built-themes) or set up an extensible [custom theme](https://material.angular.io/guide/theming#defining-a-theme). 2. Set up global Angular Material typography styles: Whether to apply the global [typography](https://material.angular.io/guide/typography) styles to your application. 3. Set up browser animations for Angular Material: Importing the [`BrowserAnimationsModule`](https://angular.dev/api/platform-browser/animations/BrowserAnimationsModule) into your application enables Angular's [animation system](https://angular.dev/guide/animations). Declining this will disable most of Angular Material's animations. The `ng add` command will additionally perform the following actions: * Add project dependencies to `package.json` * Add the Roboto font to your `index.html` * Add the Material Design icon font to your `index.html` * Add a few global CSS styles to: * Remove margins from `body` * Set `height: 100%` on `html` and `body` * Set Roboto as the default application font You're done! Angular Material is now configured to be used in your application. ### Display a component Let's display a slide toggle component in your app and verify that everything works. You need to import the `MatSlideToggleModule` that you want to display by adding the following lines to your standalone component's imports, or otherwise your component's `NgModule`. ```ts import { MatSlideToggleModule } from '@angular/material/slide-toggle'; @Component ({ imports: [ MatSlideToggleModule, ] }) class AppComponent {} ``` Add the `<mat-slide-toggle>` tag to the `app.component.html` like so: ```html <mat-slide-toggle>Toggle me!</mat-slide-toggle> ``` Run your local dev server: ```bash ng serve ``` Then point your browser to [http://localhost:4200](http://localhost:4200) You should see the Material slide toggle component on the page. In addition to the installation schematic, Angular Material comes with [several other schematics](https://material.angular.io/guide/schematics) (like nav, table, address-form, etc.) that can be used to easily generate pre-built components in your application.
112809
# Theming Angular Material ## What is theming? Angular Material's theming system lets you customize base, color, typography, and density styles for components in your application. The theming system is based on Google's [Material Design 3][material-design-theming] specification which is the latest iteration of Google's open-source design system, Material Design. **For Material 2 specific documentation and how to update to Material 3, see the [Material 2 guide][material-2].** This document describes the concepts and APIs for customizing colors. For typography customization, see [Angular Material Typography][mat-typography]. For guidance on building components to be customizable with this system, see [Theming your own components][theme-your-own]. [material-design-theming]: https://m3.material.io/ [material-2]: https://material.angular.io/guide/material-2-theming [mat-typography]: https://material.angular.io/guide/typography [theme-your-own]: https://material.angular.io/guide/theming-your-components ### Sass Angular Material's theming APIs are built with [Sass](https://sass-lang.com). This document assumes familiarity with CSS and Sass basics, including variables, functions, and mixins. ### Custom themes with Sass A **theme file** is a Sass file that calls Angular Material Sass mixins to output color, typography, and density CSS styles. #### Defining a theme Angular Material represents a theme as a Sass map that contains your color, typography, and density choices, as well as some base design system settings. The simplest usage of the API, `$theme: mat.define-theme()` defines a theme with default values. However, `define-theme` allows you to configure the appearance of your Angular Material app along three theming dimensions: color, typography, and density, by passing a theme configuration object. The configuration object may have the following properties. | Property | Description | | ------------ | --------------------------------------------------------------------------------------------------------------- | | `color` | [Optional] A map of color options. See [customizing your colors](#customizing-your-colors) for details. | | `typography` | [Optional] A map of typography options. See [customizing your typography](#customizing-your-typography) for details. | | `density` | [Optional] A map of density options. See [customizing your density](#customizing-your-density) for details. | <!-- TODO(mmalerba): Upgrade to embedded example --> ```scss @use '@angular/material' as mat; $theme: mat.define-theme(( color: ( theme-type: dark, primary: mat.$violet-palette, ), typography: ( brand-family: 'Comic Sans', bold-weight: 900 ), density: ( scale: -1 ) )); ``` #### Customizing your colors The following aspects of your app's colors can be customized via the `color` property of the theme configuration object (see the [M3 color spec](https://m3.material.io/styles/color/roles) to learn more about these terms): | Color Property | Description | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `theme-type` | [Optional] Specifies the type of theme, `light` or `dark`. The choice of a light versus a dark theme determines the background and foreground colors used throughout the components. | | `primary` | [Optional] Specifies the palette to use for the app's primary color palette. (Note: the secondary, neutral, and neutral-variant palettes described in the M3 spec will be automatically chosen based on your primary palette, to ensure a harmonious color combination). | | `tertiary` | [Optional] Specifies the palette to use for the app's tertiary color palette. | ##### Pre-built themes Angular Material includes several pre-built theme CSS files, each with different palettes selected. You can use one of these pre-built themes if you don't want to define a custom theme with Sass. | Theme | Light or dark? | Specification | |------------------------|----------------|----------------------------------| | `azure-blue.css` | Light | Material Design 3 | | `rose-red.css` | Light | Material Design 3 | | `cyan-orange.css` | Dark | Material Design 3 | | `magenta-violet.css` | Dark | Material Design 3 | | `deeppurple-amber.css` | Light | Material Design 2 | | `indigo-pink.css` | Light | Material Design 2 | | `pink-bluegrey.css` | Dark | Material Design 2 | | `purple-green.css` | Dark | Material Design 2 | These files include the CSS for every component in the library. To include only the CSS for a subset of components, you must use the Sass API detailed in [Defining a theme](#defining-a-theme) above. You can [reference the source code for these pre-built themes](https://github.com/angular/components/blob/main/src/material/core/theming/prebuilt) to see examples of complete theme definitions. ##### Pre-defined palettes The pre-built themes are based on a set of pre-defined palettes that can be used with the `primary` and `tertiary` options: - `$red-palette` - `$green-palette` - `$blue-palette` - `$yellow-palette` - `$cyan-palette` - `$magenta-palette` - `$orange-palette` - `$chartreuse-palette` - `$spring-green-palette` - `$azure-palette` - `$violet-palette` - `$rose-palette` ##### Custom theme Alternatively, custom palettes can be generated with a custom color with the following schematic: ```shell ng generate @angular/material:theme-color ``` This schematic integrates with [Material Color Utilities](https://github.com/material-foundation/material-color-utilities) to build palettes based on a single color. Optionally you can provide additional custom colors for the secondary, tertiary, and neutral palettes. The output of the schematic is a new Sass file that exports the palettes that can be provided to a theme definition. ```scss @use '@angular/material' as mat; @use './path/to/my-theme'; // location of generated file html { @include mat.theme( color: ( primary: my-theme.$primary-palette, tertiary: my-theme.$tertiary-palette, ), typography: Roboto, density: 0, ) } ``` You can also optionally generate high contrast override mixins for your custom theme that allows for a better accessibility experience. Learn more about this schematic in its [documentation](https://github.com/angular/components/blob/main/src/material/schematics/ng-generate/theme-color/README.md). <!-- TODO(mmalerba): Illustrate palettes with example. --> #### Customizing your typography The following aspects of your app's typography can be customized via the `typography` property of the theme configuration object. | Typography Property | Description | | ------------------- | -------------------------------------------------------------------- | | `plain-family` | [Optional] The font family to use for plain text, such as body text. | | `brand-family` | [Optional] The font family to use for brand text, such as headlines. | | `bold-weight` | [Optional] The font weight to use for bold text. | | `medium-weight` | [Optional] The font weight to use for medium text. | | `regular-weight` | [Optional] The font weight to use for regular text. | See the [typography guide](https://material.angular.io/guide/typography) for more information. #### Customizing your density The following aspects of your app's density can be customized via the `density` property of the theme configuration object: | Density Property | Description | | ---------------- | ---------------------------------------------------------------------------------------------------------------- | | `scale` | [Optional] The level of compactness of the components in your app, from `0` (most space) to `-5` (most compact). |
112810
#### Applying a theme to components The `core-theme` Sass mixin emits prerequisite styles for common features used by multiple components, such as ripples. This mixin must be included once per theme. Each Angular Material component has a mixin for each [theming dimension](#theming-dimensions): base, color, typography, and density. For example, `MatButton` declares `button-base`, `button-color`, `button-typography`, and `button-density`. Each mixin emits only the styles corresponding to that dimension of customization. Additionally, each component has a "theme" mixin that emits all styles that depend on the theme config. This theme mixin only emits color, typography, or density styles if you provided a corresponding configuration to `define-theme`, and it always emits the base styles. Once you've created your theme, you can apply it using the same `-theme`, `-color`, `-typography`, `-density`, and `-base` mixins. For M3 themes, these mixins make some guarantees about the emitted styles. - The mixins emit properties under the exact selector you specify. They will _not_ add to the selector or increase the specificity of the rule. - The mixins only emit [CSS custom property declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties) (e.g. `--some-prop: xyz`). They do _not_ emit any standard CSS properties such as `color`, `width`, etc. Apply the styles for each of the components used in your application by including each of their theme Sass mixins. ```scss @use '@angular/material' as mat; $my-theme: mat.define-theme(( color: ( theme-type: light, primary: mat.$violet-palette, ), )); html { // Emit theme-dependent styles for common features used across multiple components. @include mat.core-theme($my-theme); // Emit styles for MatButton based on `$my-theme`. Because the configuration // passed to `define-theme` omits typography, `button-theme` will not // emit any typography styles. @include mat.button-theme($my-theme); // Include the theme mixins for other components you use here. } ``` As an alternative to listing every component that your application uses, Angular Material offers Sass mixins that includes styles for all components in the library: `all-component-bases`, `all-component-colors`, `all-component-typographies`, `all-component-densities`, and `all-component-themes`. These mixins behave the same as individual component mixins, except they emit styles for `core-theme` and _all_ 35+ components in Angular Material. Unless your application uses every single component, this will produce unnecessary CSS. ```scss @use '@angular/material' as mat; $my-theme: mat.define-theme(( color: ( theme-type: light, primary: mat.$violet-palette, ), )); html { @include mat.all-component-themes($my-theme); } ``` To include the emitted styles in your application, [add your theme file to the `styles` array of your project's `angular.json` file][adding-styles]. [adding-styles]: https://angular.dev/reference/configs/workspace-config#styles-and-scripts-configuration #### Theming dimensions Angular Material themes are divided along four dimensions: base, color, typography, and density. ##### Base Common base styles for the design system. These styles don't change based on your configured colors, typography, or density, so they only need to be included once per application. These mixins include structural styles such as border-radius, border-width, etc. All components have a base mixin that can be used to include its base styles. (For example, `@include mat.checkbox-base($theme)`) ##### Color Styles related to the colors in your application. These style should be included at least once in your application. Depending on your needs, you may need to include these styles multiple times with different configurations. (For example, if your app supports light and dark theme colors.) All components have a color mixin that can be used to include its color styles. (For example, `@include mat.checkbox-color($theme)`) ##### Typography Styles related to the fonts used in your application, including the font family, size, weight, line-height, and letter-spacing. These style should be included at least once in your application. Depending on your needs, you may need to include these styles multiple times with different configurations. (For example, if your app supports reading content in either a serif or sans-serif font.) All components have a typography mixin that can be used to include its typography styles. (For example, `@include mat.checkbox-typography($theme)`) ##### Density Styles related to the size and spacing of elements in your application. These style should be included at least once in your application. Depending on your needs, you may need to include these styles multiple times with different configurations. (For example, if your app supports both a normal and compact mode). All components have a density mixin that can be used to include its density styles. (For example, `@include mat.checkbox-density($theme)`) ##### Theme mixin All components also support a theme mixin that can be used to include the component's styles for all theme dimensions at once. (For example, `@include mat.checkbox-theme($theme)`). **The recommended approach is to rely on the `theme` mixins to lay down your base styles, and if needed use the single dimension mixins to override particular aspects for parts of your app (see the section on [Multiple themes in one file](#multiple-themes-in-one-file).)** ### Defining multiple themes Using the Sass API described in [Defining a theme](#defining-a-theme), you can also define _multiple_ themes by repeating the API calls multiple times. You can do this either in the same theme file or in separate theme files. #### Multiple themes in one file Defining multiple themes in a single file allows you to support multiple themes without having to manage loading of multiple CSS assets. The downside, however, is that your CSS will include more styles than necessary. To control which theme applies when, `@include` the mixins only within a context specified via CSS rule declaration. See the [documentation for Sass mixins][sass-mixins] for further background. [sass-mixins]: https://sass-lang.com/documentation/at-rules/mixin ```scss @use '@angular/material' as mat; // Define a dark theme $dark-theme: mat.define-theme(( color: ( theme-type: dark, primary: mat.$violet-palette, ), )); // Define a light theme $light-theme: mat.define-theme(( color: ( theme-type: light, primary: mat.$violet-palette, ), )); html { // Apply the dark theme by default @include mat.core-theme($dark-theme); @include mat.button-theme($dark-theme); // Apply the light theme only when the user prefers light themes. @media (prefers-color-scheme: light) { // Use the `-color` mixins to only apply color styles without reapplying the same // typography and density styles. @include mat.core-color($light-theme); @include mat.button-color($light-theme); } } ``` #### Multiple themes across separate files You can define multiple themes in separate files by creating multiple theme files per [Defining a theme](#defining-a-theme), adding each of the files to the `styles` of your `angular.json`. However, you must additionally set the `inject` option for each of these files to `false` in order to prevent all the theme files from being loaded at the same time. When setting this property to `false`, your application becomes responsible for manually loading the desired file. The approach for this loading depends on your application. ### Application background color By default, Angular Material does not apply any styles to your DOM outside its own components. If you want to set your application's background color to match the components' theme, you can either: 1. Put your application's main content inside `mat-sidenav-container`, assuming you're using `MatSidenav`, or 2. Apply the `mat-app-background` CSS class to your main content root element (typically `body`).
112811
### Granular customizations with CSS custom properties The CSS custom properties emitted by the theme mixins are derived from [M3's design tokens](https://m3.material.io/foundations/design-tokens/overview). To further customize your UI beyond the `define-theme` API, you can manually set these custom properties in your styles. The guarantees made by the theme mixins mean that you do not need to target internal selectors of components or use excessive specificity to override any of these tokenized properties. Always apply your base theme to your application's root element (typically `html` or `body`) and apply any overrides on the highest-level selector where they apply. <!-- TODO(mmalerba): Upgrade to embedded example --> ```html <mat-sidenav-container> Some content... <mat-sidenav> Some sidenav content... <mat-checkbox class="danger">Enable admin mode</mat-checkbox> </mat-sidenav> </mat-sidenav-container> ``` ```scss @use '@angular/material' as mat; $light-theme: mat.define-theme(); $dark-theme: mat.define-theme(( color: ( theme-type: dark ) )); html { // Apply the base theme at the root, so it will be inherited by the whole app. @include mat.all-component-themes($light-theme); } mat-sidenav { // Override the colors to create a dark sidenav. @include mat.all-component-colors($dark-theme); } .danger { // Override the checkbox hover state to indicate that this is a dangerous setting. No need to // target the internal selectors for the elements that use these variables. --mdc-checkbox-unselected-hover-state-layer-color: red; --mdc-checkbox-unselected-hover-icon-color: red; } ``` ## Customizing density Angular Material's density customization is based on the [Material Design density guidelines][material-density]. This system defines a scale where zero represents the default density. You can decrement the number for _more density_ and increment the number for _less density_. The density system is based on a *density scale*. The scale starts with the default density of `0`. Each whole number step down (`-1`, `-2`, etc.) reduces the affected sizes by `4dp`, down to the minimum size necessary for a component to render coherently. Components that appear in task-based or pop-up contexts, such as `MatDatepicker`, don't change their size via the density system. The [Material Design density guidance][material-density] explicitly discourages increasing density for such interactions because they don't compete for space in the application's layout. You can apply custom density setting to the entire library or to individual components using their density Sass mixins. ```scss // You can set a density setting in your theme to apply to all components. $dark-theme: mat.define-theme(( color: ..., typography: ..., density: ( scale: -2 ), )); // Or you can selectively apply the Sass mixin to affect only specific parts of your application. .the-dense-zone { @include mat.button-density(-1); } ``` [material-density]: https://m3.material.io/foundations/layout/understanding-layout/spacing ## Strong focus indicators By default, most components indicate browser focus by changing their background color as described by the Material Design specification. This behavior, however, can fall short of accessibility requirements, such as [WCAG][], which require a stronger indication of browser focus. Angular Material supports rendering highly visible outlines on focused elements. Applications can enable these strong focus indicators via two Sass mixins: `strong-focus-indicators` and `strong-focus-indicators-theme`. The `strong-focus-indicators` mixin emits structural indicator styles for all components. This mixin should be included exactly once in an application, similar to the `core` mixin described above. The `strong-focus-indicators-theme` mixin emits only the indicator's color styles. This mixin should be included once per theme, similar to the theme mixins described above. Additionally, you can use this mixin to change the color of the focus indicators in situations in which the default color would not contrast sufficiently with the background color. The following example includes strong focus indicator styles in an application alongside the rest of the custom theme API. ```scss @use '@angular/material' as mat; @include mat.strong-focus-indicators(); $my-theme: mat.define-theme(( color: ( theme-type: light, primary: mat.$violet-palette, ), )); html { @include mat.all-component-themes($my-theme); @include mat.strong-focus-indicators-theme($my-theme); } ``` ### Customizing strong focus indicators You can pass a configuration map to `strong-focus-indicators` to customize the appearance of the indicators. This configuration includes `border-style`, `border-width`, and `border-radius`. You also can customize the color of indicators with `strong-focus-indicators-theme`. This mixin accepts either a theme, as described earlier in this guide, or a CSS color value. When providing a theme, the indicators will use the default hue of the primary palette. The following example includes strong focus indicator styles with custom settings alongside the rest of the custom theme API. ```scss @use '@angular/material' as mat; @include mat.strong-focus-indicators(( border-style: dotted, border-width: 4px, border-radius: 2px, )); $my-theme: mat.define-theme(( color: ( theme-type: light, primary: mat.$violet-palette, ), )); html { @include mat.all-component-themes($my-theme); @include mat.strong-focus-indicators-theme(purple); } ``` [WCAG]: https://www.w3.org/WAI/standards-guidelines/wcag/glance/ ## Theming and style encapsulation Angular Material assumes that, by default, all theme styles are loaded as global CSS. If you want to use [Shadow DOM][shadow-dom] in your application, you must load the theme styles within each shadow root that contains an Angular Material component. You can accomplish this by manually loading the CSS in each shadow root, or by using [Constructable Stylesheets][constructable-css]. [shadow-dom]: https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM [constructable-css]: https://developers.google.com/web/updates/2019/02/constructable-stylesheets ## User preference media queries Angular Material does not apply styles based on user preference media queries, such as `prefers-color-scheme` or `prefers-contrast`. Instead, Angular Material's Sass mixins give you the flexibility to apply theme styles to based on the conditions that make the most sense for your users. This may mean using media queries directly or reading a saved user preference.
112814
# Theming Angular Material 2 ## What is theming? Angular Material's theming system lets you customize base, color, typography, and density styles for components in your application. The theming system is based on Google's [Material Design 2][material-design-theming] specification. **This guide refers to Material 2, the previous version of Material. For the latest Material 3 documentation, see the [theming guide][theming].** **For information on how to update, see the section on [how to migrate an app from Material 2 to Material 3](#how-to-migrate-an-app-from-material-2-to-material-3).** This document describes the concepts and APIs for customizing colors. For typography customization, see [Angular Material Typography][mat-typography]. For guidance on building components to be customizable with this system, see [Theming your own components][theme-your-own]. [material-design-theming]: https://m2.material.io/design/material-theming/overview.html [theming]: https://material.angular.io/guide/theming [mat-typography]: https://material.angular.io/guide/typography [theme-your-own]: https://material.angular.io/guide/theming-your-components ### Sass Angular Material's theming APIs are built with [Sass](https://sass-lang.com). This document assumes familiarity with CSS and Sass basics, including variables, functions, and mixins. You can use Angular Material without Sass by using a pre-built theme, described in [Using a pre-built theme](#using-a-pre-built-theme) below. However, using the library's Sass API directly gives you the most control over the styles in your application. ## Palettes A **palette** is a collection of colors representing a portion of color space. Each value in this collection is called a **hue**. In Material Design, each hues in a palette has an identifier number. These identifier numbers include 50, and then each 100 value between 100 and 900. The numbers order hues within a palette from lightest to darkest. Angular Material represents a palette as a [Sass map][sass-maps]. This map contains the palette's hues and another nested map of contrast colors for each of the hues. The contrast colors serve as text color when using a hue as a background color. The example below demonstrates the structure of a palette. [See the Material Design color system for more background.][spec-colors] ```scss $m2-indigo-palette: ( 50: #e8eaf6, 100: #c5cae9, 200: #9fa8da, 300: #7986cb, // ... continues to 900 contrast: ( 50: rgba(black, 0.87), 100: rgba(black, 0.87), 200: rgba(black, 0.87), 300: white, // ... continues to 900 ) ); ``` [sass-maps]: https://sass-lang.com/documentation/values/maps [spec-colors]: https://m2.material.io/design/color/the-color-system.html ### Create your own palette You can create your own palette by defining a Sass map that matches the structure described in the [Palettes](#palettes) section above. The map must define hues for 50 and each hundred between 100 and 900. The map must also define a `contrast` map with contrast colors for each hue. You can use [the Material Design palette tool][palette-tool] to help choose the hues in your palette. [palette-tool]: https://m2.material.io/design/color/the-color-system.html#tools-for-picking-colors ### Predefined palettes Angular Material offers predefined palettes based on the 2014 version of the Material Design spec. See the [Material Design 2014 color palettes][2014-palettes] for a full list. In addition to hues numbered from zero to 900, the 2014 Material Design palettes each include distinct _accent_ hues numbered as `A100`, `A200`, `A400`, and `A700`. Angular Material does not require these hues, but you can use these hues when defining a theme as described in [Defining a theme](#defining-a-theme) below. ```scss @use '@angular/material' as mat; $my-palette: mat.$m2-indigo-palette; ``` [2014-palettes]: https://material.io/archive/guidelines/style/color.html#color-color-palette
112815
## Themes A **theme** is a collection of color, typography, and density options. Each theme includes three palettes that determine component colors: * A **primary** palette for the color that appears most frequently throughout your application * An **accent**, or _secondary_, palette used to selectively highlight key parts of your UI * A **warn**, or _error_, palette used for warnings and error states You can include the CSS styles for a theme in your application in one of two ways: by defining a custom theme with Sass, or by importing a pre-built theme CSS file. ### Custom themes with Sass A **theme file** is a Sass file that calls Angular Material Sass mixins to output color, typography, and density CSS styles. #### Defining a theme Angular Material represents a theme as a Sass map that contains your color, typography, and density choices, as well as some base design system settings. See [Angular Material Typography][mat-typography] for an in-depth guide to customizing typography. See [Customizing density](#customizing-density) below for details on adjusting component density. Constructing the theme first requires defining your primary and accent palettes, with an optional warn palette. The `m2-define-palette` Sass function accepts a color palette, described in the [Palettes](#palettes) section above, as well as four optional hue numbers. These four hues represent, in order: the "default" hue, a "lighter" hue, a "darker" hue, and a "text" hue. Components use these hues to choose the most appropriate color for different parts of themselves. ```scss @use '@angular/material' as mat; $my-primary: mat.m2-define-palette(mat.$m2-indigo-palette, 500); $my-accent: mat.m2-define-palette(mat.$m2-pink-palette, A200, A100, A400); // The "warn" palette is optional and defaults to red if not specified. $my-warn: mat.m2-define-palette(mat.$m2-red-palette); ``` You can construct a theme by calling either `m2-define-light-theme` or `m2-define-dark-theme` with the result from `m2-define-palette`. The choice of a light versus a dark theme determines the background and foreground colors used throughout the components. ```scss @use '@angular/material' as mat; $my-primary: mat.m2-define-palette(mat.$m2-indigo-palette, 500); $my-accent: mat.m2-define-palette(mat.$m2-pink-palette, A200, A100, A400); // The "warn" palette is optional and defaults to red if not specified. $my-warn: mat.m2-define-palette(mat.$m2-red-palette); $my-theme: mat.m2-define-light-theme(( color: ( primary: $my-primary, accent: $my-accent, warn: $my-warn, ), typography: mat.m2-define-typography-config(), density: 0, )); ``` #### Applying a theme to components The `core-theme` Sass mixin emits prerequisite styles for common features used by multiple components, such as ripples. This mixin must be included once per theme. Each Angular Material component has a mixin for each [theming dimension](#theming-dimensions): base, color, typography, and density. For example, `MatButton` declares `button-base`, `button-color`, `button-typography`, and `button-density`. Each mixin emits only the styles corresponding to that dimension of customization. Additionally, each component has a "theme" mixin that emits all styles that depend on the theme config. This theme mixin only emits color, typography, or density styles if you provided a corresponding configuration to `m2-define-light-theme` or `m2-define-dark-theme`, and it always emits the base styles. Apply the styles for each of the components used in your application by including each of their theme Sass mixins. ```scss @use '@angular/material' as mat; $my-primary: mat.m2-define-palette(mat.$m2-indigo-palette, 500); $my-accent: mat.m2-define-palette(mat.$m2-pink-palette, A200, A100, A400); $my-theme: mat.m2-define-light-theme(( color: ( primary: $my-primary, accent: $my-accent, ), typography: mat.m2-define-typography-config(), density: 0, )); // Emit theme-dependent styles for common features used across multiple components. @include mat.core-theme($my-theme); // Emit styles for MatButton based on `$my-theme`. Because the configuration // passed to `m2-define-light-theme` omits typography, `button-theme` will not // emit any typography styles. @include mat.button-theme($my-theme); // Include the theme mixins for other components you use here. ``` As an alternative to listing every component that your application uses, Angular Material offers Sass mixins that includes styles for all components in the library: `all-component-bases`, `all-component-colors`, `all-component-typographies`, `all-component-densities`, and `all-component-themes`. These mixins behave the same as individual component mixins, except they emit styles for `core-theme` and _all_ 35+ components in Angular Material. Unless your application uses every single component, this will produce unnecessary CSS. ```scss @use '@angular/material' as mat; $my-primary: mat.m2-define-palette(mat.$m2-indigo-palette, 500); $my-accent: mat.m2-define-palette(mat.$m2-pink-palette, A200, A100, A400); $my-theme: mat.m2-define-light-theme(( color: ( primary: $my-primary, accent: $my-accent, ), typography: mat.m2-define-typography-config(), density: 0, )); @include mat.all-component-themes($my-theme); ``` To include the emitted styles in your application, [add your theme file to the `styles` array of your project's `angular.json` file][adding-styles]. [adding-styles]: https://angular.dev/reference/configs/workspace-config#styles-and-scripts-configuration #### Theming dimensions Angular Material themes are divided along four dimensions: base, color, typography, and density. ##### Base Common base styles for the design system. These styles don't change based on your configured colors, typography, or density, so they only need to be included once per application. These mixins include structural styles such as border-radius, border-width, etc. All components have a base mixin that can be used to include its base styles. (For example, `@include mat.checkbox-base($theme)`) ##### Color Styles related to the colors in your application. These style should be included at least once in your application. Depending on your needs, you may need to include these styles multiple times with different configurations. (For example, if your app supports light and dark theme colors.) All components have a color mixin that can be used to include its color styles. (For example, `@include mat.checkbox-color($theme)`) ##### Typography Styles related to the fonts used in your application, including the font family, size, weight, line-height, and letter-spacing. These style should be included at least once in your application. Depending on your needs, you may need to include these styles multiple times with different configurations. (For example, if your app supports reading content in either a serif or sans-serif font.) All components have a typography mixin that can be used to include its typography styles. (For example, `@include mat.checkbox-typography($theme)`) ##### Density Styles related to the size and spacing of elements in your application. These style should be included at least once in your application. Depending on your needs, you may need to include these styles multiple times with different configurations. (For example, if your app supports both a normal and compact mode). All components have a density mixin that can be used to include its density styles. (For example, `@include mat.checkbox-density($theme)`) ##### Theme mixin All components also support a theme mixin that can be used to include the component's styles for all theme dimensions at once. (For example, `@include mat.checkbox-theme($theme)`). The recommended approach is to rely on the `theme` mixins to lay down your base styles, and if needed use the single dimension mixins to override particular aspects for parts of your app (see the section on [Multiple themes in one file](#multiple-themes-in-one-file).)
112818
## Theming your components ### Reading values from a theme As described in this guide, a theme is a Sass map that contains style values to customize components. Angular Material provides APIs for reading values from this data structure. #### Reading color values To read color values from a theme, you can use the `get-theme-color` Sass function. This function supports reading colors for both the app color palettes (primary, accent, and warn), as well as the foreground and background palettes. `get-theme-color` takes three arguments: The theme to read from, the name of the palette, and the name of the color. Each of the color palettes (primary, accent, and warn) supports reading the following named colors: | Color Name | Description | |------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------| | default | The default color from this palette | | lighter | A lighter version of the color for this palette | | darker | A darker version of the color for this palette | | text | The text color for this palette | | default-contrast | A color that stands out against the this palette's default color | | lighter-contrast | A color that stands out against the this palette's lighter color | | darker-contrast | A color that stands out against the this palette's darker color | | [hue] | The [hue] color for the palette.<br />[hue] can be one of: 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, A100, A200, A400, A700 | | [hue]-contrast | A color that stands out against the [hue] color for the palette.<br />[hue] can be one of: 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, A100, A200, A400, A700 | The background palette supports reading the following named colors: | Color Name | Description | |--------------------------|----------------------------------------------------| | status-bar | The background color for a status bar | | app-bar | The background color for an app bar | | background | The background color for the app | | hover | The background color of a hover overlay | | card | The background color of a card | | dialog | The background color of a dialog | | raised-button | The background color of a raised button | | selected-button | The background color of a selected button | | selected-disabled-button | The background color of a selected disabled button | | disabled-button | The background color of a disabled button | | focused-button | The background color of a focused button | | disabled-button-toggle | The background color of a disabled button toggle | | unselected-chip | The background color of an unselected chip | | disabled-list-option | The background color of a disabled list option | | tooltip | The background color of a tooltip | The foreground palette supports reading the following named colors: | Color name | Description | |-------------------|----------------------------------------------------------------------------------------------------------| | base | The base foreground color, can be used to for color mixing or creating a custom opacity foreground color | | divider | The color of a divider | | dividers | (Alternate name for divider) | | disabled-text | The color for disabled text | | disabled | (Alternate name for disabled-text) | | disabled-button | The color for disabled button text | | elevation | The color elevation shadows | | hint-text | The color for hint text | | secondary-text | The color for secondary text | | icon | The color for icons | | icons | (Alternate name for icon) | | text | The color for text | | In addition to reading particular colors, you can use the `get-theme-type` Sass function to determine the type of theme (either light or dark). This function takes a single argument, the theme, and returns either `light` or `dark`. See the below example of reading some colors from a theme: ```scss $theme: mat.m2-define-dark-theme(...); $primary-default: mat.get-theme-color($theme, primary, default); $accent-a100: mat.get-theme-color($theme, accent, A100); $warn-500-contrast: mat.get-theme-color($theme, warn, 500-contrast); $foreground-text: mat.get-theme-color($theme, foreground, text); $background-card: mat.get-theme-color($theme, background, card); $type: mat.get-theme-type($theme); $custom-background: if($type == dark, #030, #dfd); ``` #### Reading typography values To read typography values from a theme, you can use the `get-theme-typography` Sass function. This function supports reading typography properties from the typography levels defined in the theme. There are two ways to call the function. The first way to call it is by passing just the theme and the typography level to get a shorthand `font` property based on the settings for that level. (Note: `letter-spacing` cannot be expressed in the `font` shorthand, so it must be applied separately). The second way to call it is by passing the theme, typography level, and the specific font property you want: `font-family`, `font-size`, `font-weight`, `line-height`, or `letter-spacing`. The available typography levels are: | Name | Description | |------------|----------------------------------------------------------------------| | headline-1 | One-off header, usually at the top of the page (e.g. a hero header). | | headline-2 | One-off header, usually at the top of the page (e.g. a hero header). | | headline-3 | One-off header, usually at the top of the page (e.g. a hero header). | | headline-4 | One-off header, usually at the top of the page (e.g. a hero header). | | headline-5 | Section heading corresponding to the `<h1>` tag. | | headline-6 | Section heading corresponding to the `<h2>` tag. | | subtitle-1 | Section heading corresponding to the `<h3>` tag. | | subtitle-2 | Section heading corresponding to the `<h4>` tag. | | body-1 | Base body text. | | body-2 | Secondary body text. | | caption | Smaller body and hint text. | | button | Buttons and anchors. | See the below example of reading some typography settings from a theme: ```scss $theme: mat.m2-define-dark-theme(...); body { font: mat.get-theme-typography($theme, body-1); letter-spacing: mat.get-theme-typography($theme, body-1, letter-spacing); } ``` #### Reading density values To read the density scale from a theme, you can use the `get-theme-density` Sass function. This function takes a theme and returns the density scale (0, -1, -2, -3, -4, or -5). See the below example of reading the density scale from a theme: ```scss $theme: mat.m2-define-dark-theme(...); $density-scale: mat.get-theme-density($theme); ``` ### Checking what dimensions are configured for a theme Depending on how a theme was created, it may not have configuration data for all theming dimensions (base, color, typography, density). You can check if a theme has a configuration for a particular dimension by calling the `theme-has` Sass function, passing the theme and the dimension to check. See the below example of checking the configured dimensions for a theme: ```scss $theme: mat.m2-define-dark-theme(...); $has-base: mat.theme-has($theme, base); $has-color: mat.theme-has($theme, color); $has-typography: mat.theme-has($theme, typography); $has-density: mat.theme-has($theme, density); ``` ### Separating theme styles Angular Material components each have a Sass file that defines mixins for customizing that component's color and typography. For example, `MatButton` has mixins for `button-color` and `button-typography`. Each mixin emits all color and typography styles for that component, respectively. You can mirror this structure in your components by defining your own mixins. These mixins should accept an Angular Material theme, from which they can read color and typography values. You can then include these mixins in your application along with Angular Material's own mixins.
112821
## How to migrate an app from Material 2 to Material 3 Angular Material does not offer an automated migration from M2 to M3 because the design of your app is subjective. Material Design offers general principles and constraints to guide you, but ultimately it is up to you to decide how to apply those in your app. That said, Angular Material's M3 themes were designed with maximum compatibility in mind. ### Update your components that use Angular Material themes to be compatible with Material 3 In order to facilitate a smooth transition from M2 to M3, it may make sense to have your components support both M2 and M3 themes. Once the entire app is migrated, the support for M2 themes can be removed. The simplest way to accomplish this is by checking the theme version and emitting different styles for M2 vs M3. You can check the theme version using the `get-theme-version` function from `@angular/material`. The function will return `0` for an M2 theme or `1` for an M3 theme (see [theme your own components using a Material 3 theme](https://material.angular.io/guide/theming#theme-your-own-components-using-a-material-3-theme) for how to read values from an M3 theme). ```scss @use '@angular/material' as mat; @mixin my-comp-theme($theme) { @if (mat.get-theme-version($theme) == 1) { // Add your new M3 styles here. } @else { // Keep your old M2 styles here. } } ``` ### Pass a new M3 theme in your global theme styles Create a new M3 theme object using `define-theme` and pass it everywhere you were previously passing your M2 theme. All Angular Material mixins that take an M2 theme are compatible with M3 themes as well. ### Update usages of APIs that are not supported for Material 3 themes Because Material 3 is implemented as an alternate theme for the same components used for Material 2, the APIs for both are largely the same. However, there are a few differences to be aware of: - M3 expects that any `@include` of the `-theme`, `-color`, `-typography`, `-density`, or `-base` mixins should be wrapped in a selector. If your app includes such an `@include` at the root level, we recommend wrapping it in `html { ... }` - M3 has a different API for setting the color variant of a component (see [using component color variants](https://material.angular.io/guide/theming#using-component-color-variants) for more). - The `backgroundColor` property of `<mat-tab-group>` is not supported, and should not be used with M3 themes. - The `appearance="legacy"` variant of `<mat-button-toggle>` is not supported, and should not be used with M3 themes. - For M3 themes, calling `all-component-typographies` does _not_ emit the `typography-hierarchy` styles, as this would violate M3's guarantee to not add selectors. Instead, the `typography-hierarchy` mixin must be explicitly called if you want these styles in your app. - The `typography-hierarchy` mixin outputs CSS class names that correspond to the names of M3 typescale levels rather than M2 typescale levels. If you were relying on the M2 classes to style your app, you may need to update the class names. ### (Optional) add backwards compatibility styles for color variants We recommend _not_ relying on the `color="primary"`, `color="accent"`, or `color="warn"` options that are offered by a number of Angular Material components for M2 themes. However, if you want to quickly update to M3 and are willing to accept the extra CSS generated for these variants, you can enable backwards compatibility styles that restore the behavior of this API. Call the `color-variants-backwards-compatibility` mixin from `@angular/material` with the M3 theme you want to generate color variant styles for. <!-- TODO(mmalerba): Upgrade to embedded example --> ```scss @use '@angular/material' as mat; $theme: mat.define-theme(); html { @include mat.all-component-themes($theme); @include mat.color-variants-backwards-compatibility($theme); } ``` ### (Optional) add backwards compatibility styles for typography hierarchy Calling the `typography-hierarchy` mixin with an M3 theme generates styles for CSS classes that match the names of M3 typescale names (e.g. `.mat-headline-large`) rather than ones that match M2 typescale names (`.mat-headline-1`). If you were using the M2 class names in your app we recommend updating all usages to one of the new class names. However, to make migration easier, the `typography-hierarchy` mixin does support emitting the old class names in addition to the new ones. We have made a best effort to map the M2 classes to reasonable equivalents in M3. To enable these styles, pass an additional argument `$back-compat: true` to the mixin. <!-- TODO(mmalerba): Upgrade to embedded example --> ```scss @use '@angular/material' as mat; $theme: mat.define-theme(); @include mat.typography-hierarchy($theme, $back-compat: true); ```
112826
### Implementing the methods and properties of MatFormFieldControl #### `value` This property allows someone to set or get the value of our control. Its type should be the same type we used for the type parameter when we implemented `MatFormFieldControl`. Since our component already has a value property, we don't need to do anything for this one. #### `stateChanges` Because the `<mat-form-field>` uses the `OnPush` change detection strategy, we need to let it know when something happens in the form field control that may require the form field to run change detection. We do this via the `stateChanges` property. So far the only thing the form field needs to know about is when the value changes. We'll need to emit on the stateChanges stream when that happens, and as we continue flushing out these properties we'll likely find more places we need to emit. We should also make sure to complete `stateChanges` when our component is destroyed. ```ts stateChanges = new Subject<void>(); set value(tel: MyTel | null) { ... this.stateChanges.next(); } ngOnDestroy() { this.stateChanges.complete(); } ``` #### `id` This property should return the ID of an element in the component's template that we want the `<mat-form-field>` to associate all of its labels and hints with. In this case, we'll use the host element and just generate a unique ID for it. ```ts static nextId = 0; @HostBinding() id = `example-tel-input-${MyTelInput.nextId++}`; ``` #### `placeholder` This property allows us to tell the `<mat-form-field>` what to use as a placeholder. In this example, we'll do the same thing as `matInput` and `<mat-select>` and allow the user to specify it via an `@Input()`. Since the value of the placeholder may change over time, we need to make sure to trigger change detection in the parent form field by emitting on the `stateChanges` stream when the placeholder changes. ```ts @Input() get placeholder() { return this._placeholder; } set placeholder(plh) { this._placeholder = plh; this.stateChanges.next(); } private _placeholder: string; ``` #### `ngControl` This property allows the form field control to specify the `@angular/forms` control that is bound to this component. Since we haven't set up our component to act as a `ControlValueAccessor`, we'll just set this to `null` in our component. ```ts ngControl: NgControl = null; ``` It is likely you will want to implement `ControlValueAccessor` so that your component can work with `formControl` and `ngModel`. If you do implement `ControlValueAccessor` you will need to get a reference to the `NgControl` associated with your control and make it publicly available. The easy way is to add it as a public property to your constructor and let dependency injection handle it: ```ts constructor( ..., @Optional() @Self() public ngControl: NgControl, ..., ) { } ``` Note that if your component implements `ControlValueAccessor`, it may already be set up to provide `NG_VALUE_ACCESSOR` (in the `providers` part of the component's decorator, or possibly in a module declaration). If so, you may get a *cannot instantiate cyclic dependency* error. To resolve this, remove the `NG_VALUE_ACCESSOR` provider and instead set the value accessor directly: ```ts @Component({ ..., providers: [ ..., // Remove this. // { // provide: NG_VALUE_ACCESSOR, // useExisting: forwardRef(() => MatFormFieldControl), // multi: true, // }, ], }) export class MyTelInput implements MatFormFieldControl<MyTel>, ControlValueAccessor { constructor( ..., @Optional() @Self() public ngControl: NgControl, ..., ) { // Replace the provider from above with this. if (this.ngControl != null) { // Setting the value accessor directly (instead of using // the providers) to avoid running into a circular import. this.ngControl.valueAccessor = this; } } } ``` For additional information about `ControlValueAccessor` see the [API docs](https://angular.dev/api/forms/ControlValueAccessor). #### `focused` This property indicates whether the form field control should be considered to be in a focused state. When it is in a focused state, the form field is displayed with a solid color underline. For the purposes of our component, we want to consider it focused if any of the part inputs are focused. We can use the `focusin` and `focusout` events to easily check this. We also need to remember to emit on the `stateChanges` when the focused stated changes stream so change detection can happen. In addition to updating the focused state, we use the `focusin` and `focusout` methods to update the internal touched state of our component, which we'll use to determine the error state. ```ts focused = false; onFocusIn(event: FocusEvent) { if (!this.focused) { this.focused = true; this.stateChanges.next(); } } onFocusOut(event: FocusEvent) { if (!this._elementRef.nativeElement.contains(event.relatedTarget as Element)) { this.touched = true; this.focused = false; this.onTouched(); this.stateChanges.next(); } } ``` #### `empty` This property indicates whether the form field control is empty. For our control, we'll consider it empty if all the parts are empty. ```ts get empty() { let n = this.parts.value; return !n.area && !n.exchange && !n.subscriber; } ``` #### `shouldLabelFloat` This property is used to indicate whether the label should be in the floating position. We'll use the same logic as `matInput` and float the placeholder when the input is focused or non-empty. Since the placeholder will be overlapping our control when it's not floating, we should hide the `–` characters when it's not floating. ```ts @HostBinding('class.floating') get shouldLabelFloat() { return this.focused || !this.empty; } ``` ```css span { opacity: 0; transition: opacity 200ms; } :host.floating span { opacity: 1; } ``` #### `required` This property is used to indicate whether the input is required. `<mat-form-field>` uses this information to add a required indicator to the placeholder. Again, we'll want to make sure we run change detection if the required state changes. ```ts @Input() get required() { return this._required; } set required(req: BooleanInput) { this._required = coerceBooleanProperty(req); this.stateChanges.next(); } private _required = false; ``` #### `disabled` This property tells the form field when it should be in the disabled state. In addition to reporting the right state to the form field, we need to set the disabled state on the individual inputs that make up our component. ```ts @Input() get disabled(): boolean { return this._disabled; } set disabled(value: BooleanInput) { this._disabled = coerceBooleanProperty(value); this._disabled ? this.parts.disable() : this.parts.enable(); this.stateChanges.next(); } private _disabled = false; ``` #### `errorState` This property indicates whether the associated `NgControl` is in an error state. For example, we can show an error if the input is invalid and our component has been touched. ```ts get errorState(): boolean { return this.parts.invalid && this.touched; } ``` However, there are some error triggers that we can't subscribe to (e.g. parent form submissions), to handle such cases we should re-evaluate `errorState` on every change detection cycle. ```ts /** Whether the component is in an error state. */ errorState: boolean = false; constructor( ..., @Optional() private _parentForm: NgForm, @Optional() private _parentFormGroup: FormGroupDirective ) { ... } ngDoCheck() { if (this.ngControl) { this.updateErrorState(); } } private updateErrorState() { const parent = this._parentFormGroup || this.parentForm; const oldState = this.errorState; const newState = (this.ngControl?.invalid || this.parts.invalid) && (this.touched || parent.submitted); if (oldState !== newState) { this.errorState = newState; this.stateChanges.next(); } } ``` Keep in mind that `updateErrorState()` must have minimal logic to avoid performance issues. ##
112987
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {inject, Injectable, PLATFORM_ID} from '@angular/core'; import {isPlatformBrowser} from '@angular/common'; // Whether the current platform supports the V8 Break Iterator. The V8 check // is necessary to detect all Blink based browsers. let hasV8BreakIterator: boolean; // We need a try/catch around the reference to `Intl`, because accessing it in some cases can // cause IE to throw. These cases are tied to particular versions of Windows and can happen if // the consumer is providing a polyfilled `Map`. See: // https://github.com/Microsoft/ChakraCore/issues/3189 // https://github.com/angular/components/issues/15687 try { hasV8BreakIterator = typeof Intl !== 'undefined' && (Intl as any).v8BreakIterator; } catch { hasV8BreakIterator = false; } /** * Service to detect the current platform by comparing the userAgent strings and * checking browser-specific global properties. */ @Injectable({providedIn: 'root'}) export class Platform { private _platformId = inject(PLATFORM_ID); // We want to use the Angular platform check because if the Document is shimmed // without the navigator, the following checks will fail. This is preferred because // sometimes the Document may be shimmed without the user's knowledge or intention /** Whether the Angular application is being rendered in the browser. */ isBrowser: boolean = this._platformId ? isPlatformBrowser(this._platformId) : typeof document === 'object' && !!document; /** Whether the current browser is Microsoft Edge. */ EDGE: boolean = this.isBrowser && /(edge)/i.test(navigator.userAgent); /** Whether the current rendering engine is Microsoft Trident. */ TRIDENT: boolean = this.isBrowser && /(msie|trident)/i.test(navigator.userAgent); // EdgeHTML and Trident mock Blink specific things and need to be excluded from this check. /** Whether the current rendering engine is Blink. */ BLINK: boolean = this.isBrowser && !!((window as any).chrome || hasV8BreakIterator) && typeof CSS !== 'undefined' && !this.EDGE && !this.TRIDENT; // Webkit is part of the userAgent in EdgeHTML, Blink and Trident. Therefore we need to // ensure that Webkit runs standalone and is not used as another engine's base. /** Whether the current rendering engine is WebKit. */ WEBKIT: boolean = this.isBrowser && /AppleWebKit/i.test(navigator.userAgent) && !this.BLINK && !this.EDGE && !this.TRIDENT; /** Whether the current platform is Apple iOS. */ IOS: boolean = this.isBrowser && /iPad|iPhone|iPod/.test(navigator.userAgent) && !('MSStream' in window); // It's difficult to detect the plain Gecko engine, because most of the browsers identify // them self as Gecko-like browsers and modify the userAgent's according to that. // Since we only cover one explicit Firefox case, we can simply check for Firefox // instead of having an unstable check for Gecko. /** Whether the current browser is Firefox. */ FIREFOX: boolean = this.isBrowser && /(firefox|minefield)/i.test(navigator.userAgent); /** Whether the current platform is Android. */ // Trident on mobile adds the android platform to the userAgent to trick detections. ANDROID: boolean = this.isBrowser && /android/i.test(navigator.userAgent) && !this.TRIDENT; // Safari browsers will include the Safari keyword in their userAgent. Some browsers may fake // this and just place the Safari keyword in the userAgent. To be more safe about Safari every // Safari browser should also use Webkit as its layout engine. /** Whether the current browser is Safari. */ SAFARI: boolean = this.isBrowser && /safari/i.test(navigator.userAgent) && this.WEBKIT; /** Backwards-compatible constructor. */ constructor(..._args: unknown[]); constructor() {} }
113233
The `@angular/cdk/menu` module provides directives to help create custom menu interactions based on the [WAI ARIA specification][aria]. By using `@angular/cdk/menu` you get all of the expected behaviors for an accessible experience, including bidi layout support, keyboard interaction, and focus management. All directives apply their associated ARIA roles to their host element. ### Supported ARIA Roles The directives in `@angular/cdk/menu` set the appropriate roles on their host element. | Directive | ARIA Role | |---------------------|------------------| | CdkMenuBar | menubar | | CdkMenu | menu | | CdkMenuGroup | group | | CdkMenuItem | menuitem | | CdkMenuItemRadio | menuitemradio | | CdkMenuItemCheckbox | menuitemcheckbox | | CdkMenuTrigger | button | ### CSS Styles and Classes The `@angular/cdk/menu` is designed to be highly customizable to your needs. It therefore does not make any assumptions about how elements should be styled. You are expected to apply any required CSS styles, but the directives do apply CSS classes to make it easier for you to add custom styles. The available CSS classes are listed below, by directive. | Directive | CSS Class | Applied... | |:----------------------|--------------------------|------------------------------------------------| | `cdkMenu` | `cdk-menu` | Always | | `cdkMenu` | `cdk-menu-inline` | If the menu is an [inline menu](#menu-content) | | `cdkMenuBar` | `cdk-menu-bar` | Always | | `cdkMenuGroup` | `cdk-menu-group` | Always | | `cdkMenuItem` | `cdk-menu-item` | Always | | `cdkMenuItemCheckbox` | `cdk-menu-item` | Always | | `cdkMenuItemCheckbox` | `cdk-menu-item-checkbox` | Always | | `cdkMenuItemRadio` | `cdk-menu-item` | Always | | `cdkMenuItemRadio` | `cdk-menu-item-radio` | Always | | `cdkMenuTriggerFor` | `cdk-menu-trigger` | Always | ### Getting started Import the `CdkMenuModule` into the `NgModule` in which you want to create menus. You can then apply menu directives to build your custom menu. A typical menu consists of the following directives: - `cdkMenuTriggerFor` - links a trigger element to an `ng-template` containing the menu to be opened - `cdkMenu` - creates the menu content opened by the trigger - `cdkMenuItem` - added to each item in the menu <!-- example({ "example": "cdk-menu-standalone-menu", "file": "cdk-menu-standalone-menu-example.html" }) --> Most menu interactions consist of two parts: a trigger and a menu panel. #### Triggers You can add `cdkMenuTriggerFor` to any button to make it a trigger for the given menu, or any menu item to make it a trigger for a submenu. When adding this directive, be sure to pass a reference to the template containing the menu it should open. Users can toggle the associated menu using a mouse or keyboard. <!-- example({"example":"cdk-menu-standalone-menu", "file":"cdk-menu-standalone-menu-example.html", "region":"trigger"}) --> When creating a submenu trigger, add both `cdkMenuItem` and `cdkMenuTriggerFor` like so, <!-- example({"example":"cdk-menu-menubar", "file":"cdk-menu-menubar-example.html", "region":"file-trigger"}) --> #### Menu content There are two types of menus: * _inline menus_ are always present on the page * _pop-up menus_ can be toggled to hide or show by the user You can create menus by marking their content element with the `cdkMenu` or `cdkMenuBar` directives. You can create several types of menu interaction which are discussed below. All type of menus should exclusively contain elements with role `menuitem`, `menuitemcheckbox`, `menuitemradio`, or `group`. Supporting directives that automatically apply these roles are discussed below. Note that Angular CDK provides no styles; you must add styles as part of building your custom menu. ### Inline Menus An _inline menu_ is a menu that lives directly on the page rather than in a pop-up associated with a trigger. You can use an inline menu when you want a persistent menu interaction on a page. Menu items within an inline menus are logically grouped together, and you can navigate through them using your keyboard. You can create an inline menu by adding the `cdkMenu` directive to the element you want to serve as the menu content. <!-- example({ "example": "cdk-menu-inline", "file": "cdk-menu-inline-example.html" }) --> ### Pop-up Menus You can create pop-up menus using the `cdkMenu` directive as well. Add this directive to the element you want to serve as the content for your pop-up menu. Then wrap the content element in an `ng-template` and reference the template from the `cdkMenuTriggerFor` property of the trigger. This will allow the trigger to show and hide the menu content as needed. <!-- example({ "example": "cdk-menu-standalone-menu", "file": "cdk-menu-standalone-menu-example.html" }) --> ### Menu Bars Menu bars are a type of inline menu that you can create using the `cdkMenuBar` directive. They follow the [ARIA menubar][menubar] spec and behave similarly to a desktop application menubar. Each bar consists of at least one `cdkMenuItem` that triggers a submenu. <!-- example({ "example": "cdk-menu-menubar", "file": "cdk-menu-menubar-example.html" }) --> ### Context Menus A context menus is a type of pop-up menu that doesn't have a traditional trigger element, instead it is triggered when a user right-clicks within some container element. You can mark a container element with the `cdkContextMenuTriggerFor`, which behaves like `cdkMenuTriggerFor` except that it responds to the browser's native `contextmenu` event. Custom context menus appear next to the cursor, similarly to native context menus. <!-- example({ "example": "cdk-menu-context", "file": "cdk-menu-context-example.html" }) --> You can nest context menu container elements. Upon right-click, the menu associated with the closest container element will open. <!-- example({ "example": "cdk-menu-nested-context", "file": "cdk-menu-nested-context-example.html", "region": "triggers" }) --> In the example above, right-clicking on "Inner context menu" will open up the "inner" menu and right-clicking inside "Outer context menu" will open up the "outer" menu.
113234
### Menu Items The `cdkMenuItem` directive allows users to navigate menu items via keyboard. You can add a custom action to a menu item with the `cdkMenuItemTriggered` output. <!-- example({"example":"cdk-menu-standalone-stateful-menu", "file":"cdk-menu-standalone-stateful-menu-example.html", "region":"reset-item"}) --> You can create nested menus by using a menu item as the trigger for another menu. <!-- example({"example":"cdk-menu-menubar", "file":"cdk-menu-menubar-example.html", "region":"file-trigger"}) --> #### Menu Item Checkboxes A `cdkMenuItemCheckbox` is a special type of menu item that behaves as a checkbox. You can use this type of menu item to toggle items on and off. An element with the `cdkMenuItemCheckbox` directive does not need the additional `cdkMenuItem` directive. Checkbox items do not track their own state. You must bind the checked state using the `cdkMenuItemChecked` input and listen to `cdkMenuItemTriggered` to know when it is toggled. If you don't bind the state it will reset when the menu is closed and re-opened. <!-- example({"example":"cdk-menu-standalone-stateful-menu", "file":"cdk-menu-standalone-stateful-menu-example.html", "region":"bold-item"}) --> #### Menu Item Radios A `cdkMenuItemRadio` is a special type of menu item that behaves as a radio button. You can use this type of menu item for menus with exclusively selectable items. An element with the `cdkMenuItemRadio` directive does not need the additional `cdkMenuItem` directive. As with checkbox items, radio items do not track their own state, but you can track it by binding `cdkMenuItemChecked` and listening for `cdkMenuItemTriggered`. If you do not bind the state the selection will reset when the menu is closed and reopened. <!-- example({"example":"cdk-menu-standalone-stateful-menu", "file":"cdk-menu-standalone-stateful-menu-example.html", "region":"size-items"}) --> #### Groups By default `cdkMenu` acts as a group for `cdkMenuItemRadio` elements. Elements with `cdkMenuItemRadio` added as children of a `cdkMenu` will be logically grouped and only a single item can have the checked state. If you would like to have unrelated groups of radio buttons within a single menu you should use the `cdkMenuGroup` directive. <!-- example({ "example": "cdk-menu-standalone-stateful-menu", "file": "cdk-menu-standalone-stateful-menu-example.html" }) --> ### Smart Menu Aim `@angular/cdk/menu` is capable of intelligently predicting when a user intends to navigate to an open submenu and preventing premature closeouts. This functionality prevents users from having to hunt through the open menus in a maze-like fashion to reach their destination. To enable this feature for a menu and its sub-menus, add the `cdkTargetMenuAim` directive to the `cdkMenu` or `cdkMenuBar` element. ![menu aim diagram][diagram] As demonstrated in the diagram above we first track the user's mouse movements within a menu. Next, when a user mouses into a sibling menu item (e.g. Share button) the sibling item asks the Menu Aim service if it can perform its close actions. In order to determine if the current submenu can be closed out, the Menu Aim service calculates the slope between a selected target coordinate in the submenu and the previous mouse point, and the slope between the target and the current mouse point. If the slope of the current mouse point is greater than the slope of the previous that means the user is moving towards the submenu, so we shouldn't close out. Users however may sometimes stop short in a sibling item after moving towards the submenu. The service is intelligent enough to detect this intention and will trigger the next menu. ### Accessibility The set of directives defined in `@angular/cdk/menu` follow accessibility best practices as defined in the [ARIA spec][menubar]. Specifically, the menus are aware of left-to-right and right-to-left layouts and opened appropriately. You should however add any necessary CSS styles. Menu items should always have meaningful labels, whether through text content, `aria-label`, or `aria-labelledby`. Finally, keyboard interaction is supported as defined in the [ARIA menubar keyboard interaction spec][keyboard]. <!-- links --> [aria]: https://www.w3.org/TR/wai-aria-1.1/ 'ARIA Spec' [menubar]: https://www.w3.org/TR/wai-aria-practices-1.1/#menu 'ARIA Menubar Pattern' [keyboard]: https://www.w3.org/TR/wai-aria-practices-1.1/#keyboard-interaction-12 'ARIA Menubar Keyboard Interaction' [diagram]: https://material.angular.io/assets/img/menuaim.png 'Menu Aim Diagram'
113497
import {Component, ElementRef, ViewChild} from '@angular/core'; import { ComponentFixture, TestBed, fakeAsync, inject, tick, waitForAsync, } from '@angular/core/testing'; import {ContentObserver, MutationObserverFactory, ObserversModule} from './observe-content'; describe('Observe content directive', () => { describe('basic usage', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ObserversModule, ComponentWithTextContent, ComponentWithChildTextContent], }); })); it('should trigger the callback when the content of the element changes', done => { let fixture = TestBed.createComponent(ComponentWithTextContent); fixture.detectChanges(); // If the hint label is empty, expect no label. const spy = spyOn(fixture.componentInstance, 'doSomething').and.callFake(() => { expect(spy).toHaveBeenCalled(); done(); }); expect(spy).not.toHaveBeenCalled(); fixture.componentInstance.text = 'text'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }); it('should trigger the callback when the content of the children changes', done => { let fixture = TestBed.createComponent(ComponentWithChildTextContent); fixture.detectChanges(); // If the hint label is empty, expect no label. const spy = spyOn(fixture.componentInstance, 'doSomething').and.callFake(() => { expect(spy).toHaveBeenCalled(); done(); }); expect(spy).not.toHaveBeenCalled(); fixture.componentInstance.text = 'text'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }); it('should disconnect the MutationObserver when the directive is disabled', () => { const observeSpy = jasmine.createSpy('observe spy'); const disconnectSpy = jasmine.createSpy('disconnect spy'); // Note: since we can't know exactly when the native MutationObserver will emit, we can't // test this scenario reliably without risking flaky tests, which is why we supply a mock // MutationObserver and check that the methods are called at the right time. TestBed.overrideProvider(MutationObserverFactory, { deps: [], useFactory: () => ({ create: () => ({observe: observeSpy, disconnect: disconnectSpy}), }), }); const fixture = TestBed.createComponent(ComponentWithTextContent); fixture.detectChanges(); expect(observeSpy).toHaveBeenCalledTimes(1); expect(disconnectSpy).not.toHaveBeenCalled(); fixture.componentInstance.disabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(observeSpy).toHaveBeenCalledTimes(1); expect(disconnectSpy).toHaveBeenCalledTimes(1); }); }); describe('debounced', () => { let fixture: ComponentFixture<ComponentWithDebouncedListener>; let callbacks: Function[]; let invokeCallbacks = (args?: any) => callbacks.forEach(callback => callback(args)); beforeEach(waitForAsync(() => { callbacks = []; TestBed.configureTestingModule({ imports: [ObserversModule, ComponentWithDebouncedListener], providers: [ { provide: MutationObserverFactory, useValue: { create: function (callback: Function) { callbacks.push(callback); return { observe: () => {}, disconnect: () => {}, }; }, }, }, ], }); fixture = TestBed.createComponent(ComponentWithDebouncedListener); fixture.detectChanges(); })); it('should debounce the content changes', fakeAsync(() => { invokeCallbacks([{type: 'fake'}]); invokeCallbacks([{type: 'fake'}]); invokeCallbacks([{type: 'fake'}]); tick(500); expect(fixture.componentInstance.spy).toHaveBeenCalledTimes(1); })); }); }); describe('ContentObserver injectable', () => { describe('basic usage', () => { let callbacks: Function[]; let invokeCallbacks = (args?: any) => callbacks.forEach(callback => callback(args)); let contentObserver: ContentObserver; beforeEach(fakeAsync(() => { callbacks = []; TestBed.configureTestingModule({ imports: [ObserversModule, UnobservedComponentWithTextContent], providers: [ { provide: MutationObserverFactory, useValue: { create: function (callback: Function) { callbacks.push(callback); return { observe: () => {}, disconnect: () => {}, }; }, }, }, ], }); })); beforeEach(inject([ContentObserver], (co: ContentObserver) => { contentObserver = co; })); it('should trigger the callback when the content of the element changes', fakeAsync(() => { const spy = jasmine.createSpy('content observer'); const fixture = TestBed.createComponent(UnobservedComponentWithTextContent); fixture.detectChanges(); contentObserver.observe(fixture.componentInstance.contentEl).subscribe(() => spy()); expect(spy).not.toHaveBeenCalled(); fixture.componentInstance.text = 'text'; invokeCallbacks([{type: 'fake'}]); expect(spy).toHaveBeenCalled(); })); it('should only create one MutationObserver when observing the same element twice', fakeAsync( inject([MutationObserverFactory], (mof: MutationObserverFactory) => { const spy = jasmine.createSpy('content observer'); spyOn(mof, 'create').and.callThrough(); const fixture = TestBed.createComponent(UnobservedComponentWithTextContent); fixture.detectChanges(); const sub1 = contentObserver .observe(fixture.componentInstance.contentEl) .subscribe(() => spy()); contentObserver.observe(fixture.componentInstance.contentEl).subscribe(() => spy()); expect(mof.create).toHaveBeenCalledTimes(1); fixture.componentInstance.text = 'text'; invokeCallbacks([{type: 'fake'}]); expect(spy).toHaveBeenCalledTimes(2); spy.calls.reset(); sub1.unsubscribe(); fixture.componentInstance.text = 'text text'; invokeCallbacks([{type: 'fake'}]); expect(spy).toHaveBeenCalledTimes(1); }), )); }); describe('real behavior', () => { let spy: jasmine.Spy; let contentEl: HTMLElement; let contentObserver: ContentObserver; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ObserversModule, UnobservedComponentWithTextContent], }); const fixture = TestBed.createComponent(UnobservedComponentWithTextContent); fixture.autoDetectChanges(); spy = jasmine.createSpy('content observer'); contentObserver = TestBed.inject(ContentObserver); contentEl = fixture.componentInstance.contentEl.nativeElement; contentObserver.observe(contentEl).subscribe(spy); })); it('should ignore addition or removal of comments', waitForAsync(async () => { const comment = document.createComment('cool'); await new Promise(r => setTimeout(r)); spy.calls.reset(); contentEl.appendChild(comment); await new Promise(r => setTimeout(r)); expect(spy).not.toHaveBeenCalled(); comment.remove(); await new Promise(r => setTimeout(r)); expect(spy).not.toHaveBeenCalled(); })); it('should not ignore addition or removal of text', waitForAsync(async () => { const text = document.createTextNode('cool'); await new Promise(r => setTimeout(r)); spy.calls.reset(); contentEl.appendChild(text); await new Promise(r => setTimeout(r)); expect(spy).toHaveBeenCalled(); spy.calls.reset(); text.remove(); await new Promise(r => setTimeout(r)); expect(spy).toHaveBeenCalled(); })); it('should ignore comment content change', waitForAsync(async () => { const comment = document.createComment('cool'); contentEl.appendChild(comment); await new Promise(r => setTimeout(r)); spy.calls.reset(); comment.textContent = 'beans'; await new Promise(r => setTimeout(r)); expect(spy).not.toHaveBeenCalled(); })); it('should not ignore text content change', waitForAsync(async () => { const text = document.createTextNode('cool'); contentEl.appendChild(text); await new Promise(r => setTimeout(r)); spy.calls.reset(); text.textContent = 'beans'; await new Promise(r => setTimeout(r)); expect(spy).toHaveBeenCalled(); })); }); }); @Component({ template: ` <div (cdkObserveContent)="doSomething()" [cdkObserveContentDisabled]="disabled">{{text}}</div> `, standalone: true, imports: [ObserversModule], }) class ComponentWithTextContent { text = ''; disabled = false; doSomething() {} } @Component({ template: `<div (cdkObserveContent)="doSomething()"><div>{{text}}</div></div>`, standalone: true, imports: [ObserversModule], }) class ComponentWithChildTextContent { text = ''; doSomething() {} } @Component({ template: `<div (cdkObserveContent)="spy($event)" [debounce]="debounce">{{text}}</div>`, standalone: true, imports: [ObserversModule], }) class ComponentWithDebouncedListener { debounce = 500; spy = jasmine.createSpy('MutationObserver callback'); } @Component({ template: `<div #contentEl>{{text}}</div>`, standalone: true, imports: [ObserversModule], }) class UnobservedComponentWithTextContent { @ViewChild('contentEl') contentEl: ElementRef; text = ''; }
113862
getPlaybackRate(): number { if (this._player) { return this._player.getPlaybackRate(); } if (this._pendingPlayerState && this._pendingPlayerState.playbackRate != null) { return this._pendingPlayerState.playbackRate; } return 0; } /** See https://developers.google.com/youtube/iframe_api_reference#getAvailablePlaybackRates */ getAvailablePlaybackRates(): number[] { return this._player ? this._player.getAvailablePlaybackRates() : []; } /** See https://developers.google.com/youtube/iframe_api_reference#getVideoLoadedFraction */ getVideoLoadedFraction(): number { return this._player ? this._player.getVideoLoadedFraction() : 0; } /** See https://developers.google.com/youtube/iframe_api_reference#getPlayerState */ getPlayerState(): YT.PlayerState | undefined { if (!this._isBrowser || !window.YT) { return undefined; } if (this._player) { return this._player.getPlayerState(); } if (this._pendingPlayerState && this._pendingPlayerState.playbackState != null) { return this._pendingPlayerState.playbackState; } return PlayerState.UNSTARTED; } /** See https://developers.google.com/youtube/iframe_api_reference#getCurrentTime */ getCurrentTime(): number { if (this._player) { return this._player.getCurrentTime(); } if (this._pendingPlayerState && this._pendingPlayerState.seek) { return this._pendingPlayerState.seek.seconds; } return 0; } /** See https://developers.google.com/youtube/iframe_api_reference#getPlaybackQuality */ getPlaybackQuality(): YT.SuggestedVideoQuality { return this._player ? this._player.getPlaybackQuality() : 'default'; } /** See https://developers.google.com/youtube/iframe_api_reference#getAvailableQualityLevels */ getAvailableQualityLevels(): YT.SuggestedVideoQuality[] { return this._player ? this._player.getAvailableQualityLevels() : []; } /** See https://developers.google.com/youtube/iframe_api_reference#getDuration */ getDuration(): number { return this._player ? this._player.getDuration() : 0; } /** See https://developers.google.com/youtube/iframe_api_reference#getVideoUrl */ getVideoUrl(): string { return this._player ? this._player.getVideoUrl() : ''; } /** See https://developers.google.com/youtube/iframe_api_reference#getVideoEmbedCode */ getVideoEmbedCode(): string { return this._player ? this._player.getVideoEmbedCode() : ''; } /** * Loads the YouTube API and sets up the player. * @param playVideo Whether to automatically play the video once the player is loaded. */ protected _load(playVideo: boolean) { // Don't do anything if we're not in a browser environment. if (!this._isBrowser) { return; } if (!window.YT || !window.YT.Player) { if (this.loadApi) { this._isLoading = true; loadApi(this._nonce); } else if (this.showBeforeIframeApiLoads && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw new Error( 'Namespace YT not found, cannot construct embedded youtube player. ' + 'Please install the YouTube Player API Reference for iframe Embeds: ' + 'https://developers.google.com/youtube/iframe_api_reference', ); } this._existingApiReadyCallback = window.onYouTubeIframeAPIReady; window.onYouTubeIframeAPIReady = () => { this._existingApiReadyCallback?.(); this._ngZone.run(() => this._createPlayer(playVideo)); }; } else { this._createPlayer(playVideo); } } /** Loads the player depending on the internal state of the component. */ private _conditionallyLoad() { // If the placeholder isn't shown anymore, we have to trigger a load. if (!this._shouldShowPlaceholder()) { this._load(false); } else if (this.playerVars?.autoplay === 1) { // If it's an autoplaying video, we have to hide the placeholder and start playing. this._load(true); } } /** Whether to show the placeholder element. */ protected _shouldShowPlaceholder(): boolean { if (this.disablePlaceholder) { return false; } // Since we don't load the API on the server, we show the placeholder permanently. if (!this._isBrowser) { return true; } return this._hasPlaceholder && !!this.videoId && !this._player; } /** Gets an object that should be used to store the temporary API state. */ private _getPendingState(): PendingPlayerState { if (!this._pendingPlayerState) { this._pendingPlayerState = {}; } return this._pendingPlayerState; } /** * Determines whether a change in the component state * requires the YouTube player to be recreated. */ private _shouldRecreatePlayer(changes: SimpleChanges): boolean { const change = changes['videoId'] || changes['playerVars'] || changes['disableCookies'] || changes['disablePlaceholder']; return !!change && !change.isFirstChange(); } /** * Creates a new YouTube player and destroys the existing one. * @param playVideo Whether to play the video once it loads. */ private _createPlayer(playVideo: boolean) { this._player?.destroy(); this._pendingPlayer?.destroy(); // A player can't be created if the API isn't loaded, // or there isn't a video or playlist to be played. if (typeof YT === 'undefined' || (!this.videoId && !this.playerVars?.list)) { return; } // Important! We need to create the Player object outside of the `NgZone`, because it kicks // off a 250ms setInterval which will continually trigger change detection if we don't. const player = this._ngZone.runOutsideAngular( () => new YT.Player(this.youtubeContainer.nativeElement, { videoId: this.videoId, host: this.disableCookies ? 'https://www.youtube-nocookie.com' : undefined, width: this.width, height: this.height, // Calling `playVideo` on load doesn't appear to actually play // the video so we need to trigger it through `playerVars` instead. playerVars: playVideo ? {...(this.playerVars || {}), autoplay: 1} : this.playerVars, }), ); const whenReady = () => { // Only assign the player once it's ready, otherwise YouTube doesn't expose some APIs. this._ngZone.run(() => { this._isLoading = false; this._hasPlaceholder = false; this._player = player; this._pendingPlayer = undefined; player.removeEventListener('onReady', whenReady); this._playerChanges.next(player); this._setSize(); this._setQuality(); if (this._pendingPlayerState) { this._applyPendingPlayerState(player, this._pendingPlayerState); this._pendingPlayerState = undefined; } // Only cue the player when it either hasn't started yet or it's cued, // otherwise cuing it can interrupt a player with autoplay enabled. const state = player.getPlayerState(); if (state === PlayerState.UNSTARTED || state === PlayerState.CUED || state == null) { this._cuePlayer(); } this._changeDetectorRef.markForCheck(); }); }; this._pendingPlayer = player; player.addEventListener('onReady', whenReady); } /** Applies any state that changed before the player was initialized. */ private _applyPendingPlayerState(player: YT.Player, pendingState: PendingPlayerState): void { const {playbackState, playbackRate, volume, muted, seek} = pendingState; switch (playbackState) { case PlayerState.PLAYING: player.playVideo(); break; case PlayerState.PAUSED: player.pauseVideo(); break; case PlayerState.CUED: player.stopVideo(); break; } if (playbackRate != null) { player.setPlaybackRate(playbackRate); } if (volume != null) { player.setVolume(volume); } if (muted != null) { muted ? player.mute() : player.unMute(); } if (seek != null) { player.seekTo(seek.seconds, seek.allowSeekAhead); } } /** Cues the player based on the current component state. */ private _cuePlayer() { if (this._player && this.videoId) { this._player.cueVideoById({ videoId: this.videoId, startSeconds: this.startSeconds, endSeconds: this.endSeconds, suggestedQuality: this.suggestedQuality, }); } } /** Sets the player's size based on the current input values. */
113979
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Angular Material</title> <base href="/"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> <link href="theme.css" rel="stylesheet"> </head> <body class="mat-typography"> <e2e-app>Loading...</e2e-app> <span class="sibling">I am a sibling!</span> <script src="zone.js/bundles/zone.umd.min.js"></script> <script src="kagekiri/dist/kagekiri.umd.min.js"></script> <script src="bundles/e2e-app/main.js" type="module"></script> </body> </html>
113986
@use '@angular/material' as mat; $theme: mat.define-theme(( color: ( theme-type: light, primary: mat.$azure-palette, tertiary: mat.$blue-palette, ), density: ( scale: 0, ) )); html { @include mat.all-component-themes($theme); } @include mat.typography-hierarchy($theme);
114314
import {Component} from '@angular/core'; import {DataSource} from '@angular/cdk/collections'; import {NgForm, FormsModule} from '@angular/forms'; import {MatIconModule} from '@angular/material/icon'; import {MatButtonModule} from '@angular/material/button'; import {MatInputModule} from '@angular/material/input'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatPopoverEditModule} from '@angular/material-experimental/popover-edit'; import {CdkPopoverEditModule} from '@angular/cdk-experimental/popover-edit'; import {MatTableModule} from '@angular/material/table'; import {BehaviorSubject, Observable} from 'rxjs'; export interface Person { id: number; firstName: string; middleName: string; lastName: string; } const PERSON_DATA: Person[] = [ {id: 1, firstName: 'Terra', middleName: 'Maduin', lastName: 'Branford'}, {id: 2, firstName: 'Locke', middleName: '', lastName: 'Cole'}, {id: 3, firstName: 'Celes', middleName: 'Gestahl', lastName: 'Chere'}, {id: 4, firstName: 'Edgar', middleName: 'Roni', lastName: 'Figaro'}, {id: 5, firstName: 'Sabin', middleName: 'Rene', lastName: 'Figaro'}, {id: 6, firstName: 'Clyde', middleName: '"Shadow"', lastName: 'Arrowny'}, {id: 7, firstName: 'Setzer', middleName: '', lastName: 'Gabbiani'}, {id: 8, firstName: 'Cid', middleName: 'Del Norte', lastName: 'Marquez'}, {id: 9, firstName: 'Mog', middleName: '', lastName: 'McMoogle'}, ]; /** * @title Material Popover Edit spanning multiple columns on a Material data-table */ @Component({ selector: 'popover-edit-cell-span-mat-table-example', styleUrl: 'popover-edit-cell-span-mat-table-example.css', templateUrl: 'popover-edit-cell-span-mat-table-example.html', imports: [ MatTableModule, CdkPopoverEditModule, FormsModule, MatPopoverEditModule, MatFormFieldModule, MatInputModule, MatButtonModule, MatIconModule, ], }) export class PopoverEditCellSpanMatTableExample { displayedColumns: string[] = ['id', 'firstName', 'middleName', 'lastName']; dataSource = new ExampleDataSource(); readonly preservedValues = new WeakMap<Person, any>(); onSubmit(person: Person, f: NgForm) { if (!f.valid) { return; } person.firstName = f.value['firstName']; person.middleName = f.value['middleName']; person.lastName = f.value['lastName']; } } /** * Data source to provide what data should be rendered in the table. Note that the data source * can retrieve its data in any way. In this case, the data source is provided a reference * to a common data base, ExampleDatabase. It is not the data source's responsibility to manage * the underlying data. Instead, it only needs to take the data and send the table exactly what * should be rendered. */ export class ExampleDataSource extends DataSource<Person> { /** Stream of data that is provided to the table. */ data = new BehaviorSubject<Person[]>(PERSON_DATA); /** Connect function called by the table to retrieve one stream containing the data to render. */ connect(): Observable<Person[]> { return this.data; } disconnect() {} }
114536
<mat-autocomplete #autocomplete="matAutocomplete"> @for (state of states; track state) { <mat-option [value]="state.code">{{ state.name }}</mat-option> } </mat-autocomplete> <input id="plain" [matAutocomplete]="autocomplete"> <input id="disabled" disabled [matAutocomplete]="autocomplete">
114539
Control value: {{myControl.value || 'empty'}} <form class="example-form"> <mat-form-field class="example-full-width"> <mat-label>Number</mat-label> <input #input type="text" placeholder="Pick one" matInput [formControl]="myControl" [matAutocomplete]="auto" (input)="filter()" (focus)="filter()"> <mat-autocomplete requireSelection #auto="matAutocomplete"> @for (option of filteredOptions; track option) { <mat-option [value]="option">{{option}}</mat-option> } </mat-autocomplete> </mat-form-field> </form>
114622
import {Component} from '@angular/core'; import {MatInputModule} from '@angular/material/input'; import {MatFormFieldModule} from '@angular/material/form-field'; import {FormsModule} from '@angular/forms'; /** * @title Inputs in a form */ @Component({ selector: 'input-form-example', templateUrl: 'input-form-example.html', styleUrl: 'input-form-example.css', imports: [FormsModule, MatFormFieldModule, MatInputModule], }) export class InputFormExample {}
114690
import {ChangeDetectionStrategy, Component, ViewEncapsulation} from '@angular/core'; import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {provideMomentDateAdapter} from '@angular/material-moment-adapter'; import {MatDatepicker, MatDatepickerModule} from '@angular/material/datepicker'; // Depending on whether rollup is used, moment needs to be imported differently. // Since Moment.js doesn't have a default export, we normally need to import using the `* as` // syntax. However, rollup creates a synthetic default module and we thus need to import it using // the `default as` syntax. import * as _moment from 'moment'; // tslint:disable-next-line:no-duplicate-imports import {default as _rollupMoment, Moment} from 'moment'; import {MatInputModule} from '@angular/material/input'; import {MatFormFieldModule} from '@angular/material/form-field'; const moment = _rollupMoment || _moment; // See the Moment.js docs for the meaning of these formats: // https://momentjs.com/docs/#/displaying/format/ export const MY_FORMATS = { parse: { dateInput: 'MM/YYYY', }, display: { dateInput: 'MM/YYYY', monthYearLabel: 'MMM YYYY', dateA11yLabel: 'LL', monthYearA11yLabel: 'MMMM YYYY', }, }; /** @title Datepicker emulating a Year and month picker */ @Component({ selector: 'datepicker-views-selection-example', templateUrl: 'datepicker-views-selection-example.html', styleUrl: 'datepicker-views-selection-example.css', providers: [ // Moment can be provided globally to your app by adding `provideMomentDateAdapter` // to your app config. We provide it at the component level here, due to limitations // of our example generation script. provideMomentDateAdapter(MY_FORMATS), ], encapsulation: ViewEncapsulation.None, imports: [ MatFormFieldModule, MatInputModule, MatDatepickerModule, FormsModule, ReactiveFormsModule, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DatepickerViewsSelectionExample { readonly date = new FormControl(moment()); setMonthAndYear(normalizedMonthAndYear: Moment, datepicker: MatDatepicker<Moment>) { const ctrlValue = this.date.value ?? moment(); ctrlValue.month(normalizedMonthAndYear.month()); ctrlValue.year(normalizedMonthAndYear.year()); this.date.setValue(ctrlValue); datepicker.close(); } }
114704
import {ChangeDetectionStrategy, Component} from '@angular/core'; import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {provideMomentDateAdapter} from '@angular/material-moment-adapter'; import {MatDatepickerModule} from '@angular/material/datepicker'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatInputModule} from '@angular/material/input'; // Depending on whether rollup is used, moment needs to be imported differently. // Since Moment.js doesn't have a default export, we normally need to import using the `* as` // syntax. However, rollup creates a synthetic default module and we thus need to import it using // the `default as` syntax. import * as _moment from 'moment'; // tslint:disable-next-line:no-duplicate-imports import {default as _rollupMoment} from 'moment'; const moment = _rollupMoment || _moment; /** @title Datepicker that uses Moment.js dates */ @Component({ selector: 'datepicker-moment-example', templateUrl: 'datepicker-moment-example.html', providers: [ // Moment can be provided globally to your app by adding `provideMomentDateAdapter` // to your app config. We provide it at the component level here, due to limitations // of our example generation script. provideMomentDateAdapter(), ], imports: [ MatFormFieldModule, MatInputModule, MatDatepickerModule, FormsModule, ReactiveFormsModule, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class DatepickerMomentExample { // Datepicker takes `Moment` objects instead of `Date` objects. readonly date = new FormControl(moment([2017, 0, 1])); }
114951
import {Component} from '@angular/core'; import {MatTableModule} from '@angular/material/table'; export interface PeriodicElement { name: string; position: number; weight: number; symbol: string; } const ELEMENT_DATA: PeriodicElement[] = [ {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'}, {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'}, {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'}, {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'}, {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'}, {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'}, {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'}, {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'}, {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'}, {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'}, ]; /** * @title Binding event handlers and properties to the table rows. */ @Component({ selector: 'table-row-binding-example', styleUrl: 'table-row-binding-example.css', templateUrl: 'table-row-binding-example.html', imports: [MatTableModule], }) export class TableRowBindingExample { displayedColumns: string[] = ['position', 'name', 'weight', 'symbol']; dataSource = ELEMENT_DATA; clickedRows = new Set<PeriodicElement>(); }
114954
import {HttpClient} from '@angular/common/http'; import {Component, ViewChild, AfterViewInit, inject} from '@angular/core'; import {MatPaginator, MatPaginatorModule} from '@angular/material/paginator'; import {MatSort, MatSortModule, SortDirection} from '@angular/material/sort'; import {merge, Observable, of as observableOf} from 'rxjs'; import {catchError, map, startWith, switchMap} from 'rxjs/operators'; import {MatTableModule} from '@angular/material/table'; import {MatProgressSpinnerModule} from '@angular/material/progress-spinner'; import {DatePipe} from '@angular/common'; /** * @title Table retrieving data through HTTP */ @Component({ selector: 'table-http-example', styleUrl: 'table-http-example.css', templateUrl: 'table-http-example.html', imports: [MatProgressSpinnerModule, MatTableModule, MatSortModule, MatPaginatorModule, DatePipe], }) export class TableHttpExample implements AfterViewInit { private _httpClient = inject(HttpClient); displayedColumns: string[] = ['created', 'state', 'number', 'title']; exampleDatabase: ExampleHttpDatabase | null; data: GithubIssue[] = []; resultsLength = 0; isLoadingResults = true; isRateLimitReached = false; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; ngAfterViewInit() { this.exampleDatabase = new ExampleHttpDatabase(this._httpClient); // If the user changes the sort order, reset back to the first page. this.sort.sortChange.subscribe(() => (this.paginator.pageIndex = 0)); merge(this.sort.sortChange, this.paginator.page) .pipe( startWith({}), switchMap(() => { this.isLoadingResults = true; return this.exampleDatabase!.getRepoIssues( this.sort.active, this.sort.direction, this.paginator.pageIndex, ).pipe(catchError(() => observableOf(null))); }), map(data => { // Flip flag to show that loading has finished. this.isLoadingResults = false; this.isRateLimitReached = data === null; if (data === null) { return []; } // Only refresh the result length if there is new data. In case of rate // limit errors, we do not want to reset the paginator to zero, as that // would prevent users from re-triggering requests. this.resultsLength = data.total_count; return data.items; }), ) .subscribe(data => (this.data = data)); } } export interface GithubApi { items: GithubIssue[]; total_count: number; } export interface GithubIssue { created_at: string; number: string; state: string; title: string; } /** An example database that the data source uses to retrieve data for the table. */ export class ExampleHttpDatabase { constructor(private _httpClient: HttpClient) {} getRepoIssues(sort: string, order: SortDirection, page: number): Observable<GithubApi> { const href = 'https://api.github.com/search/issues'; const requestUrl = `${href}?q=repo:angular/components&sort=${sort}&order=${order}&page=${ page + 1 }`; return this._httpClient.get<GithubApi>(requestUrl); } }
114979
import {AfterViewInit, Component, ViewChild} from '@angular/core'; import {MatPaginator, MatPaginatorModule} from '@angular/material/paginator'; import {MatSort, MatSortModule} from '@angular/material/sort'; import {MatTableDataSource, MatTableModule} from '@angular/material/table'; import {MatInputModule} from '@angular/material/input'; import {MatFormFieldModule} from '@angular/material/form-field'; export interface UserData { id: string; name: string; progress: string; fruit: string; } /** Constants used to fill up our data base. */ const FRUITS: string[] = [ 'blueberry', 'lychee', 'kiwi', 'mango', 'peach', 'lime', 'pomegranate', 'pineapple', ]; const NAMES: string[] = [ 'Maia', 'Asher', 'Olivia', 'Atticus', 'Amelia', 'Jack', 'Charlotte', 'Theodore', 'Isla', 'Oliver', 'Isabella', 'Jasper', 'Cora', 'Levi', 'Violet', 'Arthur', 'Mia', 'Thomas', 'Elizabeth', ]; /** * @title Data table with sorting, pagination, and filtering. */ @Component({ selector: 'table-overview-example', styleUrl: 'table-overview-example.css', templateUrl: 'table-overview-example.html', imports: [MatFormFieldModule, MatInputModule, MatTableModule, MatSortModule, MatPaginatorModule], }) export class TableOverviewExample implements AfterViewInit { displayedColumns: string[] = ['id', 'name', 'progress', 'fruit']; dataSource: MatTableDataSource<UserData>; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; constructor() { // Create 100 users const users = Array.from({length: 100}, (_, k) => createNewUser(k + 1)); // Assign the data to the data source for the table to render this.dataSource = new MatTableDataSource(users); } ngAfterViewInit() { this.dataSource.paginator = this.paginator; this.dataSource.sort = this.sort; } applyFilter(event: Event) { const filterValue = (event.target as HTMLInputElement).value; this.dataSource.filter = filterValue.trim().toLowerCase(); if (this.dataSource.paginator) { this.dataSource.paginator.firstPage(); } } } /** Builds and returns a new User. */ function createNewUser(id: number): UserData { const name = NAMES[Math.round(Math.random() * (NAMES.length - 1))] + ' ' + NAMES[Math.round(Math.random() * (NAMES.length - 1))].charAt(0) + '.'; return { id: id.toString(), name: name, progress: Math.round(Math.random() * 100).toString(), fruit: FRUITS[Math.round(Math.random() * (FRUITS.length - 1))], }; }
114999
<form [formGroup]="form"> <mat-selection-list #shoesList [formControl]="shoesControl" name="shoes" [multiple]="false"> @for (shoe of shoes; track shoe) { <mat-list-option [value]="shoe.value">{{shoe.name}}</mat-list-option> } </mat-selection-list> <p> Option selected: {{shoesControl.value ? shoesControl.value[0] : 'None'}} </p> </form>
115007
<mat-selection-list #shoes> @for (shoe of typesOfShoes; track shoe) { <mat-list-option>{{shoe}}</mat-list-option> } </mat-selection-list> <p> Options selected: {{shoes.selectedOptions.selected.length}} </p>
115015
<form [formGroup]="form"> <mat-selection-list #shoesList [formControl]="shoesControl" name="shoes" [multiple]="false"> @for (shoe of shoes; track shoe) { <mat-list-option [value]="shoe.value">{{shoe.name}}</mat-list-option> } </mat-selection-list> <p> Option selected: {{shoesControl.value ? shoesControl.value[0] : 'None'}} </p> </form>
115140
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Angular Material</title> <base href="/"> <link rel="icon" type="image/x-icon" href="favicon.ico"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://fonts.googleapis.com/icon?family=Material+Symbols+Outlined" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> <!-- FontAwesome for mat-icon demo. --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> </head> <body> <dev-app>Loading...</dev-app> <script src="zone.js/bundles/zone.umd.js"></script> <script src="bundles/dev-app/main.js" type="module"></script> <script> (g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({ v: "weekly", key: window.GOOGLE_MAPS_KEY || 'invalid' }); </script> </body> </html>
115145
@use '@angular/material' as mat; @use '@angular/material-experimental' as experimental; // Plus imports for other components in your app. // Disable legacy API compatibility, since dev-app is fully migrated to theme inspection API. mat.$theme-legacy-inspection-api-compatibility: false; // Define the default (light) theme. $candy-app-primary: mat.m2-define-palette(mat.$m2-indigo-palette); $candy-app-accent: mat.m2-define-palette(mat.$m2-pink-palette, A200, A100, A400); $candy-app-theme: mat.m2-define-light-theme(( // Define the default colors for our app. color: ( primary: $candy-app-primary, accent: $candy-app-accent ), // Define the default typography for our app. typography: mat.m2-define-typography-config(), // Define the default density level for our app. density: 0, )); @include mat.app-background(); @include mat.elevation-classes(); // Include the default theme styles. @include mat.all-component-themes($candy-app-theme); @include experimental.column-resize-theme($candy-app-theme); @include experimental.popover-edit-theme($candy-app-theme); @include mat.typography-hierarchy($candy-app-theme); .demo-strong-focus { // Note: we can theme the indicators directly through `strong-focus-indicators` as well. // Use the theme so we have some coverage over the entire API surface. @include mat.strong-focus-indicators(); @include mat.strong-focus-indicators-theme($candy-app-theme); } // Include the alternative theme styles inside of a block with a CSS class. You can make this // CSS class whatever you want. In this example, any component inside of an element with // `.demo-unicorn-dark-theme` will be affected by this alternate dark theme instead of the // default theme. .demo-unicorn-dark-theme { // Create the color palettes used in our dark theme. $dark-primary: mat.m2-define-palette(mat.$m2-blue-grey-palette); $dark-accent: mat.m2-define-palette(mat.$m2-amber-palette, A200, A100, A400); $dark-warn: mat.m2-define-palette(mat.$m2-deep-orange-palette); $dark-colors: mat.m2-define-dark-theme( ( color: ( primary: $dark-primary, accent: $dark-accent, warn: $dark-warn ), density: 0, typography: mat.m2-define-typography-config(), ) ); // Include the dark theme color styles. @include mat.all-component-colors($dark-colors); @include experimental.column-resize-color($dark-colors); @include experimental.popover-edit-color($dark-colors); // Include the dark theme colors for focus indicators. &.demo-strong-focus { @include mat.strong-focus-indicators-color($dark-colors); } } // Create classes for all density scales which are supported by all MDC-based components. // The classes are applied conditionally based on the selected density in the dev-app layout // component. $density-scales: (-1, -2, -3, -4, minimum, maximum); @each $density in $density-scales { .demo-density-#{$density} { @include mat.all-component-densities($density); } }
115146
@use '@angular/material' as mat; // Plus imports for other components in your app. // Disable legacy API compatibility, since dev-app is fully migrated to theme inspection API. mat.$theme-legacy-inspection-api-compatibility: false; $primary: mat.$azure-palette; $tertiary: mat.$blue-palette; // Create a theme with the specified color type and density. @function create-theme($type: light, $density: 0) { @return mat.define-theme(( color: ( theme-type: $type, primary: $primary, tertiary: $tertiary, use-system-variables: true, ), typography: (use-system-variables: true), density: ( scale: $density ), )); } // Define the default (light) theme. $light-theme: create-theme($type: light); // Create our dark theme. $dark-theme: create-theme($type: dark); // Include the default theme styles. html { color-scheme: light; body:not(.demo-experimental-theme) { @include mat.all-component-themes($light-theme); @include mat.system-level-colors($light-theme); @include mat.system-level-typography($light-theme); // TODO(mmalerba): Support M3 for experimental components. // @include matx.column-resize-theme($light-theme); // @include matx.popover-edit-theme($light-theme); } body.demo-experimental-theme { @include mat.theme(( color: ( primary: $primary, tertiary: $tertiary, ), typography: Roboto, density: 0, )); } } @include mat.typography-hierarchy($light-theme); .demo-strong-focus { // Note: we can theme the indicators directly through `strong-focus-indicators` as well. // Use the theme so we have some coverage over the entire API surface. @include mat.strong-focus-indicators(); @include mat.strong-focus-indicators-theme($light-theme); } // Include the alternative theme styles inside of a block with a CSS class. You can make this // CSS class whatever you want. In this example, any component inside of an element with // `.demo-unicorn-dark-theme` will be affected by this alternate dark theme instead of the // default theme. body.demo-unicorn-dark-theme { color-scheme: dark; &:not(.demo-experimental-theme) { // Include the dark theme color styles. @include mat.all-component-colors($dark-theme); @include mat.system-level-colors($dark-theme); // TODO(mmalerba): Support M3 for experimental components. // @include matx.column-resize-color($dark-theme); // @include matx.popover-edit-color($dark-theme); } // Include the dark theme colors for focus indicators. &.demo-strong-focus { @include mat.strong-focus-indicators-color($dark-theme); } } // Create classes for all density scales which are supported by all MDC-based components. // The classes are applied conditionally based on the selected density in the dev-app layout // component. $density-scales: (-1, -2, -3, -4, minimum, maximum); @each $scale in $density-scales { .demo-density-#{$scale} { body:not(.demo-experimental-theme) & { $density-theme: create-theme($density: $scale); @include mat.all-component-densities($density-theme); } body.demo-experimental-theme & { @include mat.theme((density: $scale)); } } } // Enable back-compat CSS for color="..." API & typography hierarchy. .demo-color-api-back-compat { @include mat.color-variants-backwards-compatibility($light-theme); @include mat.typography-hierarchy($light-theme, $back-compat: true); &.demo-unicorn-dark-theme { @include mat.color-variants-backwards-compatibility($dark-theme); } } // In M3 buttons are smaller than their touch target at zero-density. .demo-config-buttons button { margin: 4px; } // In M3 we need some spacing around the list in the sidenav. mat-nav-list.demo-nav-list { margin: 8px; }
115194
Space above cards: <input type="number" [formControl]="topHeightCtrl"> <div [style.height.px]="topHeightCtrl.value"></div> <div class="demo-autocomplete"> <mat-card> Reactive length: {{ reactiveStates.length }} <div class="demo-truncate-text">Reactive value: {{ stateCtrl.value | json }}</div> <div>Reactive dirty: {{ stateCtrl.dirty }}</div> <mat-form-field [color]="reactiveStatesTheme"> <mat-label>State</mat-label> <input #reactiveInput matInput [matAutocomplete]="reactiveAuto" [formControl]="stateCtrl" (input)="reactiveStates = filterStates(reactiveInput.value)" (focus)="reactiveStates = filterStates(reactiveInput.value)"> </mat-form-field> <mat-autocomplete #reactiveAuto="matAutocomplete" [displayWith]="displayFn" [hideSingleSelectionIndicator]="reactiveHideSingleSelectionIndicator" [autoActiveFirstOption]="reactiveAutoActiveFirstOption" [requireSelection]="reactiveRequireSelection"> @for (state of reactiveStates; track state; let index = $index) { <mat-option [value]="state" [disabled]="reactiveIsStateDisabled(state.index)"> <span>{{ state.name }}</span> <span class="demo-secondary-text"> ({{ state.code }}) </span> </mat-option> } </mat-autocomplete> <p> <button mat-button (click)="stateCtrl.reset()">RESET</button> <button mat-button (click)="stateCtrl.setValue(states[10])">SET VALUE</button> <button mat-button (click)="stateCtrl.enabled ? stateCtrl.disable() : stateCtrl.enable()"> TOGGLE DISABLED </button> </p> <p> <label for="reactive-disable-state-options">Disable States</label> <select [(ngModel)]="reactiveDisableStateOption" id="reactive-disable-state-options"> <option value="none">None</option> <option value="first-middle-last">Disable First, Middle and Last States</option> <option value="all">Disable All States</option> </select> </p> <p> <mat-checkbox [(ngModel)]="reactiveHideSingleSelectionIndicator"> Hide Single-Selection Indicator </mat-checkbox> </p> <p> <mat-checkbox [(ngModel)]="reactiveAutoActiveFirstOption"> Automatically activate first option </mat-checkbox> </p> <p> <mat-checkbox [(ngModel)]="reactiveRequireSelection"> Require Selection </mat-checkbox> </p> </mat-card> <mat-card> <div>Template-driven value (currentState): {{ currentState }}</div> <div>Template-driven dirty: {{ modelDir ? modelDir.dirty : false }}</div> <!-- Added an @if below to test that autocomplete works with @if --> @if (true) { <mat-form-field [color]="templateStatesTheme"> <mat-label>State</mat-label> <input matInput [matAutocomplete]="tdAuto" [(ngModel)]="currentState" (ngModelChange)="tdStates = filterStates(currentState)" [disabled]="tdDisabled"> <mat-autocomplete #tdAuto="matAutocomplete" [hideSingleSelectionIndicator]="templateHideSingleSelectionIndicator" [autoActiveFirstOption]="templateAutoActiveFirstOption" [requireSelection]="templateRequireSelection"> @for (state of tdStates; track state) { <mat-option [value]="state.name" [disabled]="templateIsStateDisabled(state.index)"> <span>{{ state.name }}</span> </mat-option> } </mat-autocomplete> </mat-form-field> } <p> <button mat-button (click)="clearTemplateState()">RESET</button> <button mat-button (click)="currentState='California'">SET VALUE</button> <button mat-button (click)="tdDisabled=!tdDisabled"> TOGGLE DISABLED </button> <select [(ngModel)]="templateStatesTheme"> @for (theme of availableThemes; track theme) { <option [value]="theme.value">{{theme.name}}</option> } </select> </p> <p> <mat-checkbox [(ngModel)]="templateHideSingleSelectionIndicator"> Hide Single-Selection Indicator </mat-checkbox> <p> <mat-checkbox [(ngModel)]="templateAutoActiveFirstOption"> Automatically activate first option </mat-checkbox> </p> <p> <mat-checkbox [(ngModel)]="templateRequireSelection"> Require Selection </mat-checkbox> </p> <p> <label for="template-disable-state-options">Disable States</label> <select [(ngModel)]="templateDisableStateOption" id="template-disable-state-options"> <option value="none">None</option> <option value="first-middle-last">Disable First, Middle and Last States</option> <option value="all">Disable All States</option> </select> </p> </mat-card> <mat-card> <div>Option groups (currentGroupedState): {{ currentGroupedState }}</div> <mat-form-field> <mat-label>State</mat-label> <input matInput [matAutocomplete]="groupedAuto" [(ngModel)]="currentGroupedState" (ngModelChange)="filteredGroupedStates = filterStateGroups(currentGroupedState)"> </mat-form-field> </mat-card> <mat-card> <mat-card-subtitle>Autocomplete inside a Dialog</mat-card-subtitle> <mat-card-content> <button mat-button (click)="openDialog()">Open dialog</button> </mat-card-content> </mat-card> </div> <mat-autocomplete #groupedAuto="matAutocomplete"> @for (group of filteredGroupedStates; track group) { <mat-optgroup [label]="'States starting with ' + group.letter"> @for (state of group.states; track state) { <mat-option [value]="state.name">{{ state.name }}</mat-option> } </mat-optgroup> } </mat-autocomplete>
115292
<div #demoYouTubePlayer class="demo-youtube-player"> <h2>Basic Example</h2> <section> <div class="demo-video-selection"> <label>Pick the video:</label> <mat-radio-group aria-label="Select a video" [(ngModel)]="selectedVideo"> @for (video of videos; track video) { <mat-radio-button [value]="video">{{video.name}}</mat-radio-button> } <mat-radio-button [value]="undefined">Unset</mat-radio-button> </mat-radio-group> </div> <div class="demo-video-selection"> <mat-checkbox [(ngModel)]="disableCookies">Disable cookies</mat-checkbox> <mat-checkbox [(ngModel)]="disablePlaceholder">Disable placeholder</mat-checkbox> </div> <youtube-player [videoId]="selectedVideoId" [playerVars]="playerVars" [width]="videoWidth" [height]="videoHeight" [disableCookies]="disableCookies" [disablePlaceholder]="disablePlaceholder" [placeholderImageQuality]="placeholderQuality"></youtube-player> </section> <h2>Placeholder quality comparison (high to low)</h2> <youtube-player [videoId]="selectedVideoId" [width]="videoWidth" [height]="videoHeight" placeholderImageQuality="high"/> <youtube-player [videoId]="selectedVideoId" [width]="videoWidth" [height]="videoHeight" placeholderImageQuality="standard"/> <youtube-player [videoId]="selectedVideoId" [width]="videoWidth" [height]="videoHeight" placeholderImageQuality="low"/> </div>
115315
@use '@angular/material' as mat; :host { display: block; max-width: 1000px; } h1 { font: var(--mat-sys-title-large); font-size: 28px; padding-top: 32px; } h2 { font: var(--mat-sys-title-large); } a { color: var(--mat-sys-primary); } .demo-warn { background: var(--mat-sys-error-container); color: var(--mat-sys-on-error-container); border: 1px solid var(--mat-sys-outline-variant); border-radius: var(--mat-sys-corner-extra-small); padding: 8px; } .demo-group { display: grid; grid-template-columns: 1fr 1fr; grid-gap: 24px; margin-top: 24px; } @media (max-width: 1000px) { .demo-group { grid-template-columns: auto;} } .demo-color-container { border-radius: var(--mat-sys-corner-small); display: inline-block; font: var(--mat-sys-body-medium); vertical-align: top; } .demo-heading { color: var(--mat-sys-on-primary); background: var(--mat-sys-primary); border: 1px solid var(--mat-sys-outline); border-top-right-radius: var(--mat-sys-corner-small); border-top-left-radius: var(--mat-sys-corner-small); border-bottom: none; padding: 16px; display: flex; align-items: center; justify-content: space-between; } .demo-name { font: var(--mat-sys-title-medium); } .demo-variable { font: var(--mat-sys-title-small); font-family: monospace; text-align: right; } .demo-description { border: 1px solid var(--mat-sys-outline); border-bottom-right-radius: var(--mat-sys-corner-small); border-bottom-left-radius: var(--mat-sys-corner-small); padding: 0 16px; } .demo-code { font-family: monospace; } .demo-surface-variable { display: inline-block; font-family: monospace; background: var(--mat-sys-primary-container); color: var(--mat-sys-on-primary-container); padding: 2px 6px; margin: 0 2px; border-radius: 4px; } mat-expansion-panel { margin-top: 24px; overflow: visible; @include mat.expansion-overrides(( 'container-text-font': var(--mat-sys-body-medium-font), 'container-text-size': var(--mat-sys-body-medium-size), 'container-text-weight': var(--mat-sys-body-medium-weight), 'container-text-line-height': var(--mat-sys-body-medium-line-height), 'container-text-tracking': var(--mat-sys-body-medium-tracking), )); } .demo-compact-color-container { border-radius: var(--mat-sys-corner-small); border: 1px solid var(--mat-sys-outline); overflow: hidden; // Hide child heading background color margin-top: 24px; .demo-heading { border: none; border-radius: 0; &:not(:nth-child(1)) { border-top: 1px solid var(--mat-sys-outline); } } .demo-variables { text-align: end; } } .demo-typography-group { border: 1px solid var(--mat-sys-outline); border-radius: var(--mat-sys-corner-small); margin-top: 40px; overflow: hidden; } .demo-typography-title { text-transform: capitalize; font: var(--mat-sys-title-medium); padding: 16px; border-bottom: 1px solid var(--mat-sys-outline); background: var(--mat-sys-primary-container); color: var(--mat-sys-on-primary-container); } .demo-typography-variable { min-width: 240px; } .demo-typography-example { padding: 16px; display: flex; align-items: baseline; border-top: 1px solid var(--mat-sys-outline-variant); &:nth-child(1) { border: none; } .demo-surface-variable { margin-right: 16px; } } .demo-typography-text { display: inline-block; } .demo-elevation { height: 40px; width: 300px; margin: 32px; display: flex; align-items: center; justify-content: center; background: var(--mat-sys-surface-container); color: var(--mat-sys-on-surface); border-radius: var(--mat-sys-corner-extra-small); } .demo-code-block { background: var(--mat-sys-surface-container-low); padding: 16px; border-radius: var(--mat-sys-corner-small); border: 1px solid var(--mat-sys-outline); } .demo-overrides { background-color: var(--mat-sys-primary); color: var(--mat-sys-on-primary); font: var(--mat-sys-body-medium); border-radius: var(--mat-sys-corner-large); box-shadow: var(--mat-sys-level3); padding: 16px; @include mat.theme-overrides(( primary: #ebdcff, on-primary: #230f46, body-medium: 600 1.5rem / 2.25rem Arial, corner-large: 32px, level3: 0 4px 6px 1px var(--mat-sys-surface-dim), )); }
115316
<p class="demo-warn"> This page uses an experimental prototype version of a <span class="demo-surface-variable">material.theme</span> API. To enable it, click the <mat-icon>public</mat-icon> icon in the header. </p> <p> Angular Material components depend on CSS variables defined by the <span class="demo-surface-variable">material.theme</span> Sass mixin. This page provides guidance and documentation for using these variables to customize components. </p> <h1>Colors</h1> <p> Material Design uses color to create accessible, personal color schemes that communicate your product's hierarchy, state, and brand. See Material Design's <a href="https://m3.material.io/styles/color/system/overview">Color System</a> page to learn more about its use and purpose. </p> <p> The following colors are the most often used in Angular Material components. Use these colors and follow their uses to add theme colors to your application's custom components. </p> <p> Note that variables starting with "--mat-sys-on-*" are designed to be used for text or icons placed on top of its paired parent color. For example, <span class="demo-surface-variable">--mat-sys-on-primary</span> is used for text and icons in elements filled with the <span class="demo-surface-variable">--mat-sys-primary</span> color. </p> <div class="demo-group"> <div class="demo-color-container"> <div class="demo-heading" [style.background-color]="'var(--mat-sys-primary)'" [style.color]="'var(--mat-sys-on-primary)'"> <div class="demo-name"> Primary</div> <div class="demo-variable demo-code"> --mat-sys-primary</div> </div> <div class="demo-description"> <p> The most common color used by Angular Material components to participate in the application theme. </p> <p> Examples include the background color of filled buttons, the icon color of selected radio buttons, and the outline color of form fields. </p> <p> Use the color <span class="demo-surface-variable">--mat-sys-on-primary</span> for icons, text, and other visual elements placed on a primary background. This color is calculated to be optimal for accessibility and legibility. </p> </div> </div> <div class="demo-color-container"> <div class="demo-heading" [style.background-color]="'var(--mat-sys-surface)'" [style.color]="'var(--mat-sys-on-surface)'"> <div class="demo-name"> Surface</div> <div class="demo-variable code"> --mat-sys-surface</div> </div> <div class="demo-description"> <p> A low-emphasis background color that provides a clear contrast for both light and dark themes and their varied theme colors. </p> <p> Examples include the background color of the application and most components such as the dialog, card, table, and more. </p> <p> Use the color <span class="demo-surface-variable">--mat-sys-on-surface</span> for icons, text, and other visual elements placed on a surface background. This color is calculated to be optimal for accessibility and legibility. </p> </div> </div> <div class="demo-color-container"> <div class="demo-heading" [style.background-color]="'var(--mat-sys-error)'" [style.color]="'var(--mat-sys-on-error)'"> <div class="demo-name"> Error</div> <div class="demo-variable demo-code"> --mat-sys-error</div> </div> <div class="demo-description"> <p> High-contrast color meant to alert the user to attract immediate attention. </p> <p> Examples include the background color of the badge and the text color of invalid form fields inputs. </p> <p> Use the color <span class="demo-surface-variable">--mat-sys-on-error</span> for icons, text, and other visual elements placed on an error background. This color is calculated to be optimal for accessibility and legibility. </p> </div> </div> <div class="demo-color-container"> <div class="demo-heading" [style.background-color]="'var(--mat-sys-outline)'" [style.color]="'var(--mat-sys-surface)'"> <div class="demo-name"> Outline</div> <div class="demo-variable demo-code"> --mat-sys-outline </div> </div> <div class="demo-description"> <p> Used for borders and dividers to help provide visual separation between and around elements. </p> <p> Examples include the color of the divider and border color of an outlined form field. </p> <p> Use the color <span class="demo-surface-variable">--mat-sys-outline-variant</span> for a less prominent outline. </p> </div> </div> </div> <mat-expansion-panel> <mat-expansion-panel-header>Other available colors</mat-expansion-panel-header> <p> These colors are less commonly used in Angular Material components but are available for adding color variety and creating additional emphasis to components. </p> <p> Colors may be paired with a <span class="demo-surface-variable">--mat-sys-on-</span> variable that should be used for text and icons placed within a filled container. </p> <h2>Alternative Theme Colors</h2> <theme-demo-colors [colors]="alternativeThemeColors"></theme-demo-colors> <h2>Surface Colors</h2> <p> The following colors should be used for backgrounds and large, low-emphasis areas of the screen. </p> <p> Containers filled with a surface color should apply the <span class="demo-surface-variable">--mat-sys-on-surface</span> color to text and icons placed within. </p> <theme-demo-colors [colors]="surfaceColors"></theme-demo-colors> <h2>Fixed Colors</h2> <p> These colors are the same for both light and dark themes. They are unused by any Angular Material components. </p> <theme-demo-colors [colors]="fixedColors"></theme-demo-colors> </mat-expansion-panel> <h1>Typography</h1> <p> There are five categories of font types defined by Material Design: body, display, headline, label, and title. Each category has three sizes: small, medium, and large. </p> <p> Learn more about how these categories and their sizes should be used in your application by visiting Material Design's <a href="https://m3.material.io/styles/typography/overview">Typography</a> documentation. </p> @for (category of ['body', 'display', 'headline', 'label', 'title']; track $index) { <div class="demo-typography-group"> <div class="demo-typography-title">{{category}}</div> @for (size of ['small', 'medium', 'large']; track $index) { <div class="demo-typography-example"> <div class="demo-typography-variable"> <div class="demo-surface-variable">--mat-sys-{{category}}-{{size}}</div> </div> <div class="demo-typography-text" [style.font]="'var(--mat-sys-' + category + '-' + size + ')'">Lorem ipsum dolor</div> </div> } </div> } <p> Each variable can be applied to the `font` CSS style. Additionally, the parts of the variable definition can be accessed individually by appending the keywords "font", "line-height", "size", "tracking", and "weight". </p> <p> For example, the values for medium body text may be defined as follows: </p> <pre class="demo-code-block"> --mat-sys-body-medium: 400 0.875rem / 1.25rem Roboto, sans-serif; --mat-sys-body-medium-font: Roboto, sans-serif; --mat-sys-body-medium-line-height: 1.25rem; --mat-sys-body-medium-size: 0.875rem; --mat-sys-body-medium-tracking: 0.016rem; --mat-sys-body-medium-weight: 400; </pre> <h1>Elevation</h1>
115384
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { afterNextRender, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, inject, Injector, ViewChild, } from '@angular/core'; import {FormsModule} from '@angular/forms'; import {MatButtonModule} from '@angular/material/button'; import {MatDividerModule} from '@angular/material/divider'; import {MatFormFieldModule} from '@angular/material/form-field'; import {MatIconModule} from '@angular/material/icon'; import {MatInputModule} from '@angular/material/input'; import {MatPaginator, MatPaginatorModule} from '@angular/material/paginator'; import {MatSelectModule} from '@angular/material/select'; import {MatTableDataSource, MatTableModule} from '@angular/material/table'; @Component({ selector: 'performance-demo', templateUrl: 'performance-demo.html', styleUrl: 'performance-demo.css', imports: [ FormsModule, MatButtonModule, MatDividerModule, MatFormFieldModule, MatIconModule, MatInputModule, MatPaginatorModule, MatSelectModule, MatTableModule, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class PerformanceDemo implements AfterViewInit { /** Controls the rendering of components. */ show = false; /** The number of times metrics will be gathered. */ sampleSize = 100; /** The number of components being rendered. */ componentCount = 100; /** A flat array of every sample recorded. */ allSamples: number[] = []; /** Used to disable benchmark controls while a benchmark is being run. */ isRunningBenchmark = false; /** The columns in the metrics table. */ displayedColumns: string[] = ['index', 'time']; /** Basically the same thing as allSamples but organized as a mat-table data source. */ dataSource = new MatTableDataSource<{index: number; time: string}>(); /** The average plus/minus the stdev. */ computedResults = ''; /** Used in an `@for` to render the desired number of comonents. */ componentArray = [].constructor(this.componentCount); private _injector = inject(Injector); readonly cdr = inject(ChangeDetectorRef); /** The standard deviation of the recorded samples. */ get stdev(): number | undefined { if (!this.allSamples.length) { return undefined; } return Math.sqrt( this.allSamples.map(x => Math.pow(x - this.mean!, 2)).reduce((a, b) => a + b) / this.allSamples.length, ); } /** The average value of the recorded samples. */ get mean(): number | undefined { if (!this.allSamples.length) { return undefined; } return this.allSamples.reduce((a, b) => a + b) / this.allSamples.length; } @ViewChild(MatPaginator) paginator?: MatPaginator; ngAfterViewInit() { this.dataSource.paginator = this.paginator!; } getTotalRenderTime(): string { return this.allSamples.length ? `${this.format(this.mean!)} ± ${this.format(this.stdev!)}` : ''; } format(num: number): string { const roundedNum = Math.round(num * 100) / 100; return roundedNum >= 10 ? roundedNum.toFixed(2) : '0' + roundedNum.toFixed(2); } async runBenchmark(): Promise<void> { this.isRunningBenchmark = true; const samples = []; for (let i = 0; i < this.sampleSize; i++) { samples.push(await this.recordSample()); } this.dataSource.data = this.dataSource.data.concat( samples.map((sample, i) => ({ index: this.allSamples.length + i, time: this.format(sample), })), ); this.allSamples.push(...samples); this.isRunningBenchmark = false; this.computedResults = this.getTotalRenderTime(); this.cdr.markForCheck(); } clearMetrics() { this.allSamples = []; this.dataSource.data = []; this.computedResults = this.getTotalRenderTime(); } recordSample(): Promise<number> { return new Promise(res => { setTimeout(() => { this.show = true; this.cdr.markForCheck(); const start = performance.now(); afterNextRender( () => { const end = performance.now(); this.show = false; this.cdr.markForCheck(); res(end - start); }, {injector: this._injector}, ); }); }); } }
115390
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {Directionality} from '@angular/cdk/bidi'; import { ChangeDetectionStrategy, Component, TemplateRef, ViewChild, ViewEncapsulation, inject, } from '@angular/core'; import {FormsModule} from '@angular/forms'; import {MatButtonModule} from '@angular/material/button'; import {MatCheckboxModule} from '@angular/material/checkbox'; import {MatInputModule} from '@angular/material/input'; import {MatSelectModule} from '@angular/material/select'; import { MatSnackBar, MatSnackBarConfig, MatSnackBarHorizontalPosition, MatSnackBarVerticalPosition, } from '@angular/material/snack-bar'; @Component({ selector: 'snack-bar-demo', templateUrl: 'snack-bar-demo.html', styleUrl: 'snack-bar-demo.css', encapsulation: ViewEncapsulation.None, imports: [FormsModule, MatButtonModule, MatCheckboxModule, MatInputModule, MatSelectModule], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SnackBarDemo { snackBar = inject(MatSnackBar); private _dir = inject(Directionality); @ViewChild('template') template: TemplateRef<any>; message = 'Snack Bar opened.'; actionButtonLabel = 'Retry'; action = false; setAutoHide = true; autoHide = 10000; addExtraClass = false; horizontalPosition: MatSnackBarHorizontalPosition = 'center'; verticalPosition: MatSnackBarVerticalPosition = 'bottom'; open() { const config = this._createConfig(); this.snackBar.open(this.message, this.action ? this.actionButtonLabel : undefined, config); } openTemplate() { const config = this._createConfig(); this.snackBar.openFromTemplate(this.template, config); } private _createConfig() { const config = new MatSnackBarConfig(); config.verticalPosition = this.verticalPosition; config.horizontalPosition = this.horizontalPosition; config.duration = this.setAutoHide ? this.autoHide : 0; config.panelClass = this.addExtraClass ? ['demo-party'] : undefined; config.direction = this._dir.value; return config; } }
115418
import {bootstrapApplication, provideClientHydration} from '@angular/platform-browser'; import {provideAnimations} from '@angular/platform-browser/animations'; import {AUTOMATED_KITCHEN_SINK, KitchenSink} from './kitchen-sink/kitchen-sink'; bootstrapApplication(KitchenSink, { providers: [ provideAnimations(), provideClientHydration(), { provide: AUTOMATED_KITCHEN_SINK, useValue: false, }, ], });
115426
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Angular Material Universal Kitchen Sink Test</title> <link href="styles.css" rel="stylesheet"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet"> <base href="/"> </head> <body class="mat-app-background mat-typography"> <kitchen-sink>Loading...</kitchen-sink> <script src="zone.js/bundles/zone.umd.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?libraries=visualization"></script> <script src="https://unpkg.com/@googlemaps/markerclustererplus/dist/index.min.js"></script> <script src="client_bundle/main.js" type="module"></script> </body> </html>
115769
@Component({ selector: 'mat-option', exportAs: 'matOption', host: { 'role': 'option', '[class.mdc-list-item--selected]': 'selected', '[class.mat-mdc-option-multiple]': 'multiple', '[class.mat-mdc-option-active]': 'active', '[class.mdc-list-item--disabled]': 'disabled', '[id]': 'id', // Set aria-selected to false for non-selected items and true for selected items. Conform to // [WAI ARIA Listbox authoring practices guide]( // https://www.w3.org/WAI/ARIA/apg/patterns/listbox/), "If any options are selected, each // selected option has either aria-selected or aria-checked set to true. All options that are // selectable but not selected have either aria-selected or aria-checked set to false." Align // aria-selected implementation of Chips and List components. // // Set `aria-selected="false"` on not-selected listbox options to fix VoiceOver announcing // every option as "selected" (#21491). '[attr.aria-selected]': 'selected', '[attr.aria-disabled]': 'disabled.toString()', '(click)': '_selectViaInteraction()', '(keydown)': '_handleKeydown($event)', 'class': 'mat-mdc-option mdc-list-item', }, styleUrl: 'option.css', templateUrl: 'option.html', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, imports: [MatPseudoCheckbox, MatRipple], }) export class MatOption<T = any> implements FocusableOption, AfterViewChecked, OnDestroy { private _element = inject<ElementRef<HTMLElement>>(ElementRef); _changeDetectorRef = inject(ChangeDetectorRef); private _parent = inject<MatOptionParentComponent>(MAT_OPTION_PARENT_COMPONENT, {optional: true}); group = inject<MatOptgroup>(MAT_OPTGROUP, {optional: true}); private _signalDisableRipple = false; private _selected = false; private _active = false; private _disabled = false; private _mostRecentViewValue = ''; /** Whether the wrapping component is in multiple selection mode. */ get multiple() { return this._parent && this._parent.multiple; } /** Whether or not the option is currently selected. */ get selected(): boolean { return this._selected; } /** The form value of the option. */ @Input() value: T; /** The unique ID of the option. */ @Input() id: string = `mat-option-${_uniqueIdCounter++}`; /** Whether the option is disabled. */ @Input({transform: booleanAttribute}) get disabled(): boolean { return (this.group && this.group.disabled) || this._disabled; } set disabled(value: boolean) { this._disabled = value; } /** Whether ripples for the option are disabled. */ get disableRipple(): boolean { return this._signalDisableRipple ? (this._parent!.disableRipple as Signal<boolean>)() : !!this._parent?.disableRipple; } /** Whether to display checkmark for single-selection. */ get hideSingleSelectionIndicator(): boolean { return !!(this._parent && this._parent.hideSingleSelectionIndicator); } /** Event emitted when the option is selected or deselected. */ // tslint:disable-next-line:no-output-on-prefix @Output() readonly onSelectionChange = new EventEmitter<MatOptionSelectionChange<T>>(); /** Element containing the option's text. */ @ViewChild('text', {static: true}) _text: ElementRef<HTMLElement> | undefined; /** Emits when the state of the option changes and any parents have to be notified. */ readonly _stateChanges = new Subject<void>(); constructor(...args: unknown[]); constructor() { inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader); inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader); this._signalDisableRipple = !!this._parent && isSignal(this._parent.disableRipple); } /** * Whether or not the option is currently active and ready to be selected. * An active option displays styles as if it is focused, but the * focus is actually retained somewhere else. This comes in handy * for components like autocomplete where focus must remain on the input. */ get active(): boolean { return this._active; } /** * The displayed value of the option. It is necessary to show the selected option in the * select's trigger. */ get viewValue(): string { // TODO(kara): Add input property alternative for node envs. return (this._text?.nativeElement.textContent || '').trim(); } /** Selects the option. */ select(emitEvent = true): void { if (!this._selected) { this._selected = true; this._changeDetectorRef.markForCheck(); if (emitEvent) { this._emitSelectionChangeEvent(); } } } /** Deselects the option. */ deselect(emitEvent = true): void { if (this._selected) { this._selected = false; this._changeDetectorRef.markForCheck(); if (emitEvent) { this._emitSelectionChangeEvent(); } } } /** Sets focus onto this option. */ focus(_origin?: FocusOrigin, options?: FocusOptions): void { // Note that we aren't using `_origin`, but we need to keep it because some internal consumers // use `MatOption` in a `FocusKeyManager` and we need it to match `FocusableOption`. const element = this._getHostElement(); if (typeof element.focus === 'function') { element.focus(options); } } /** * This method sets display styles on the option to make it appear * active. This is used by the ActiveDescendantKeyManager so key * events will display the proper options as active on arrow key events. */ setActiveStyles(): void { if (!this._active) { this._active = true; this._changeDetectorRef.markForCheck(); } } /** * This method removes display styles on the option that made it appear * active. This is used by the ActiveDescendantKeyManager so key * events will display the proper options as active on arrow key events. */ setInactiveStyles(): void { if (this._active) { this._active = false; this._changeDetectorRef.markForCheck(); } } /** Gets the label to be used when determining whether the option should be focused. */ getLabel(): string { return this.viewValue; } /** Ensures the option is selected when activated from the keyboard. */ _handleKeydown(event: KeyboardEvent): void { if ((event.keyCode === ENTER || event.keyCode === SPACE) && !hasModifierKey(event)) { this._selectViaInteraction(); // Prevent the page from scrolling down and form submits. event.preventDefault(); } } /** * `Selects the option while indicating the selection came from the user. Used to * determine if the select's view -> model callback should be invoked.` */ _selectViaInteraction(): void { if (!this.disabled) { this._selected = this.multiple ? !this._selected : true; this._changeDetectorRef.markForCheck(); this._emitSelectionChangeEvent(true); } } /** Returns the correct tabindex for the option depending on disabled state. */ // This method is only used by `MatLegacyOption`. Keeping it here to avoid breaking the types. // That's because `MatLegacyOption` use `MatOption` type in a few places such as // `MatOptionSelectionChange`. It is safe to delete this when `MatLegacyOption` is deleted. _getTabIndex(): string { return this.disabled ? '-1' : '0'; } /** Gets the host DOM element. */ _getHostElement(): HTMLElement { return this._element.nativeElement; } ngAfterViewChecked() { // Since parent components could be using the option's label to display the selected values // (e.g. `mat-select`) and they don't have a way of knowing if the option's label has changed // we have to check for changes in the DOM ourselves and dispatch an event. These checks are // relatively cheap, however we still limit them only to selected options in order to avoid // hitting the DOM too often. if (this._selected) { const viewValue = this.viewValue; if (viewValue !== this._mostRecentViewValue) { if (this._mostRecentViewValue) { this._stateChanges.next(); } this._mostRecentViewValue = viewValue; } } } ngOnDestroy() { this._stateChanges.complete(); } /** Emits the selection change event. */ private _emitSelectionChangeEvent(isUserInput = false): void { this.onSelectionChange.emit(new MatOptionSelectionChange<T>(this, isUserInput)); } }
115793
( 0: #000000, 10: #1a1c18, 20: #2f312c, 25: #3a3c37, 30: #464742, 35: #52534e, 40: #5e5f5a, 50: #767872, 60: #90918b, 70: #abaca5, 80: #c7c7c0, 90: #e3e3dc, 95: #f1f1ea, 98: #fafaf2, 99: #fdfdf5, 100: #ffffff, 4: #0c0f0b, 6: #121410, 12: #1e201c, 17: #282b26, 22: #333531, 24: #383a35, 87: #dadbd3, 92: #e8e9e1, 94: #eeeee7, 96: #f3f4ed, ), neutral-variant: ( 0: #000000, 10: #181d14, 20: #2d3228, 25: #383d33, 30: #44483e, 35: #4f5449, 40: #5b6055, 50: #74796d, 60: #8e9286, 70: #a8ada0, 80: #c4c8bb, 90: #e0e4d6, 95: #eef2e4, 98: #f7fbec, 99: #fafeef, 100: #ffffff, ), )); /// Spring Green color palette to be used as primary or tertiary palette. $spring-green-palette: _patch-error-palette(( 0: #000000, 10: #00210b, 20: #003917, 25: #00461e, 30: #005225, 35: #00602c, 40: #006d33, 50: #008942, 60: #00a751, 70: #00c561, 80: #00e472, 90: #63ff94, 95: #c4ffcb, 98: #eaffe9, 99: #f5fff2, 100: #ffffff, secondary: ( 0: #000000, 10: #0e1f12, 20: #233425, 25: #2e4030, 30: #394b3b, 35: #445746, 40: #506352, 50: #697c6a, 60: #829682, 70: #9cb19c, 80: #b7ccb7, 90: #d3e8d2, 95: #e1f6e0, 98: #eaffe9, 99: #f5fff2, 100: #ffffff, ), neutral: ( 0: #000000, 10: #191c19, 20: #2e312e, 25: #393c39, 30: #454744, 35: #51534f, 40: #5d5f5b, 50: #757873, 60: #8f918d, 70: #aaaca7, 80: #c5c7c2, 90: #e2e3de, 95: #f0f1ec, 98: #f9faf4, 99: #fcfdf7, 100: #ffffff, 4: #0c0f0c, 6: #111411, 12: #1d201d, 17: #282b27, 22: #323632, 24: #373a36, 87: #d9dbd5, 92: #e7e9e3, 94: #edefe8, 96: #f2f4ee, ), neutral-variant: ( 0: #000000, 10: #161d17, 20: #2b322b, 25: #363d36, 30: #414941, 35: #4d544c, 40: #596058, 50: #717970, 60: #8b9389, 70: #a6ada4, 80: #c1c9be, 90: #dde5da, 95: #ebf3e8, 98: #f4fcf0, 99: #f7fef3, 100: #ffffff, ), )); /// Azure color palette to be used as primary or tertiary palette. $azure-palette: _patch-error-palette(( 0: #000000, 10: #001b3f, 20: #002f65, 25: #003a7a, 30: #00458f, 35: #0050a5, 40: #005cbb, 50: #0074e9, 60: #438fff, 70: #7cabff, 80: #abc7ff, 90: #d7e3ff, 95: #ecf0ff, 98: #f9f9ff, 99: #fdfbff, 100: #ffffff, secondary: ( 0: #000000, 10: #131c2b, 20: #283041, 25: #333c4d, 30: #3e4759, 35: #4a5365, 40: #565e71, 50: #6f778b, 60: #8891a5, 70: #a3abc0, 80: #bec6dc, 90: #dae2f9, 95: #ecf0ff, 98: #f9f9ff, 99: #fdfbff, 100: #ffffff, ), neutral: ( 0: #000000, 10: #1a1b1f, 20: #2f3033, 25: #3b3b3f, 30: #46464a, 35: #525256, 40: #5e5e62, 50: #77777a, 60: #919094, 70: #ababaf, 80: #c7c6ca, 90: #e3e2e6, 95: #f2f0f4, 98: #faf9fd, 99: #fdfbff, 100: #ffffff, 4: #0d0e11, 6: #121316, 12: #1f2022, 17: #292a2c, 22: #343537, 24: #38393c, 87: #dbd9dd, 92: #e9e7eb, 94: #efedf0, 96: #f4f3f6, ), neutral-variant: ( 0: #000000, 10: #181c22, 20: #2d3038, 25: #383b43, 30: #44474e, 35: #4f525a, 40: #5b5e66, 50: #74777f, 60: #8e9099, 70: #a9abb4, 80: #c4c6d0, 90: #e0e2ec, 95: #eff0fa, 98: #f9f9ff, 99: #fdfbff, 100: #ffffff, ), )); /// Violet color palette to be used as primary or tertiary palette. $violet-palette: _patch-error-palette(( 0: #000000, 10: #270057, 20: #42008a, 25: #5000a4, 30:
115794
#5f00c0, 35: #6e00dc, 40: #7d00fa, 50: #944aff, 60: #a974ff, 70: #bf98ff, 80: #d5baff, 90: #ecdcff, 95: #f7edff, 98: #fef7ff, 99: #fffbff, 100: #ffffff, secondary: ( 0: #000000, 10: #1f182a, 20: #352d40, 25: #40384c, 30: #4b4357, 35: #574f63, 40: #645b70, 50: #7d7389, 60: #978ca4, 70: #b2a7bf, 80: #cec2db, 90: #eadef7, 95: #f7edff, 98: #fef7ff, 99: #fffbff, 100: #ffffff, ), neutral: ( 0: #000000, 10: #1d1b1e, 20: #323033, 25: #3d3a3e, 30: #49464a, 35: #545155, 40: #605d61, 50: #7a767a, 60: #948f94, 70: #aeaaae, 80: #cac5ca, 90: #e6e1e6, 95: #f5eff4, 98: #fef8fc, 99: #fffbff, 100: #ffffff, 4: #0f0d11, 6: #151316, 12: #211f22, 17: #2b292d, 22: #363437, 24: #3b383c, 87: #ded8dd, 92: #ede6eb, 94: #f2ecf1, 96: #f8f2f6, ), neutral-variant: ( 0: #000000, 10: #1d1a22, 20: #332f37, 25: #3e3a42, 30: #49454e, 35: #55515a, 40: #615c66, 50: #7b757f, 60: #958e99, 70: #b0a9b3, 80: #cbc4cf, 90: #e8e0eb, 95: #f6eef9, 98: #fef7ff, 99: #fffbff, 100: #ffffff, ), )); /// Rose color palette to be used as primary or tertiary palette. $rose-palette: _patch-error-palette(( 0: #000000, 10: #3f001b, 20: #65002f, 25: #7a003a, 30: #8f0045, 35: #a40050, 40: #ba005c, 50: #e80074, 60: #ff4a8e, 70: #ff84a9, 80: #ffb1c5, 90: #ffd9e1, 95: #ffecef, 98: #fff8f8, 99: #fffbff, 100: #ffffff, secondary: ( 0: #000000, 10: #2b151b, 20: #422930, 25: #4f343b, 30: #5b3f46, 35: #684b52, 40: #74565d, 50: #8f6f76, 60: #aa888f, 70: #c6a2aa, 80: #e3bdc5, 90: #ffd9e1, 95: #ffecef, 98: #fff8f8, 99: #fffbff, 100: #ffffff, ), neutral: ( 0: #000000, 10: #201a1b, 20: #352f30, 25: #413a3b, 30: #4c4546, 35: #585052, 40: #655c5e, 50: #7e7576, 60: #988e90, 70: #b3a9aa, 80: #cfc4c5, 90: #ece0e1, 95: #faeeef, 98: #fff8f8, 99: #fffbff, 100: #ffffff, 4: #120d0e, 6: #171213, 12: #241e1f, 17: #2f2829, 22: #3a3334, 24: #3e3738, 87: #e3d7d8, 92: #f1e5e6, 94: #f7ebec, 96: #fdf1f2, ), neutral-variant: ( 0: #000000, 10: #24191b, 20: #3a2d30, 25: #45383b, 30: #514346, 35: #5d4f52, 40: #6a5a5e, 50: #847376, 60: #9e8c90, 70: #baa7aa, 80: #d6c2c5, 90: #f3dde1, 95: #ffecef, 98: #fff8f8, 99: #fffbff, 100: #ffffff, ), ));
115795
// This file contains functions used to define Angular Material theme objects. @use 'sass:map'; @use '../style/sass-utils'; @use './palettes'; @use '../tokens/m3-tokens'; @use './config-validation'; // Prefix used for component token fallback variables, e.g. // `color: var(--mdc-text-button-label-text-color, var(--mat-sys-primary));` $system-fallback-prefix: mat-sys; // Default system level prefix to use when directly calling the `system-level-*` mixins. // Prefix used for component token fallback variables, e.g. // `color: var(--mdc-text-button-label-text-color, var(--mat-sys-primary));` // TODO: Remove this variable after internal clients are migrated from "sys" $system-level-prefix: mat-sys; /// Map key used to store internals of theme config. $internals: _mat-theming-internals-do-not-access; /// The theme version of generated themes. $theme-version: 1; /// Defines an Angular Material theme object with color, typography, and density settings. /// @param {Map} $config The theme configuration /// @return {Map} A theme object @function define-theme($config: ()) { $err: config-validation.validate-theme-config($config); @if $err { @error $err; } @return sass-utils.deep-merge-all( define-colors(map.get($config, color) or ()), define-typography(map.get($config, typography) or ()), define-density(map.get($config, density) or ()), ($internals: (base-tokens: m3-tokens.generate-base-tokens())), ); } /// Defines an Angular Material theme object with color settings. /// @param {Map} $config The color configuration /// @return {Map} A theme object @function define-colors($config: ()) { $err: config-validation.validate-color-config($config); @if $err { @error $err; } $type: map.get($config, theme-type) or light; $primary: map.get($config, primary) or palettes.$violet-palette; $tertiary: map.get($config, tertiary) or $primary; $system-variables-prefix: map.get($config, system-variables-prefix) or $system-level-prefix; sass-utils.$use-system-color-variables: map.get($config, use-system-variables) or false; @return ( $internals: ( theme-version: $theme-version, theme-type: $type, palettes: ( primary: map.remove($primary, neutral, neutral-variant, secondary), secondary: map.get($primary, secondary), tertiary: map.remove($tertiary, neutral, neutral-variant, secondary), neutral: map.get($primary, neutral), neutral-variant: map.get($primary, neutral-variant), error: map.get($primary, error), ), color-system-variables-prefix: $system-variables-prefix, color-tokens: m3-tokens.generate-color-tokens( $type, $primary, $tertiary, map.get($primary, error), $system-variables-prefix) ) ); } /// Defines an Angular Material theme object with typography settings. /// @param {Map} $config The typography configuration /// @return {Map} A theme object @function define-typography($config: ()) { $err: config-validation.validate-typography-config($config); @if $err { @error $err; } $plain: map.get($config, plain-family) or (Roboto, sans-serif); $brand: map.get($config, brand-family) or $plain; $bold: map.get($config, bold-weight) or 700; $medium: map.get($config, medium-weight) or 500; $regular: map.get($config, regular-weight) or 400; $system-variables-prefix: map.get($config, system-variables-prefix) or $system-level-prefix; sass-utils.$use-system-typography-variables: map.get($config, use-system-variables) or false; @return ( $internals: ( theme-version: $theme-version, font-definition: ( plain: $plain, brand: $brand, bold: $bold, medium: $medium, regular: $regular, ), typography-system-variables-prefix: $system-variables-prefix, typography-tokens: m3-tokens.generate-typography-tokens( $brand, $plain, $bold, $medium, $regular, $system-variables-prefix) ) ); } /// Defines an Angular Material theme object with density settings. /// @param {Map} $config The density configuration /// @return {Map} A theme object @function define-density($config: ()) { $err: config-validation.validate-density-config($config); @if $err { @error $err; } $density-scale: map.get($config, scale) or 0; @return ( $internals: ( theme-version: $theme-version, density-scale: $density-scale, density-tokens: m3-tokens.generate-density-tokens($density-scale) ) ); }
115797
@use 'sass:list'; @use 'sass:map'; @use '../style/validation'; @use './m2-inspection'; $_internals: _mat-theming-internals-do-not-access; $_m3-typescales: ( display-large, display-medium, display-small, headline-large, headline-medium, headline-small, title-large, title-medium, title-small, label-large, label-medium, label-small, body-large, body-medium, body-small, ); $_typography-properties: (font, font-family, line-height, font-size, letter-spacing, font-weight); /// Validates that the given value is a versioned theme object. /// @param {Any} $theme The theme object to validate. /// @return {Boolean|Null} true if the theme has errors, else null. @function _validate-theme-object($theme) { $err: validation.validate-type($theme, 'map') or map.get($theme, $_internals, theme-version) == null; @return if($err, true, null); } /// Gets the version number of a theme object. A theme that is not a valid versioned theme object is /// considered to be version 0. /// @param {Map} $theme The theme to check the version of /// @return {Number} The version number of the theme (0 if unknown). @function get-theme-version($theme) { $err: _validate-theme-object($theme); @return if($err, 0, map.get($theme, $_internals, theme-version) or 0); } /// Gets the type of theme represented by a theme object (light or dark). /// @param {Map} $theme The theme /// @return {String} The type of theme (either `light` or `dark`). @function get-theme-type($theme) { $version: get-theme-version($theme); @if $version == 0 { @return m2-inspection.get-theme-type($theme); } @else if $version == 1 { @if not theme-has($theme, color) { @error 'Color information is not available on this theme.'; } @return map.get($theme, $_internals, theme-type) or light; } @else { @error #{'Unrecognized theme version:'} $version; } } /// Gets a color from a theme object. This function can take 2 or 3 arguments. If 2 arguments are /// passed, the second argument is treated as the name of a color role. If 3 arguments are passed, /// the second argument is treated as the name of a color palette (primary, secondary, etc.) and the /// third is treated as the palette hue (10, 50, etc.) /// @param {Map} $theme The theme /// @param {String} $color-role-or-palette-name The name of the color role to get, or the name of a /// color palette. /// @param {Number} $hue The palette hue to get (passing this argument means the second argument is /// interpreted as a palette name). /// @return {Color} The requested theme color. @function get-theme-color($theme, $args...) { $version: get-theme-version($theme); $args-count: list.length($args); @if $args-count != 1 and $args-count != 2 and $args-count != 3 { @error #{'Expected between 2 and 4 arguments. Got:'} $args-count + 1; }
115798
@if $version == 0 { @return m2-inspection.get-theme-color($theme, $args...); } @else if $version == 1 { @if $args-count == 1 { @return _get-theme-role-color($theme, $args...); } @else if $args-count == 2 { @return _get-theme-palette-color($theme, $args...); } } @else { @error #{'Unrecognized theme version:'} $version; } } /// Gets a role color from a theme object. /// @param {Map} $theme The theme /// @param {String} $color-role-name The name of the color role to get. /// @return {Color} The requested role color. @function _get-theme-role-color($theme, $color-role-name) { $err: _validate-theme-object($theme); @if $err { // TODO(mmalerba): implement for old style theme objects. @error #{'get-theme-color does not support legacy theme objects.'}; } @if not theme-has($theme, color) { @error 'Color information is not available on this theme.'; } $color-roles: map.get($theme, $_internals, color-tokens, (mdc, theme)); $result: map.get($color-roles, $color-role-name); @if not $result { @error #{'Valid color roles are: #{map.keys($color-roles)}. Got:'} $color-role-name; } @return $result; } /// Gets a palette color from a theme object. /// @param {Map} $theme The theme /// @param {String} $palette-name The name of the palette to get the color from. /// @param {Number} $hue The hue to read from the palette. /// @return {Color} The requested palette color. @function _get-theme-palette-color($theme, $palette-name, $hue) { $err: _validate-theme-object($theme); @if $err { // TODO(mmalerba): implement for old style theme objects. @error #{'get-theme-color does not support legacy theme objects.'}; } @if not theme-has($theme, color) { @error 'Color information is not available on this theme.'; } $palettes: map.get($theme, $_internals, palettes); $palette: map.get($palettes, $palette-name); @if not $palette { $supported-palettes: map.keys($palettes); @error #{'Valid palettes are: #{$supported-palettes}. Got:'} $palette-name; } $result: map.get($palette, $hue); @if not $result { $supported-hues: map.keys($palette); @error #{'Valid hues for'} $palette-name #{'are: #{$supported-hues}. Got:'} $hue; } @return $result; } /// Gets a typography value from a theme object. /// @param {Map} $theme The theme /// @param {String} $typescale The typescale name. /// @param {String} $property The CSS font property to get /// (font, font-family, font-size, font-weight, line-height, or letter-spacing). /// @return {*} The value of the requested font property. @function get-theme-typography($theme, $typescale, $property: font) { $version: get-theme-version($theme); @if $version == 0 { @return m2-inspection.get-theme-typography($theme, $typescale, $property); } @else if $version == 1 { @if not theme-has($theme, typography) { @error 'Typography information is not available on this theme.'; } @if not list.index($_m3-typescales, $typescale) { @error #{'Valid typescales are: #{$_m3-typescales}. Got:'} $typescale; } @if not list.index($_typography-properties, $property) { @error #{'Valid typography properties are: #{$_typography-properties}. Got:'} $property; } $property-key: map.get(( font: '', font-family: '-font', line-height: '-line-height', font-size: '-size', letter-spacing: '-tracking', font-weight: '-weight' ), $property); $token-name: '#{$typescale}#{$property-key}'; @return map.get($theme, $_internals, typography-tokens, (mdc, typography), $token-name); } @else { @error #{'Unrecognized theme version:'} $version; } } /// Gets the density scale from a theme object. /// @param {Map} $theme The theme /// @return {Number} The density scale. @function get-theme-density($theme) { $version: get-theme-version($theme); @if $version == 0 { @return m2-inspection.get-theme-density($theme); } @else if $version == 1 { @if not theme-has($theme, density) { @error 'Density information is not available on this theme.'; } @return map.get($theme, $_internals, density-scale); } @else { @error #{'Unrecognized theme version:'} $version; } } /// Checks whether the theme has information about given theming system. /// @param {Map} $theme The theme /// @param {String} $system The system to check /// @param {Boolean} Whether the theme has information about the system. @function theme-has($theme, $system) { $version: get-theme-version($theme); @if $version == 0 { @return m2-inspection.theme-has($theme, $system); } @else if $version == 1 { @if $system == base { @return map.get($theme, $_internals, base-tokens) != null; } @if $system == color { @return map.get($theme, $_internals, color-tokens) != null and map.get($theme, $_internals, theme-type) != null and map.get($theme, $_internals, palettes) != null; } @if $system == typography { @return map.get($theme, $_internals, typography-tokens) != null; } @if $system == density { @return map.get($theme, $_internals, density-scale) != null; } @error 'Valid systems are: base, color, typography, density. Got:' $system; } @else { @error #{'Unrecognized theme version:'} $version; } } /// Removes the information about the given theming system(s) from the given theme. /// @param {Map} $theme The theme to remove information from /// @param {String...} $systems The systems to remove /// @return {Map} A version of the theme without the removed theming systems. @function theme-remove($theme, $systems...) { $err: validation.validate-allowed-values($systems, color, typography, density, base); @if $err { @error #{'Expected $systems to contain valid system names (color, typography, density, or'} #{'base). Got invalid system names:'} $err; } $version: get-theme-version($theme); @if $version == 0 { @return m2-inspection.theme-remove($theme, $systems...); } @else if $version == 1 { @each $system in $systems { @if $system == base { $theme: map.deep-remove($theme, $_internals, base-tokens); } @else if $system == color { $theme: map.deep-remove($theme, $_internals, color-tokens); $theme: map.deep-remove($theme, $_internals, theme-type); $theme: map.deep-remove($theme, $_internals, palettes); } @else if $system == typography { $theme: map.deep-remove($theme, $_internals, typography-tokens); } @else if $system == density { $theme: map.deep-remove($theme, $_internals, density-scale); $theme: map.deep-remove($theme, $_internals, density-tokens); } } @return $theme; } } /// Gets the set of tokens from the given theme, limited to those affected by the requested theming /// systems. /// @param {Map} $theme The theme to get tokens from. /// @param {String...} $systems The theming systems to get tokens for. Valid values are: color, /// typography, density, base. If no systems are passed, all tokens will be returned. /// @return {Map} The requested tokens for the theme.
115808
describe('theming definition api', () => { describe('define-theme', () => { it('should fill in defaults', () => { const css = transpile(` $theme: mat.define-theme(); $data: map.get($theme, $internals); :root { --keys: #{map.keys($data)}; --version: #{map.get($data, theme-version)}; --type: #{map.get($data, theme-type)}; --palettes: #{map.keys(map.get($data, palettes))}; --density: #{map.get($data, density-scale)}; --base-tokens: #{list.length(map.get($data, base-tokens)) > 0}; --color-tokens: #{list.length(map.get($data, color-tokens)) > 0}; --typography-tokens: #{list.length(map.get($data, typography-tokens)) > 0}; --density-tokens: #{list.length(map.get($data, density-tokens)) > 0}; --color-system-variables-prefix: #{map.get($data, color-system-variables-prefix)}; --typography-system-variables-prefix: #{map.get($data, typography-system-variables-prefix)}; } `); const vars = getRootVars(css); expect(vars['keys'].split(', ')).toEqual([ 'theme-version', 'theme-type', 'palettes', 'color-system-variables-prefix', 'color-tokens', 'font-definition', 'typography-system-variables-prefix', 'typography-tokens', 'density-scale', 'density-tokens', 'base-tokens', ]); expect(vars['version']).toBe('1'); expect(vars['type']).toBe('light'); expect(vars['palettes'].split(', ')).toEqual([ 'primary', 'secondary', 'tertiary', 'neutral', 'neutral-variant', 'error', ]); expect(vars['density']).toBe('0'); expect(vars['base-tokens']).toBe('true'); expect(vars['color-tokens']).toBe('true'); expect(vars['typography-tokens']).toBe('true'); expect(vars['density-tokens']).toBe('true'); expect(vars['typography-system-variables-prefix']).toBe('mat-sys'); expect(vars['color-system-variables-prefix']).toBe('mat-sys'); }); it('should customize colors', () => { const css = transpile(` $theme: mat.define-theme(( color: ( theme-type: dark, primary: mat.$yellow-palette, tertiary: mat.$red-palette, ) )); $data: map.get($theme, $internals); :root { --token-surface: #{map.get($data, color-tokens, (mdc, theme), surface)}; --token-primary: #{map.get($data, color-tokens, (mdc, theme), primary)}; --token-secondary: #{map.get($data, color-tokens, (mdc, theme), secondary)}; --token-tertiary: #{map.get($data, color-tokens, (mdc, theme), tertiary)}; --palette-primary: #{map.get($data, palettes, primary, 50)}; --palette-secondary: #{map.get($data, palettes, secondary, 50)}; --palette-tertiary: #{map.get($data, palettes, tertiary, 50)}; --type: #{map.get($data, theme-type)}; } `); const vars = getRootVars(css); expect(vars['token-surface']).toBe('#14140f'); expect(vars['token-primary']).toBe('#cdcd00'); expect(vars['token-secondary']).toBe('#cac8a5'); expect(vars['token-tertiary']).toBe('#ffb4a8'); expect(vars['palette-primary']).toBe('#7b7b00'); expect(vars['palette-secondary']).toBe('#7a795a'); expect(vars['palette-tertiary']).toBe('#ef0000'); expect(vars['type']).toBe('dark'); }); it('should customize typography', () => { const css = transpile(` $theme: mat.define-theme(( typography: ( brand-family: Comic Sans, plain-family: Wingdings, bold-weight: 300, medium-weight: 200, regular-weight: 100, ) )); $data: map.get($theme, $internals); :root { --display-font: #{map.get($data, typography-tokens, (mdc, typography), display-large-font)}; --display-weight: #{map.get($data, typography-tokens, (mdc, typography), display-large-weight)}; --title-font: #{map.get($data, typography-tokens, (mdc, typography), title-small-font)}; --title-weight: #{map.get($data, typography-tokens, (mdc, typography), title-small-weight)}; } `); const vars = getRootVars(css); expect(vars['display-font']).toBe('Comic Sans'); expect(vars['display-weight']).toBe('100'); expect(vars['title-font']).toBe('Wingdings'); expect(vars['title-weight']).toBe('200'); }); it('should customize density', () => { const css = transpile(` $theme: mat.define-theme(( density: ( scale: -2 ) )); $data: map.get($theme, $internals); :root { --size: #{map.get($data, density-tokens, (mdc, checkbox), state-layer-size)}; } `); const vars = getRootVars(css); expect(vars['size']).toBe('32px'); }); it('should throw for invalid system config', () => { expect(() => transpile(`$theme: mat.define-theme(5)`)).toThrowError( /\$config should be a configuration object\. Got: 5/, ); }); it('should throw for invalid color config', () => { expect(() => transpile(`$theme: mat.define-theme((color: 5))`)).toThrowError( /\$config\.color should be a color configuration object\. Got: 5/, ); }); it('should throw for invalid typography config', () => { expect(() => transpile(`$theme: mat.define-theme((typography: 5))`)).toThrowError( /\$config\.typography should be a typography configuration object\. Got: 5/, ); }); it('should throw for invalid density config', () => { expect(() => transpile(`$theme: mat.define-theme((density: 5))`)).toThrowError( /\$config\.density should be a density configuration object\. Got: 5/, ); }); it('should throw for invalid config property', () => { expect(() => transpile(`$theme: mat.define-theme((fake: 5))`)).toThrowError( /\$config has unexpected properties.*Found: fake/, ); }); it('should throw for invalid color property', () => { expect(() => transpile(`$theme: mat.define-theme((color: (fake: 5)))`)).toThrowError( /\$config\.color has unexpected properties.*Found: fake/, ); }); it('should throw for invalid typography property', () => { expect(() => transpile(`$theme: mat.define-theme((typography: (fake: 5)))`)).toThrowError( /\$config\.typography has unexpected properties.*Found: fake/, ); }); it('should throw for invalid density property', () => { expect(() => transpile(`$theme: mat.define-theme((density: (fake: 5)))`)).toThrowError( /\$config\.density has unexpected properties.*Found: fake/, ); }); it('should throw for invalid theme type', () => { expect(() => transpile(`$theme: mat.define-theme((color: (theme-type: black)))`), ).toThrowError(/Expected \$config\.color.theme-type to be one of:.*Got: black/); }); it('should throw for invalid palette', () => { expect(() => transpile(`$theme: mat.define-theme((color: (tertiary: mat.$m2-red-palette)))`), ).toThrowError(/Expected \$config\.color\.tertiary to be a valid M3 palette\. Got:/); }); it('should throw for invalid density scale', () => { expect(() => transpile(`$theme: mat.define-theme((density: (scale: 10)))`)).toThrowError( /Expected \$config\.density\.scale to be one of:.*Got: 10/, ); }); });
115815
import {compileString} from 'sass'; import {runfiles} from '@bazel/runfiles'; import * as path from 'path'; import {createLocalAngularPackageImporter} from '../../../../../tools/sass/local-sass-importer'; // Note: For Windows compatibility, we need to resolve the directory paths through runfiles // which are guaranteed to reside in the source tree. const testDir = path.join(runfiles.resolvePackageRelative('../_all-theme.scss'), '../tests'); const packagesDir = path.join(runfiles.resolveWorkspaceRelative('src/cdk/_index.scss'), '../..'); const localPackageSassImporter = createLocalAngularPackageImporter(packagesDir); /** Transpiles given Sass content into CSS. */ function transpile(content: string) { return compileString( ` @use 'sass:map'; @use '../../../index' as mat; ${content} `, { loadPaths: [testDir], importers: [localPackageSassImporter], }, ).css.toString(); } describe('theming inspection api', () => { describe('for m2 theme', () => { it('should get theme version', () => { expect( transpile(` $theme: mat.m2-define-light-theme(( color: ( primary: mat.m2-define-palette(mat.$m2-red-palette), accent: mat.m2-define-palette(mat.$m2-red-palette), warn: mat.m2-define-palette(mat.$m2-red-palette), ), typography: mat.m2-define-typography-config(), density: 0, )); div { --theme-version: #{mat.get-theme-version($theme)}; } `), ).toMatch('--theme-version: 0;'); }); it('should get theme type', () => { expect( transpile(` $theme: mat.m2-define-dark-theme(( color: ( primary: mat.m2-define-palette(mat.$m2-red-palette), accent: mat.m2-define-palette(mat.$m2-red-palette), ), )); div { --theme-type: #{mat.get-theme-type($theme)}; } `), ).toMatch('--theme-type: dark;'); }); it('should get role color', () => { expect( transpile(` $theme: mat.m2-define-light-theme(( color: ( primary: mat.m2-define-palette(mat.$m2-red-palette), accent: mat.m2-define-palette(mat.$m2-green-palette) ) )); div { color: mat.get-theme-color($theme, accent); } `), ).toMatch('color: #4caf50;'); }); it('should get palette color', () => { expect( transpile(` $theme: mat.m2-define-light-theme(( color: ( primary: mat.m2-define-palette(mat.$m2-red-palette), accent: mat.m2-define-palette(mat.$m2-green-palette) ) )); div { color: mat.get-theme-color($theme, accent, A200); } `), ).toMatch('color: #69f0ae;'); }); it('should get typography properties from theme', () => { const css = transpile(` $theme: mat.m2-define-light-theme(( typography: mat.m2-define-typography-config() )); div { font: mat.get-theme-typography($theme, headline-1); font-family: mat.get-theme-typography($theme, headline-1, font-family); font-size: mat.get-theme-typography($theme, headline-1, font-size); font-weight: mat.get-theme-typography($theme, headline-1, font-weight); line-height: mat.get-theme-typography($theme, headline-1, line-height); letter-spacing: mat.get-theme-typography($theme, headline-1, letter-spacing); } `); expect(css).toMatch('font: 300 96px / 96px Roboto, sans-serif;'); expect(css).toMatch('font-family: Roboto, sans-serif;'); expect(css).toMatch('font-size: 96px;'); expect(css).toMatch('font-weight: 300;'); expect(css).toMatch('line-height: 96px;'); expect(css).toMatch('letter-spacing: -0.015625em;'); }); it('should get density scale', () => { expect( transpile(` $theme: mat.m2-define-light-theme(( density: -1 )); div { --density-scale: #{mat.get-theme-density($theme)}; } `), ).toMatch('--density-scale: -1;'); }); it('should check what information the theme has', () => { const css = transpile(` $theme: mat.m2-define-light-theme(( color: ( primary: mat.m2-define-palette(mat.$m2-red-palette), accent: mat.m2-define-palette(mat.$m2-red-palette), ), typography: mat.m2-define-typography-config(), density: -1, )); $color-only: mat.m2-define-light-theme(( color: ( primary: mat.m2-define-palette(mat.$m2-red-palette), accent: mat.m2-define-palette(mat.$m2-red-palette), ), typography: null, density: null, )); $typography-only: mat.m2-define-light-theme(( color: null, typography: mat.m2-define-typography-config(), density: null, )); $density-only: mat.m2-define-light-theme(( color: null, typography: null, density: -1, )); div { --base: #{( mat.theme-has($theme, base), mat.theme-has($color-only, base), mat.theme-has($typography-only, base), mat.theme-has($density-only, base), )}; --color: #{( mat.theme-has($theme, color), mat.theme-has($color-only, color), mat.theme-has($typography-only, color), mat.theme-has($density-only, color), )}; --typography: #{( mat.theme-has($theme, typography), mat.theme-has($color-only, typography), mat.theme-has($typography-only, typography), mat.theme-has($density-only, typography), )}; --density: #{( mat.theme-has($theme, density), mat.theme-has($color-only, density), mat.theme-has($typography-only, density), mat.theme-has($density-only, density), )}; } `); expect(css).toMatch(/--base: true, true, true, true;/); expect(css).toMatch(/--color: true, true, false, false;/); expect(css).toMatch(/--typography: true, false, true, false;/); expect(css).toMatch(/--density: true, false, false, true;/); }); it('should work with compatibility disabled', () => { expect( transpile(` mat.$theme-legacy-inspection-api-compatibility: false; $theme: mat.m2-define-dark-theme(( color: ( primary: mat.m2-define-palette(mat.$m2-red-palette), accent: mat.m2-define-palette(mat.$m2-red-palette), ) )); div { --theme-type: #{mat.get-theme-type($theme)}; } `), ).toMatch('--theme-type: dark;'); }); it('should not allow access via legacy APIs with compatibility disabled', () => { expect(() => transpile(` mat.$theme-legacy-inspection-api-compatibility: false; $theme: mat.m2-define-dark-theme(( color: ( primary: mat.m2-define-palette(mat.$red-palette), accent: mat.m2-define-palette(mat.$red-palette), ) )); $color-config: mat.get-color-config($theme); $primary: map.get($color-config, primary); div { color: #{mat.m2-get-color-from-palette($primary)}; } `), ).toThrow(); }); });
115816
describe('for m3 theme', () => { it('should get theme version', () => { expect( transpile(` $theme: mat.define-theme(); div { --theme-version: #{mat.get-theme-version($theme)}; } `), ).toMatch('--theme-version: 1;'); }); it('should get theme type', () => { expect( transpile(` $theme: mat.define-theme(); div { --theme-type: #{mat.get-theme-type($theme)}; } `), ).toMatch('--theme-type: light;'); }); it('should get role color', () => { expect( transpile(` $theme: mat.define-theme(); div { color: mat.get-theme-color($theme, primary-container); } `), ).toMatch('color: #ecdcff;'); }); it('should error on invalid color role', () => { expect(() => transpile(` $theme: mat.define-theme(); div { color: mat.get-theme-color($theme, fake-role); } `), ).toThrowError(/Valid color roles are.*Got: fake-role/); }); it('should get palette color', () => { expect( transpile(` $theme: mat.define-theme(); div { color: mat.get-theme-color($theme, tertiary, 20); } `), ).toMatch('color: #42008a;'); }); it('should error on invalid color palette', () => { expect(() => transpile(` $theme: mat.define-theme(); div { color: mat.get-theme-color($theme, fake-palette, 20); } `), ).toThrowError(/Valid palettes are.*Got: fake-palette/); }); it('should error on invalid color hue', () => { expect(() => transpile(` $theme: mat.define-theme(); div { color: mat.get-theme-color($theme, neutral, 11); } `), ).toThrowError(/Valid hues for neutral are.*Got: 11/); }); it('should error on wrong number of get-color-theme args', () => { expect(() => transpile(` $theme: mat.define-theme(); div { color: mat.get-theme-color($theme); } `), ).toThrowError(/Expected between 2 and 4 arguments\. Got: 1/); }); it('should get typography properties from theme', () => { const css = transpile(` $theme: mat.define-theme(); div { font: mat.get-theme-typography($theme, headline-large); font-family: mat.get-theme-typography($theme, headline-large, font-family); font-size: mat.get-theme-typography($theme, headline-large, font-size); font-weight: mat.get-theme-typography($theme, headline-large, font-weight); line-height: mat.get-theme-typography($theme, headline-large, line-height); letter-spacing: mat.get-theme-typography($theme, headline-large, letter-spacing); } `); expect(css).toMatch('font: 400 2rem / 2.5rem Roboto, sans-serif;'); expect(css).toMatch('font-family: Roboto, sans-serif;'); expect(css).toMatch('font-size: 2rem;'); expect(css).toMatch('font-weight: 400;'); expect(css).toMatch('line-height: 2.5rem;'); expect(css).toMatch('letter-spacing: 0;'); }); it('should error on invalid typescale', () => { expect(() => transpile(` $theme: mat.define-theme(); div { font: mat.get-theme-typography($theme, subtitle-large); } `), ).toThrowError(/Valid typescales are:.*Got: subtitle-large/); }); it('should error on invalid typography property', () => { expect(() => transpile(` $theme: mat.define-theme(); div { text-transform: mat.get-theme-typography($theme, body-small, text-transform); } `), ).toThrowError(/Valid typography properties are:.*Got: text-transform/); }); it('should get density scale', () => { expect( transpile(` $theme: mat.define-theme(); div { --density-scale: #{mat.get-theme-density($theme)}; } `), ).toMatch('--density-scale: 0;'); }); it('should check what information the theme has', () => { const css = transpile(` $theme: mat.define-theme(); $color-only: mat.define-colors(); $typography-only: mat.define-typography(); $density-only: mat.define-density(); div { --base: #{( mat.theme-has($theme, base), mat.theme-has($color-only, base), mat.theme-has($typography-only, base), mat.theme-has($density-only, base), )}; --color: #{( mat.theme-has($theme, color), mat.theme-has($color-only, color), mat.theme-has($typography-only, color), mat.theme-has($density-only, color), )}; --typography: #{( mat.theme-has($theme, typography), mat.theme-has($color-only, typography), mat.theme-has($typography-only, typography), mat.theme-has($density-only, typography), )}; --density: #{( mat.theme-has($theme, density), mat.theme-has($color-only, density), mat.theme-has($typography-only, density), mat.theme-has($density-only, density), )}; } `); expect(css).toMatch(/--base: true, false, false, false;/); expect(css).toMatch(/--color: true, true, false, false;/); expect(css).toMatch(/--typography: true, false, true, false;/); expect(css).toMatch(/--density: true, false, false, true;/); }); it('should error when reading theme type from a theme with no color information', () => { expect(() => transpile(` $theme: mat.define-density(); div { color: mat.get-theme-type($theme); } `), ).toThrowError(/Color information is not available on this theme/); }); it('should error when reading color from a theme with no color information', () => { expect(() => transpile(` $theme: mat.define-density(); div { color: mat.get-theme-color($theme, primary); } `), ).toThrowError(/Color information is not available on this theme/); }); it('should error when reading typography from a theme with no typography information', () => { expect(() => transpile(` $theme: mat.define-density(); div { font: mat.get-theme-typography($theme, body-small); } `), ).toThrowError(/Typography information is not available on this theme/); }); it('should error when reading density from a theme with no density information', () => { expect(() => transpile(` $theme: mat.define-colors(); div { --density: #{mat.get-theme-density($theme)}; } `), ).toThrowError(/Density information is not available on this theme/); }); it('should not emit styles for removed theme dimensions', () => { const css = transpile(` $theme: mat.theme-remove(mat.define-theme(), base, color, typography, density); div { @include mat.all-component-themes($theme); }`); expect(css.trim()).toBe(''); }); }); });
115842
@use 'sass:list'; @use 'sass:map'; @use 'sass:meta'; @use '../theming/theming'; @use './palette'; /// Extracts a color from a palette or throws an error if it doesn't exist. /// @param {Map} $palette The palette from which to extract a color. /// @param {String | Number} $hue The hue for which to get the color. @function _get-color-from-palette($palette, $hue) { @if map.has-key($palette, $hue) { @return map.get($palette, $hue); } @error 'Hue "' + $hue + '" does not exist in palette. Available hues are: ' + map.keys($palette); } /// For a given hue in a palette, return the contrast color from the map of contrast palettes. /// @param {Map} $palette The palette from which to extract a color. /// @param {String | Number} $hue The hue for which to get a contrast color. /// @returns {Color} The contrast color for the given palette and hue. @function get-contrast-color-from-palette($palette, $hue) { @return map.get(map.get($palette, contrast), $hue); } /// Creates a map of hues to colors for a theme. This is used to define a theme palette in terms /// of the Material Design hues. /// @param {Map} $base-palette Map of hue keys to color values for the basis for this palette. /// @param {String | Number} $default Default hue for this palette. /// @param {String | Number} $lighter "lighter" hue for this palette. /// @param {String | Number} $darker "darker" hue for this palette. /// @param {String | Number} $text "text" hue for this palette. /// @returns {Map} A complete Angular Material theming palette. @function define-palette($base-palette, $default: 500, $lighter: 100, $darker: 700, $text: $default) { $result: map.merge($base-palette, ( default: _get-color-from-palette($base-palette, $default), lighter: _get-color-from-palette($base-palette, $lighter), darker: _get-color-from-palette($base-palette, $darker), text: _get-color-from-palette($base-palette, $text), default-contrast: get-contrast-color-from-palette($base-palette, $default), lighter-contrast: get-contrast-color-from-palette($base-palette, $lighter), darker-contrast: get-contrast-color-from-palette($base-palette, $darker) )); // For each hue in the palette, add a "-contrast" color to the map. @each $hue, $color in $base-palette { $result: map.merge($result, ( '#{$hue}-contrast': get-contrast-color-from-palette($base-palette, $hue) )); } @return $result; } /// Gets a color from a theme palette (the output of mat-palette). /// The hue can be one of the standard values (500, A400, etc.), one of the three preconfigured /// hues (default, lighter, darker), or any of the aforementioned suffixed with "-contrast". /// /// @param {Map} $palette The palette from which to extract a color. /// @param {String | Number} $hue The hue from the palette to use. If this is a value between 0 // and 1, it will be treated as opacity. /// @param {Number} $opacity The alpha channel value for the color. /// @returns {Color} The color for the given palette, hue, and opacity. @function get-color-from-palette($palette, $hue: default, $opacity: null) { // If hueKey is a number between zero and one, then it actually contains an // opacity value, so recall this function with the default hue and that given opacity. @if meta.type-of($hue) == number and $hue >= 0 and $hue <= 1 { @return get-color-from-palette($palette, default, $hue); } // We cast the $hue to a string, because some hues starting with a number, like `700-contrast`, // might be inferred as numbers by Sass. Casting them to string fixes the map lookup. $color: if(map.has-key($palette, $hue), map.get($palette, $hue), map.get($palette, $hue + '')); @if (meta.type-of($color) != color) { // If the $color resolved to something different from a color (e.g. a CSS variable), // we can't apply the opacity anyway so we return the value as is, otherwise Sass can // throw an error or output something invalid. @return $color; } @return rgba($color, if($opacity == null, opacity($color), $opacity)); } // Validates the specified theme by ensuring that the optional color config defines // a primary, accent and warn palette. Returns the theme if no failures were found. @function _mat-validate-theme($theme) { @if map.get($theme, color) { $color: map.get($theme, color); @if not map.get($color, primary) { @error 'Theme does not define a valid "primary" palette.'; } @else if not map.get($color, accent) { @error 'Theme does not define a valid "accent" palette.'; } @else if not map.get($color, warn) { @error 'Theme does not define a valid "warn" palette.'; } } @return $theme; } // Creates a light-themed color configuration from the specified // primary, accent and warn palettes. @function _mat-create-light-color-config($primary, $accent, $warn: null) { @return ( primary: $primary, accent: $accent, warn: if($warn != null, $warn, define-palette(palette.$red-palette)), is-dark: false, foreground: palette.$light-theme-foreground-palette, background: palette.$light-theme-background-palette, ); } // Creates a dark-themed color configuration from the specified // primary, accent and warn palettes. @function _mat-create-dark-color-config($primary, $accent, $warn: null) { @return ( primary: $primary, accent: $accent, warn: if($warn != null, $warn, define-palette(palette.$red-palette)), is-dark: true, foreground: palette.$dark-theme-foreground-palette, background: palette.$dark-theme-background-palette, ); } // TODO: Remove legacy API and rename `$primary` below to `$config`. Currently it cannot be renamed // as it would break existing apps that set the parameter by name. /// Creates a container object for a light theme to be given to individual component theme mixins. /// @param {Map} $primary The theme configuration object. /// @returns {Map} A complete Angular Material theme map.
115845
@use 'sass:list'; @use 'sass:map'; @use 'sass:string'; @use 'typography-utils'; @use '../theming/inspection'; // Definition and versioning functions live in their own files to avoid circular dependencies, but // we re-export them here so that historical imports from this file continue to work without needing // to be updated. @forward './versioning'; @mixin typography-hierarchy($theme, $selector: '.mat-typography', $back-compat: false) { @if inspection.get-theme-version($theme) == 1 { @include _m3-typography-hierarchy($theme, $selector, $back-compat); } @else { @include _m2-typography-hierarchy($theme, $selector); } } @function _get-selector($selectors, $prefix) { $result: (); @each $selector in $selectors { // Don't add "naked" tag selectors, and don't nest prefix selector. @if string.index($selector, '.') == 1 { $result: list.append($result, $selector, $separator: comma); } // Don't nest the prefix selector in itself. @if $selector != $prefix { $result: list.append($result, '#{$prefix} #{$selector}', $separator: comma); } } @return $result; } @mixin _m3-typography-level($theme, $selector-prefix, $level, $selectors, $margin: null) { #{_get-selector($selectors, $selector-prefix)} { // TODO(mmalerba): When we expose system tokens as CSS vars, we should change this to emit token // slots. font: inspection.get-theme-typography($theme, $level, font); letter-spacing: inspection.get-theme-typography($theme, $level, letter-spacing); @if $margin != null { margin: 0 0 $margin; } } } @mixin _m3-typography-hierarchy($theme, $selector-prefix, $add-m2-selectors) { $levels: ( display-large: ( selectors: ('.mat-display-large', 'h1'), m2-selectors: ('.mat-h1', '.mat-headline-1'), margin: 0.5em ), display-medium: ( selectors: ('.mat-display-medium', 'h2'), m2-selectors: ('.mat-h2', '.mat-headline-2'), margin: 0.5em ), display-small: ( selectors: ('.mat-display-small', 'h3'), m2-selectors: ('.mat-h3', '.mat-headline-3'), margin: 0.5em ), headline-large: ( selectors: ('.mat-headline-large', 'h4'), m2-selectors: ('.mat-h4', '.mat-headline-4'), margin: 0.5em ), headline-medium: ( selectors: ('.mat-headline-medium', 'h5'), m2-selectors: ('.mat-h5', '.mat-headline-5'), margin: 0.5em ), headline-small: ( selectors: ('.mat-headline-small', 'h6'), m2-selectors: ('.mat-h6', '.mat-headline-6'), margin: 0.5em ), title-large: ( selectors: ('.mat-title-large'), m2-selectors: ('.mat-subtitle-1'), ), title-medium: ( selectors: ('.mat-title-medium'), m2-selectors: ('.mat-subtitle-2'), ), title-small: ( selectors: ('.mat-title-small') ), body-large: ( selectors: ('.mat-body-large', $selector-prefix), m2-selectors: ('.mat-body', '.mat-body-strong', '.mat-body-2'), ), body-medium: ( selectors: ('.mat-body-medium') ), body-small: ( selectors: ('.mat-body-small') ), label-large: ( selectors: ('.mat-label-large') ), label-medium: ( selectors: ('.mat-label-medium') ), label-small: ( selectors: ('.mat-label-small'), m2-selectors: ('.mat-small', '.mat-caption') ), ); @each $level, $options in $levels { @if $add-m2-selectors { $options: map.set($options, selectors, list.join(map.get($options, selectors), map.get($options, m2-selectors) or ())); } $options: map.remove($options, m2-selectors); // Apply styles for the level. @include _m3-typography-level($theme, $selector-prefix, $level, $options...); // Also style <p> inside body-large. @if $level == body-large { #{_get-selector(map.get($options, selectors), $selector-prefix)} { p { margin: 0 0 0.75em; } } } } } /// Emits baseline typographic styles based on a given config. /// @param {Map} $config-or-theme A typography config for an entire theme. /// @param {String} $selector Ancestor selector under which native elements, such as h1, will /// be styled. @mixin _m2-typography-hierarchy($theme, $selector) { // Note that it seems redundant to prefix the class rules with the `$selector`, however it's // necessary if we want to allow people to overwrite the tag selectors. This is due to // selectors like `#{$selector} h1` being more specific than ones like `.mat-title`. .mat-h1, .mat-headline-5, #{$selector} .mat-h1, #{$selector} .mat-headline-5, #{$selector} h1 { font: inspection.get-theme-typography($theme, headline-5, font); letter-spacing: inspection.get-theme-typography($theme, headline-5, letter-spacing); margin: 0 0 16px; } .mat-h2, .mat-headline-6, #{$selector} .mat-h2, #{$selector} .mat-headline-6, #{$selector} h2 { font: inspection.get-theme-typography($theme, headline-6, font); letter-spacing: inspection.get-theme-typography($theme, headline-6, letter-spacing); margin: 0 0 16px; } .mat-h3, .mat-subtitle-1, #{$selector} .mat-h3, #{$selector} .mat-subtitle-1, #{$selector} h3 { font: inspection.get-theme-typography($theme, subtitle-1, font); letter-spacing: inspection.get-theme-typography($theme, subtitle-1, letter-spacing); margin: 0 0 16px; } .mat-h4, .mat-body-1, #{$selector} .mat-h4, #{$selector} .mat-body-1, #{$selector} h4 { font: inspection.get-theme-typography($theme, body-1, font); letter-spacing: inspection.get-theme-typography($theme, body-1, letter-spacing); margin: 0 0 16px; } // Note: the spec doesn't have anything that would correspond to h5 and h6, but we add these for // consistency. The font sizes come from the Chrome user agent styles which have h5 at 0.83em // and h6 at 0.67em. .mat-h5, #{$selector} .mat-h5, #{$selector} h5 { @include typography-utils
115861
@function _get-sys-typeface($ref, $prefix) { @if (sass-utils.$use-system-typography-variables) { $keys: ( 'body-large', 'body-large-font', 'body-large-line-height', 'body-large-size', 'body-large-tracking', 'body-large-weight', 'body-medium', 'body-medium-font', 'body-medium-line-height', 'body-medium-size', 'body-medium-tracking', 'body-medium-weight', 'body-small', 'body-small-font', 'body-small-line-height', 'body-small-size', 'body-small-tracking', 'body-small-weight', 'display-large', 'display-large-font', 'display-large-line-height', 'display-large-size', 'display-large-tracking', 'display-large-weight', 'display-medium', 'display-medium-font', 'display-medium-line-height', 'display-medium-size', 'display-medium-tracking', 'display-medium-weight', 'display-small', 'display-small-font', 'display-small-line-height', 'display-small-size', 'display-small-tracking', 'display-small-weight', 'headline-large', 'headline-large-font', 'headline-large-line-height', 'headline-large-size', 'headline-large-tracking', 'headline-large-weight', 'headline-medium', 'headline-medium-font', 'headline-medium-line-height', 'headline-medium-size', 'headline-medium-tracking', 'headline-medium-weight', 'headline-small', 'headline-small-font', 'headline-small-line-height', 'headline-small-size', 'headline-small-tracking', 'headline-small-weight', 'label-large', 'label-large-font', 'label-large-line-height', 'label-large-size', 'label-large-tracking', 'label-large-weight', 'label-large-weight-prominent', 'label-medium', 'label-medium-font', 'label-medium-line-height', 'label-medium-size', 'label-medium-tracking', 'label-medium-weight', 'label-medium-weight-prominent', 'label-small', 'label-small-font', 'label-small-line-height', 'label-small-size', 'label-small-tracking', 'label-small-weight', 'title-large', 'title-large-font', 'title-large-line-height', 'title-large-size', 'title-large-tracking', 'title-large-weight', 'title-medium', 'title-medium-font', 'title-medium-line-height', 'title-medium-size', 'title-medium-tracking', 'title-medium-weight', 'title-small', 'title-small-font', 'title-small-line-height', 'title-small-size', 'title-small-tracking', 'title-small-weight' ); @return create-map($keys, $prefix); } @return m3-token-definitions.md-sys-typescale-values($ref); } /// Generates a set of namespaced color tokens for all components. /// @param {String} $type The type of theme system (light or dark) /// @param {Map} $primary The primary palette /// @param {Map} $tertiary The tertiary palette /// @param {Map} $error The error palette /// @param {String} $system-variables-prefix The prefix of system tokens /// @return {Map} A map of namespaced color tokens @function generate-color-tokens($type, $primary, $tertiary, $error, $system-variables-prefix) { $ref: ( md-ref-palette: generate-ref-palette-tokens($primary, $tertiary, $error) ); $sys-color: _get-sys-color($type, $ref, $system-variables-prefix); @return generate-tokens(map.merge($ref, ( md-sys-color: $sys-color, // Because the elevation values are always combined with color values to create the box shadow, // elevation needs to be part of the color dimension. md-sys-elevation: m3-token-definitions.md-sys-elevation-values(), // Because the state values are sometimes combined with color values to create rgba colors, // state needs to be part of color dimension. // TODO(mmalerba): If at some point we remove the need for these combined values, we can move // state to the base dimension. md-sys-state: m3-token-definitions.md-sys-state-values(), ))); } /// Generates a set of namespaced color tokens for all components. /// @param {String|List} $brand The brand font-family /// @param {String|List} $plain The plain fort-family /// @param {String|Number} $bold The bold font-weight /// @param {String|Number} $medium The medium font-weight /// @param {String|Number} $regular The regular font-weight /// @param {String} $system-variables-prefix The prefix of system tokens /// @return {Map} A map of namespaced typography tokens @function generate-typography-tokens($brand, $plain, $bold, $medium, $regular, $system-variables-prefix) { $ref: ( md-ref-typeface: generate-ref-typeface-tokens($brand, $plain, $bold, $medium, $regular) ); $sys-typeface: _get-sys-typeface($ref, $system-variables-prefix); @return generate-tokens(( md-sys-typescale: $sys-typeface )); } /// Generates a set of namespaced density tokens for all components. /// @param {String|Number} $scale The regular font-weight /// @return {Map} A map of namespaced density tokens @function generate-density-tokens($scale) { @return density.get-tokens-for-scale($scale); } /// Generates a set of namespaced tokens not related to color, typography, or density for all /// components. /// @return {Map} A map of namespaced tokens not related to color, typography, or density @function generate-base-tokens() { // TODO(mmalerba): Exclude density tokens once implemented. @return generate-tokens(( md-sys-motion: m3-token-definitions.md-sys-motion-values(), md-sys-shape: m3-token-definitions.md-sys-shape-values(), ), $include-non-systemized: true); }
115865
@mixin system-level-typography($theme, $overrides: (), $prefix: null) { $font-definition: map.get($theme, _mat-theming-internals-do-not-access, font-definition); $brand: map.get($font-definition, brand); $plain: map.get($font-definition, plain); $bold: map.get($font-definition, bold); $medium: map.get($font-definition, medium); $regular: map.get($font-definition, regular); $ref: (md-ref-typeface: m3-tokens.generate-ref-typeface-tokens($brand, $plain, $bold, $medium, $regular) ); @if (not $prefix) { $prefix: map.get($theme, _mat-theming-internals-do-not-access, typography-system-variables-prefix) or definition.$system-level-prefix; } & { @each $name, $value in definitions.md-sys-typescale-values($ref) { --#{$prefix}-#{$name}: #{map.get($overrides, $name) or $value}; } } } @mixin system-level-elevation($theme, $overrides: (), $prefix: definition.$system-level-prefix) { $shadow-color: map.get( $theme, _mat-theming-internals-do-not-access, color-tokens, (mdc, theme), shadow); @each $name, $value in definitions.md-sys-elevation-values() { $level: map.get($overrides, $name) or $value; $value: elevation.get-box-shadow($level, $shadow-color); & { --#{$prefix}-#{$name}: #{$value}; } } } @mixin system-level-shape($theme: (), $overrides: (), $prefix: definition.$system-level-prefix) { & { @each $name, $value in definitions.md-sys-shape-values() { --#{$prefix}-#{$name}: #{map.get($overrides, $name) or $value}; } } } @mixin system-level-state($theme: (), $overrides: (), $prefix: definition.$system-level-prefix) { & { @each $name, $value in definitions.md-sys-state-values() { --#{$prefix}-#{$name}: #{map.get($overrides, $name) or $value}; } } } @mixin system-level-motion($theme: (), $overrides: (), $prefix: definition.$system-level-prefix) { & { @each $name, $value in definitions.md-sys-motion-values() { --#{$prefix}-#{$name}: #{map.get($overrides, $name) or $value}; } } } // Return a new map where the values are the same as the provided map's // keys, prefixed with "--mat-sys-". For example: // (key1: '', key2: '') --> (key1: --mat-sys-key1, key2: --mat-sys-key2) @function _create-system-app-vars-map($map) { $new-map: (); @each $key, $value in $map { $new-map: map.set($new-map, $key, --#{definition.$system-fallback-prefix}-#{$key}); } @return $new-map; } // Create a components tokens map where values are based on // system fallback variables referencing Material's system keys. // Includes density token fallbacks where density is 0. @function create-system-fallbacks() { $app-vars: ( 'md-sys-color': _create-system-app-vars-map(definitions.md-sys-color-values-light()), 'md-sys-typescale': _create-system-app-vars-map(definitions.md-sys-typescale-values()), 'md-sys-elevation': _create-system-app-vars-map(definitions.md-sys-elevation-values()), 'md-sys-state': _create-system-app-vars-map(definitions.md-sys-state-values()), 'md-sys-shape': _create-system-app-vars-map(definitions.md-sys-shape-values()), // Add a subset of palette-specific colors used by components instead of system values 'md-ref-palette': _create-system-app-vars-map( ( neutral10: '', // Form field native select option text color neutral-variant20: '', // Sidenav scrim (container background shadow when opened), ) ), ); @return sass-utils.deep-merge-all( m3-tokens.generate-tokens($app-vars, true, true), m3-tokens.generate-density-tokens(0) ); } /// Creates a single merged map from the provided variable-length map arguments @function map-merge-all($maps...) { $result: (); @each $map in $maps { $result: map.merge($result, $map); } @return $result; }
116031
#{'/'} if( $exclude-hardcoded-values, null, 1.5rem ) map.get($deps, 'md-ref-typeface', 'plain') ), 'body-large-font': map.get($deps, 'md-ref-typeface', 'plain'), 'body-large-line-height': if($exclude-hardcoded-values, null, 1.5rem), 'body-large-size': if($exclude-hardcoded-values, null, 1rem), 'body-large-tracking': if($exclude-hardcoded-values, null, 0.031rem), 'body-large-weight': map.get($deps, 'md-ref-typeface', 'weight-regular'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.body-medium.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'body-medium': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-regular') if($exclude-hardcoded-values, null, 0.875rem) #{'/'} if( $exclude-hardcoded-values, null, 1.25rem ) map.get($deps, 'md-ref-typeface', 'plain') ), 'body-medium-font': map.get($deps, 'md-ref-typeface', 'plain'), 'body-medium-line-height': if($exclude-hardcoded-values, null, 1.25rem), 'body-medium-size': if($exclude-hardcoded-values, null, 0.875rem), 'body-medium-tracking': if($exclude-hardcoded-values, null, 0.016rem), 'body-medium-weight': map.get($deps, 'md-ref-typeface', 'weight-regular'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.body-small.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'body-small': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-regular') if($exclude-hardcoded-values, null, 0.75rem) #{'/'} if( $exclude-hardcoded-values, null, 1rem ) map.get($deps, 'md-ref-typeface', 'plain') ), 'body-small-font': map.get($deps, 'md-ref-typeface', 'plain'), 'body-small-line-height': if($exclude-hardcoded-values, null, 1rem), 'body-small-size': if($exclude-hardcoded-values, null, 0.75rem), 'body-small-tracking': if($exclude-hardcoded-values, null, 0.025rem), 'body-small-weight': map.get($deps, 'md-ref-typeface', 'weight-regular'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.display-large.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'display-large': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-regular') if($exclude-hardcoded-values, null, 3.562rem) #{'/'} if( $exclude-hardcoded-values, null, 4rem ) map.get($deps, 'md-ref-typeface', 'brand') ), 'display-large-font': map.get($deps, 'md-ref-typeface', 'brand'), 'display-large-line-height': if($exclude-hardcoded-values, null, 4rem), 'display-large-size': if($exclude-hardcoded-values, null, 3.562rem), 'display-large-tracking': if($exclude-hardcoded-values, null, -0.016rem), 'display-large-weight': map.get($deps, 'md-ref-typeface', 'weight-regular'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.display-medium.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'display-medium': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-regular') if($exclude-hardcoded-values, null, 2.812rem) #{'/'} if( $exclude-hardcoded-values, null, 3.25rem ) map.get($deps, 'md-ref-typeface', 'brand') ), 'display-medium-font': map.get($deps, 'md-ref-typeface', 'brand'), 'display-medium-line-height': if($exclude-hardcoded-values, null, 3.25rem), 'display-medium-size': if($exclude-hardcoded-values, null, 2.812rem), 'display-medium-tracking': if($exclude-hardcoded-values, null, 0), 'display-medium-weight': map.get($deps, 'md-ref-typeface', 'weight-regular'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.display-small.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'display-small': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-regular') if($exclude-hardcoded-values, null, 2.25rem) #{'/'} if( $exclude-hardcoded-values, null, 2.75rem ) map.get($deps, 'md-ref-typeface', 'brand') ), 'display-small-font': map.get($deps, 'md-ref-typeface', 'brand'), 'display-small-line-height': if($exclude-hardcoded-values, null, 2.75rem), 'display-small-size': if($exclude-hardcoded-values, null, 2.25rem), 'display-small-tracking': if($exclude-hardcoded-values, null, 0), 'display-small-weight': map.get($deps, 'md-ref-typeface', 'weight-regular'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.headline-large.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'headline-large': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-regular') if($exclude-hardcoded-values, null, 2rem) #{'/'} if( $exclude-hardcoded-values, null, 2.5rem ) map.get($deps, 'md-ref-typeface', 'brand') ), 'headline-large-font': map.get($deps, 'md-ref-typeface', 'brand'), 'headline-large-line-height': if($exclude-hardcoded-values, null, 2.5rem), 'headline-large-size': if($exclude-hardcoded-values, null, 2rem), 'headline-large-tracking': if($exclude-hardcoded-values, null, 0), 'headline-large-weight': map.get($deps, 'md-ref-typeface', 'weight-regular'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.headline-medium.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'headline-medium': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-regular') if($exclude-hardcoded-values, null, 1.75rem) #{'/'} if( $exclude-hardcoded-values, null, 2.25rem ) map.get($deps, 'md-ref-typeface', 'brand') ), 'headline-medium-font': map.get($deps, 'md-ref-typeface', 'brand'), 'headline-medium-line-height': if($exclude-hardcoded-values, null, 2.25rem), 'headline-medium-size': if($exclude-hardcoded-values, null, 1.75rem), 'headline-medium-tracking': if($exclude-hardcoded-values, null, 0), 'headline-medium-weight': map.get($deps, 'md-ref-typeface', 'weight-regular'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.headline-small.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'headline-small': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-regular') if($exclude-hardcoded-values, null, 1.5rem) #{'/'} if( $exclude-hardcoded-values, null, 2rem ) map.get($deps, 'md-ref-typeface', 'brand') )
116032
, 'headline-small-font': map.get($deps, 'md-ref-typeface', 'brand'), 'headline-small-line-height': if($exclude-hardcoded-values, null, 2rem), 'headline-small-size': if($exclude-hardcoded-values, null, 1.5rem), 'headline-small-tracking': if($exclude-hardcoded-values, null, 0), 'headline-small-weight': map.get($deps, 'md-ref-typeface', 'weight-regular'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.label-large.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'label-large': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-medium') if($exclude-hardcoded-values, null, 0.875rem) #{'/'} if( $exclude-hardcoded-values, null, 1.25rem ) map.get($deps, 'md-ref-typeface', 'plain') ), 'label-large-font': map.get($deps, 'md-ref-typeface', 'plain'), 'label-large-line-height': if($exclude-hardcoded-values, null, 1.25rem), 'label-large-size': if($exclude-hardcoded-values, null, 0.875rem), 'label-large-tracking': if($exclude-hardcoded-values, null, 0.006rem), 'label-large-weight': map.get($deps, 'md-ref-typeface', 'weight-medium'), 'label-large-weight-prominent': map.get($deps, 'md-ref-typeface', 'weight-bold'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.label-medium.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'label-medium': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-medium') if($exclude-hardcoded-values, null, 0.75rem) #{'/'} if( $exclude-hardcoded-values, null, 1rem ) map.get($deps, 'md-ref-typeface', 'plain') ), 'label-medium-font': map.get($deps, 'md-ref-typeface', 'plain'), 'label-medium-line-height': if($exclude-hardcoded-values, null, 1rem), 'label-medium-size': if($exclude-hardcoded-values, null, 0.75rem), 'label-medium-tracking': if($exclude-hardcoded-values, null, 0.031rem), 'label-medium-weight': map.get($deps, 'md-ref-typeface', 'weight-medium'), 'label-medium-weight-prominent': map.get($deps, 'md-ref-typeface', 'weight-bold'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.label-small.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'label-small': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-medium') if($exclude-hardcoded-values, null, 0.688rem) #{'/'} if( $exclude-hardcoded-values, null, 1rem ) map.get($deps, 'md-ref-typeface', 'plain') ), 'label-small-font': map.get($deps, 'md-ref-typeface', 'plain'), 'label-small-line-height': if($exclude-hardcoded-values, null, 1rem), 'label-small-size': if($exclude-hardcoded-values, null, 0.688rem), 'label-small-tracking': if($exclude-hardcoded-values, null, 0.031rem), 'label-small-weight': map.get($deps, 'md-ref-typeface', 'weight-medium'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.title-large.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'title-large': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-regular') if($exclude-hardcoded-values, null, 1.375rem) #{'/'} if( $exclude-hardcoded-values, null, 1.75rem ) map.get($deps, 'md-ref-typeface', 'brand') ), 'title-large-font': map.get($deps, 'md-ref-typeface', 'brand'), 'title-large-line-height': if($exclude-hardcoded-values, null, 1.75rem), 'title-large-size': if($exclude-hardcoded-values, null, 1.375rem), 'title-large-tracking': if($exclude-hardcoded-values, null, 0), 'title-large-weight': map.get($deps, 'md-ref-typeface', 'weight-regular'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.title-medium.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'title-medium': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-medium') if($exclude-hardcoded-values, null, 1rem) #{'/'} if( $exclude-hardcoded-values, null, 1.5rem ) map.get($deps, 'md-ref-typeface', 'plain') ), 'title-medium-font': map.get($deps, 'md-ref-typeface', 'plain'), 'title-medium-line-height': if($exclude-hardcoded-values, null, 1.5rem), 'title-medium-size': if($exclude-hardcoded-values, null, 1rem), 'title-medium-tracking': if($exclude-hardcoded-values, null, 0.009rem), 'title-medium-weight': map.get($deps, 'md-ref-typeface', 'weight-medium'), // Warning: risk of reduced fidelity from using this composite typography token. // Tokens md.sys.typescale.title-small.tracking cannot be represented in the "font" // property shorthand. Consider using the discrete properties instead. 'title-small': if( $exclude-hardcoded-values, null, map.get($deps, 'md-ref-typeface', 'weight-medium') if($exclude-hardcoded-values, null, 0.875rem) #{'/'} if( $exclude-hardcoded-values, null, 1.25rem ) map.get($deps, 'md-ref-typeface', 'plain') ), 'title-small-font': map.get($deps, 'md-ref-typeface', 'plain'), 'title-small-line-height': if($exclude-hardcoded-values, null, 1.25rem), 'title-small-size': if($exclude-hardcoded-values, null, 0.875rem), 'title-small-tracking': if($exclude-hardcoded-values, null, 0.006rem), 'title-small-weight': map.get($deps, 'md-ref-typeface', 'weight-medium') ); }
116136
class MatAutocomplete implements AfterContentInit, OnDestroy { private _changeDetectorRef = inject(ChangeDetectorRef); private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); protected _defaults = inject<MatAutocompleteDefaultOptions>(MAT_AUTOCOMPLETE_DEFAULT_OPTIONS); private _activeOptionChanges = Subscription.EMPTY; /** Emits when the panel animation is done. Null if the panel doesn't animate. */ _animationDone = new EventEmitter<AnimationEvent>(); /** Manages active item in option list based on key events. */ _keyManager: ActiveDescendantKeyManager<MatOption>; /** Whether the autocomplete panel should be visible, depending on option length. */ showPanel: boolean = false; /** Whether the autocomplete panel is open. */ get isOpen(): boolean { return this._isOpen && this.showPanel; } _isOpen: boolean = false; /** Latest trigger that opened the autocomplete. */ _latestOpeningTrigger: unknown; /** @docs-private Sets the theme color of the panel. */ _setColor(value: ThemePalette) { this._color = value; this._changeDetectorRef.markForCheck(); } /** @docs-private theme color of the panel */ protected _color: ThemePalette; // The @ViewChild query for TemplateRef here needs to be static because some code paths // lead to the overlay being created before change detection has finished for this component. // Notably, another component may trigger `focus` on the autocomplete-trigger. /** @docs-private */ @ViewChild(TemplateRef, {static: true}) template: TemplateRef<any>; /** Element for the panel containing the autocomplete options. */ @ViewChild('panel') panel: ElementRef; /** Reference to all options within the autocomplete. */ @ContentChildren(MatOption, {descendants: true}) options: QueryList<MatOption>; /** Reference to all option groups within the autocomplete. */ @ContentChildren(MAT_OPTGROUP, {descendants: true}) optionGroups: QueryList<MatOptgroup>; /** Aria label of the autocomplete. */ @Input('aria-label') ariaLabel: string; /** Input that can be used to specify the `aria-labelledby` attribute. */ @Input('aria-labelledby') ariaLabelledby: string; /** Function that maps an option's control value to its display value in the trigger. */ @Input() displayWith: ((value: any) => string) | null = null; /** * Whether the first option should be highlighted when the autocomplete panel is opened. * Can be configured globally through the `MAT_AUTOCOMPLETE_DEFAULT_OPTIONS` token. */ @Input({transform: booleanAttribute}) autoActiveFirstOption: boolean; /** Whether the active option should be selected as the user is navigating. */ @Input({transform: booleanAttribute}) autoSelectActiveOption: boolean; /** * Whether the user is required to make a selection when they're interacting with the * autocomplete. If the user moves away from the autocomplete without selecting an option from * the list, the value will be reset. If the user opens the panel and closes it without * interacting or selecting a value, the initial value will be kept. */ @Input({transform: booleanAttribute}) requireSelection: boolean; /** * Specify the width of the autocomplete panel. Can be any CSS sizing value, otherwise it will * match the width of its host. */ @Input() panelWidth: string | number; /** Whether ripples are disabled within the autocomplete panel. */ @Input({transform: booleanAttribute}) disableRipple: boolean; /** Event that is emitted whenever an option from the list is selected. */ @Output() readonly optionSelected: EventEmitter<MatAutocompleteSelectedEvent> = new EventEmitter<MatAutocompleteSelectedEvent>(); /** Event that is emitted when the autocomplete panel is opened. */ @Output() readonly opened: EventEmitter<void> = new EventEmitter<void>(); /** Event that is emitted when the autocomplete panel is closed. */ @Output() readonly closed: EventEmitter<void> = new EventEmitter<void>(); /** Emits whenever an option is activated. */ @Output() readonly optionActivated: EventEmitter<MatAutocompleteActivatedEvent> = new EventEmitter<MatAutocompleteActivatedEvent>(); /** * Takes classes set on the host mat-autocomplete element and applies them to the panel * inside the overlay container to allow for easy styling. */ @Input('class') set classList(value: string | string[]) { this._classList = value; this._elementRef.nativeElement.className = ''; } _classList: string | string[]; /** Whether checkmark indicator for single-selection options is hidden. */ @Input({transform: booleanAttribute}) get hideSingleSelectionIndicator(): boolean { return this._hideSingleSelectionIndicator; } set hideSingleSelectionIndicator(value: boolean) { this._hideSingleSelectionIndicator = value; this._syncParentProperties(); } private _hideSingleSelectionIndicator: boolean; /** Syncs the parent state with the individual options. */ _syncParentProperties(): void { if (this.options) { for (const option of this.options) { option._changeDetectorRef.markForCheck(); } } } /** Unique ID to be used by autocomplete trigger's "aria-owns" property. */ id: string = `mat-autocomplete-${_uniqueAutocompleteIdCounter++}`; /** * Tells any descendant `mat-optgroup` to use the inert a11y pattern. * @docs-private */ readonly inertGroups: boolean; constructor(...args: unknown[]); constructor() { const platform = inject(Platform); // TODO(crisbeto): the problem that the `inertGroups` option resolves is only present on // Safari using VoiceOver. We should occasionally check back to see whether the bug // wasn't resolved in VoiceOver, and if it has, we can remove this and the `inertGroups` // option altogether. this.inertGroups = platform?.SAFARI || false; this.autoActiveFirstOption = !!this._defaults.autoActiveFirstOption; this.autoSelectActiveOption = !!this._defaults.autoSelectActiveOption; this.requireSelection = !!this._defaults.requireSelection; this._hideSingleSelectionIndicator = this._defaults.hideSingleSelectionIndicator ?? false; } ngAfterContentInit() { this._keyManager = new ActiveDescendantKeyManager<MatOption>(this.options) .withWrap() .skipPredicate(this._skipPredicate); this._activeOptionChanges = this._keyManager.change.subscribe(index => { if (this.isOpen) { this.optionActivated.emit({source: this, option: this.options.toArray()[index] || null}); } }); // Set the initial visibility state. this._setVisibility(); } ngOnDestroy() { this._keyManager?.destroy(); this._activeOptionChanges.unsubscribe(); this._animationDone.complete(); } /** * Sets the panel scrollTop. This allows us to manually scroll to display options * above or below the fold, as they are not actually being focused when active. */ _setScrollTop(scrollTop: number): void { if (this.panel) { this.panel.nativeElement.scrollTop = scrollTop; } } /** Returns the panel's scrollTop. */ _getScrollTop(): number { return this.panel ? this.panel.nativeElement.scrollTop : 0; } /** Panel should hide itself when the option list is empty. */ _setVisibility() { this.showPanel = !!this.options.length; this._changeDetectorRef.markForCheck(); } /** Emits the `select` event. */ _emitSelectEvent(option: MatOption): void { const event = new MatAutocompleteSelectedEvent(this, option); this.optionSelected.emit(event); } /** Gets the aria-labelledby for the autocomplete panel. */ _getPanelAriaLabelledby(labelId: string | null): string | null { if (this.ariaLabel) { return null; } const labelExpression = labelId ? labelId + ' ' : ''; return this.ariaLabelledby ? labelExpression + this.ariaLabelledby : labelId; } // `skipPredicate` determines if key manager should avoid putting a given option in the tab // order. Allow disabled list items to receive focus via keyboard to align with WAI ARIA // recommendation. // // Normally WAI ARIA's instructions are to exclude disabled items from the tab order, but it // makes a few exceptions for compound widgets. // // From [Developing a Keyboard Interface]( // https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/): // "For the following composite widget elements, keep them focusable when disabled: Options in a // Listbox..." // // The user can focus disabled options using the keyboard, but the user cannot click disabled // options. protected _skipPredicate() { return false; } }
116139
import {OverlayModule} from '@angular/cdk/overlay'; import {dispatchFakeEvent} from '@angular/cdk/testing/private'; import { Component, NgZone, OnDestroy, Provider, QueryList, Type, ViewChild, ViewChildren, provideZoneChangeDetection, } from '@angular/core'; import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing'; import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {Subscription} from 'rxjs'; import {MatOption} from '../core'; import {MatFormField, MatFormFieldModule} from '../form-field'; import {MatInputModule} from '../input'; import {MatAutocomplete} from './autocomplete'; import {MatAutocompleteTrigger} from './autocomplete-trigger'; import {MatAutocompleteModule} from './module'; describe('MatAutocomplete Zone.js integration', () => { // Creates a test component fixture. function createComponent<T>(component: Type<T>, providers: Provider[] = []) { TestBed.configureTestingModule({ imports: [ MatAutocompleteModule, MatFormFieldModule, MatInputModule, FormsModule, ReactiveFormsModule, NoopAnimationsModule, OverlayModule, ], providers: [provideZoneChangeDetection(), ...providers], declarations: [component], }); return TestBed.createComponent<T>(component); } describe('panel toggling', () => { let fixture: ComponentFixture<SimpleAutocomplete>; beforeEach(() => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); }); it('should show the panel when the first open is after the initial zone stabilization', waitForAsync(() => { // Note that we're running outside the Angular zone, in order to be able // to test properly without the subscription from `_subscribeToClosingActions` // giving us a false positive. fixture.ngZone!.runOutsideAngular(() => { fixture.componentInstance.trigger.openPanel(); Promise.resolve().then(() => { expect(fixture.componentInstance.panel.showPanel) .withContext(`Expected panel to be visible.`) .toBe(true); }); }); })); }); it('should emit from `autocomplete.closed` after click outside inside the NgZone', waitForAsync(async () => { const inZoneSpy = jasmine.createSpy('in zone spy'); const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const subscription = fixture.componentInstance.trigger.autocomplete.closed.subscribe(() => inZoneSpy(NgZone.isInAngularZone()), ); await new Promise(r => setTimeout(r)); dispatchFakeEvent(document, 'click'); expect(inZoneSpy).toHaveBeenCalledWith(true); subscription.unsubscribe(); })); }); const SIMPLE_AUTOCOMPLETE_TEMPLATE = ` <mat-form-field [floatLabel]="floatLabel" [style.width.px]="width" [color]="theme"> @if (hasLabel) { <mat-label>State</mat-label> } <input matInput placeholder="State" [matAutocomplete]="auto" [matAutocompletePosition]="position" [matAutocompleteDisabled]="autocompleteDisabled" [formControl]="stateCtrl"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete" [class]="panelClass" [displayWith]="displayFn" [disableRipple]="disableRipple" [requireSelection]="requireSelection" [aria-label]="ariaLabel" [aria-labelledby]="ariaLabelledby" (opened)="openedSpy()" (closed)="closedSpy()"> @for (state of filteredStates; track state) { <mat-option [value]="state" [style.height.px]="state.height" [disabled]="state.disabled"> <span>{{ state.code }}: {{ state.name }}</span> </mat-option> } </mat-autocomplete> `; @Component({template: SIMPLE_AUTOCOMPLETE_TEMPLATE, standalone: false}) class SimpleAutocomplete implements OnDestroy { stateCtrl = new FormControl<{name: string; code: string} | string | null>(null); filteredStates: any[]; valueSub: Subscription; floatLabel = 'auto'; position = 'auto'; width: number; disableRipple = false; autocompleteDisabled = false; hasLabel = true; requireSelection = false; ariaLabel: string; ariaLabelledby: string; panelClass = 'class-one class-two'; theme: string; openedSpy = jasmine.createSpy('autocomplete opened spy'); closedSpy = jasmine.createSpy('autocomplete closed spy'); @ViewChild(MatAutocompleteTrigger, {static: true}) trigger: MatAutocompleteTrigger; @ViewChild(MatAutocomplete) panel: MatAutocomplete; @ViewChild(MatFormField) formField: MatFormField; @ViewChildren(MatOption) options: QueryList<MatOption>; states: {code: string; name: string; height?: number; disabled?: boolean}[] = [ {code: 'AL', name: 'Alabama'}, {code: 'CA', name: 'California'}, {code: 'FL', name: 'Florida'}, {code: 'KS', name: 'Kansas'}, {code: 'MA', name: 'Massachusetts'}, {code: 'NY', name: 'New York'}, {code: 'OR', name: 'Oregon'}, {code: 'PA', name: 'Pennsylvania'}, {code: 'TN', name: 'Tennessee'}, {code: 'VA', name: 'Virginia'}, {code: 'WY', name: 'Wyoming'}, ]; constructor() { this.filteredStates = this.states; this.valueSub = this.stateCtrl.valueChanges.subscribe(val => { this.filteredStates = val ? this.states.filter(s => s.name.match(new RegExp(val as string, 'gi'))) : this.states; }); } displayFn(value: any): string { return value ? value.name : value; } ngOnDestroy() { this.valueSub.unsubscribe(); } }
116141
The autocomplete is a normal text input enhanced by a panel of suggested options. ### Simple autocomplete Start by creating the autocomplete panel and the options displayed inside it. Each option should be defined by a `mat-option` tag. Set each option's value property to whatever you'd like the value of the text input to be when that option is selected. <!-- example({"example":"autocomplete-simple", "file":"autocomplete-simple-example.html", "region":"mat-autocomplete"}) --> Next, create the input and set the `matAutocomplete` input to refer to the template reference we assigned to the autocomplete. Let's assume you're using the `formControl` directive from `ReactiveFormsModule` to track the value of the input. > Note: It is possible to use template-driven forms instead, if you prefer. We use reactive forms in this example because it makes subscribing to changes in the input's value easy. For this example, be sure to import `ReactiveFormsModule` from `@angular/forms` into your `NgModule`. If you are unfamiliar with using reactive forms, you can read more about the subject in the [Angular documentation](https://angular.dev/guide/forms/reactive-forms). Now we'll need to link the text input to its panel. We can do this by exporting the autocomplete panel instance into a local template variable (here we called it "auto"), and binding that variable to the input's `matAutocomplete` property. <!-- example({"example":"autocomplete-simple", "file":"autocomplete-simple-example.html", "region":"input"}) --> ### Adding a custom filter At this point, the autocomplete panel should be toggleable on focus and options should be selectable. But if we want our options to filter when we type, we need to add a custom filter. You can filter the options in any way you like based on the text input\*. Here we will perform a simple string test on the option value to see if it matches the input value, starting from the option's first letter. We already have access to the built-in `valueChanges` Observable on the `FormControl`, so we can simply map the text input's values to the suggested options by passing them through this filter. The resulting Observable, `filteredOptions`, can be added to the template in place of the `options` property using the `async` pipe. Below we are also priming our value change stream with an empty string so that the options are filtered by that value on init (before there are any value changes). \*For optimal accessibility, you may want to consider adding text guidance on the page to explain filter criteria. This is especially helpful for screenreader users if you're using a non-standard filter that doesn't limit matches to the beginning of the string. <!-- example(autocomplete-filter) --> ### Setting separate control and display values If you want the option's control value (what is saved in the form) to be different than the option's display value (what is displayed in the text field), you'll need to set the `displayWith` property on your autocomplete element. A common use case for this might be if you want to save your data as an object, but display just one of the option's string properties. To make this work, create a function on your component class that maps the control value to the desired display value. Then bind it to the autocomplete's `displayWith` property. <!-- example(autocomplete-display) --> ### Require an option to be selected By default, the autocomplete will accept the value that the user typed into the input field. Instead, if you want to instead ensure that an option from the autocomplete was selected, you can enable the `requireSelection` input on `mat-autocomplete`. This will change the behavior of the autocomplete in the following ways: 1. If the user opens the autocomplete, changes its value, but doesn't select anything, the autocomplete value will be reset back to `null`. 2. If the user opens and closes the autocomplete without changing the value, the old value will be preserved. This behavior can be configured globally using the `MAT_AUTOCOMPLETE_DEFAULT_OPTIONS` injection token. <!-- example(autocomplete-require-selection) --> ### Automatically highlighting the first option If your use case requires for the first autocomplete option to be highlighted when the user opens the panel, you can do so by setting the `autoActiveFirstOption` input on the `mat-autocomplete` component. This behavior can be configured globally using the `MAT_AUTOCOMPLETE_DEFAULT_OPTIONS` injection token. <!-- example(autocomplete-auto-active-first-option) --> ### Autocomplete on a custom input element While `mat-autocomplete` supports attaching itself to a `mat-form-field`, you can also set it on any other `input` element using the `matAutocomplete` attribute. This allows you to customize what the input looks like without having to bring in the extra functionality from `mat-form-field`. <!-- example(autocomplete-plain-input) --> ### Attaching the autocomplete panel to a different element By default the autocomplete panel will be attached to your input element, however in some cases you may want it to attach to a different container element. You can change the element that the autocomplete is attached to using the `matAutocompleteOrigin` directive together with the `matAutocompleteConnectedTo` input: ```html <div class="custom-wrapper-example" matAutocompleteOrigin #origin="matAutocompleteOrigin"> <input matInput [formControl]="myControl" [matAutocomplete]="auto" [matAutocompleteConnectedTo]="origin"> </div> <mat-autocomplete #auto="matAutocomplete"> @for (option of options; track option) { <mat-option [value]="option">{{option}}</mat-option> } </mat-autocomplete> ``` ### Keyboard interaction | Keyboard shortcut | Action | |----------------------------------------|----------------------------------------------------------------| | <kbd>Down Arrow</kbd> | Navigate to the next option. | | <kbd>Up Arrow</kbd> | Navigate to the previous option. | | <kbd>Enter</kbd> | Select the active option. | | <kbd>Escape</kbd> | Close the autocomplete panel. | | <kbd>Alt</kbd> + <kbd>Up Arrow</kbd> | Close the autocomplete panel. | | <kbd>Alt</kbd> + <kbd>Down Arrow</kbd> | Open the autocomplete panel if there are any matching options. | ### Option groups `mat-option` can be collected into groups using the `mat-optgroup` element: <!-- example({"example":"autocomplete-optgroup", "file":"autocomplete-optgroup-example.html", "region":"mat-autocomplete"}) --> ### Accessibility `MatAutocomplete` implements the ARIA combobox interaction pattern. The text input trigger specifies `role="combobox"` while the content of the pop-up applies `role="listbox"`. Because of this listbox pattern, you should _not_ put other interactive controls, such as buttons or checkboxes, inside an autocomplete option. Nesting interactive controls like this interferes with most assistive technology. Always provide an accessible label for the autocomplete. This can be done by using a `<mat-label>` inside of `<mat-form-field>`, a native `<label>` element, the `aria-label` attribute, or the `aria-labelledby` attribute. `MatAutocomplete` preserves focus on the text trigger, using `aria-activedescendant` to support navigation though the autocomplete options. By default, `MatAutocomplete` displays a checkmark to identify the selected item. While you can hide the checkmark indicator via `hideSingleSelectionIndicator`, this makes the component less accessible by making it harder or impossible for users to visually identify selected items.
116146
it('should update the panel direction if it changes for the trigger', () => { const dirProvider = {value: 'rtl', change: EMPTY}; const rtlFixture = createComponent(SimpleAutocomplete, [ {provide: Directionality, useFactory: () => dirProvider}, ]); rtlFixture.detectChanges(); rtlFixture.componentInstance.trigger.openPanel(); rtlFixture.detectChanges(); let boundingBox = overlayContainerElement.querySelector( '.cdk-overlay-connected-position-bounding-box', )!; expect(boundingBox.getAttribute('dir')).toEqual('rtl'); rtlFixture.componentInstance.trigger.closePanel(); rtlFixture.detectChanges(); dirProvider.value = 'ltr'; rtlFixture.componentInstance.trigger.openPanel(); rtlFixture.detectChanges(); boundingBox = overlayContainerElement.querySelector( '.cdk-overlay-connected-position-bounding-box', )!; expect(boundingBox.getAttribute('dir')).toEqual('ltr'); }); it('should be able to set a custom value for the `autocomplete` attribute', () => { const fixture = createComponent(AutocompleteWithNativeAutocompleteAttribute); const input = fixture.nativeElement.querySelector('input'); fixture.detectChanges(); expect(input.getAttribute('autocomplete')).toBe('changed'); }); it('should not throw when typing in an element with a null and disabled autocomplete', () => { const fixture = createComponent(InputWithoutAutocompleteAndDisabled); fixture.detectChanges(); expect(() => { dispatchKeyboardEvent(fixture.nativeElement.querySelector('input'), 'keydown', SPACE); fixture.detectChanges(); }).not.toThrow(); }); it('should clear the selected option if it no longer matches the input text while typing', waitForAsync(async () => { const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); // Select an option and reopen the panel. (overlayContainerElement.querySelector('mat-option') as HTMLElement).click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.options.first.selected).toBe(true); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; input.value = ''; typeInElement(input, 'Ala'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.options.first.selected).toBe(false); })); it('should not clear the selected option if it no longer matches the input text while typing with requireSelection', waitForAsync(async () => { const fixture = createComponent(SimpleAutocomplete); fixture.componentInstance.requireSelection = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); // Select an option and reopen the panel. (overlayContainerElement.querySelector('mat-option') as HTMLElement).click(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.options.first.selected).toBe(true); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; input.value = ''; typeInElement(input, 'Ala'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(fixture.componentInstance.options.first.selected).toBe(true); }));
116157
it('should preserve the value if a selection is required, and there are no options', waitForAsync(async () => { const input = fixture.nativeElement.querySelector('input'); const {stateCtrl, trigger, states} = fixture.componentInstance; fixture.componentInstance.requireSelection = true; fixture.changeDetectorRef.markForCheck(); stateCtrl.setValue(states[1]); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('California'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); fixture.componentInstance.states = fixture.componentInstance.filteredStates = []; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const spy = jasmine.createSpy('optionSelected spy'); const subscription = trigger.optionSelections.subscribe(spy); dispatchFakeEvent(document, 'click'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(input.value).toBe('California'); expect(stateCtrl.value).toEqual({code: 'CA', name: 'California'}); expect(spy).not.toHaveBeenCalled(); subscription.unsubscribe(); })); it('should clear the value if requireSelection is enabled and the user edits the input before clicking away', waitForAsync(async () => { const input = fixture.nativeElement.querySelector('input'); const {stateCtrl, trigger} = fixture.componentInstance; fixture.componentInstance.requireSelection = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); // Simulate opening the input and clicking the first option. trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); (overlayContainerElement.querySelector('mat-option') as HTMLElement).click(); await new Promise(r => setTimeout(r)); fixture.detectChanges(); expect(trigger.panelOpen).toBe(false); expect(input.value).toBe('Alabama'); expect(stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'}); // Simulate pressing backspace while focus is still on the input. dispatchFakeEvent(input, 'keydown'); input.value = 'Alabam'; fixture.detectChanges(); dispatchFakeEvent(input, 'input'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(trigger.panelOpen).toBe(true); expect(input.value).toBe('Alabam'); expect(stateCtrl.value).toEqual({code: 'AL', name: 'Alabama'}); // Simulate clicking away. input.blur(); dispatchFakeEvent(document, 'click'); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(trigger.panelOpen).toBe(false); expect(input.value).toBe(''); expect(stateCtrl.value).toBe(null); })); }); describe('panel closing', () => { let fixture: ComponentFixture<SimpleAutocomplete>; let input: HTMLInputElement; let trigger: MatAutocompleteTrigger; let closingActionSpy: jasmine.Spy; let closingActionsSub: Subscription; beforeEach(fakeAsync(() => { fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); trigger = fixture.componentInstance.trigger; closingActionSpy = jasmine.createSpy('closing action listener'); closingActionsSub = trigger.panelClosingActions.subscribe(closingActionSpy); input = fixture.debugElement.query(By.css('input'))!.nativeElement; fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); flush(); })); afterEach(() => { closingActionsSub.unsubscribe(); }); it('should emit panel close event when clicking away', () => { expect(closingActionSpy).not.toHaveBeenCalled(); dispatchFakeEvent(document, 'click'); expect(closingActionSpy).toHaveBeenCalledWith(null); }); it('should emit panel close event when tabbing out', () => { const tabEvent = createKeyboardEvent('keydown', TAB); input.focus(); expect(closingActionSpy).not.toHaveBeenCalled(); trigger._handleKeydown(tabEvent); expect(closingActionSpy).toHaveBeenCalledWith(null); }); it('should not emit when tabbing away from a closed panel', waitForAsync(async () => { const tabEvent = createKeyboardEvent('keydown', TAB); input.focus(); await new Promise(r => setTimeout(r)); trigger._handleKeydown(tabEvent); // Ensure that it emitted once while the panel was open. expect(closingActionSpy).toHaveBeenCalledTimes(1); trigger._handleKeydown(tabEvent); // Ensure that it didn't emit again when tabbing out again. expect(closingActionSpy).toHaveBeenCalledTimes(1); })); it('should emit panel close event when selecting an option', () => { const option = overlayContainerElement.querySelector('mat-option') as HTMLElement; expect(closingActionSpy).not.toHaveBeenCalled(); option.click(); expect(closingActionSpy).toHaveBeenCalledWith(jasmine.any(MatOptionSelectionChange)); }); it('should close the panel when pressing escape', () => { expect(closingActionSpy).not.toHaveBeenCalled(); dispatchKeyboardEvent(document.body, 'keydown', ESCAPE); expect(closingActionSpy).toHaveBeenCalledWith(null); }); // TODO(mmalerba): This test previously only passed because it wasn't properly flushed. // We should figure out if this is indeed the desired behavior, and if so fix the // implementation. // tslint:disable-next-line:ban xit('should not prevent escape key propagation when there are no options', waitForAsync(async () => { fixture.componentInstance.filteredStates = fixture.componentInstance.states = []; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); const event = createKeyboardEvent('keydown', ESCAPE); spyOn(event, 'stopPropagation').and.callThrough(); dispatchEvent(document.body, event); fixture.detectChanges(); expect(event.stopPropagation).not.toHaveBeenCalled(); })); }); describe('without matInput', () => { let fixture: ComponentFixture<AutocompleteWithNativeInput>; beforeEach(() => { fixture = createComponent(AutocompleteWithNativeInput); fixture.detectChanges(); }); it('should not throw when clicking outside', fakeAsync(() => { dispatchFakeEvent(fixture.debugElement.query(By.css('input'))!.nativeElement, 'focus'); fixture.detectChanges(); flush(); expect(() => dispatchFakeEvent(document, 'click')).not.toThrow(); })); }); describe('with panel classes in the default options', () => { it('should apply them if provided as string', () => { const fixture = createComponent(SimpleAutocomplete, [ {provide: MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, useValue: {overlayPanelClass: 'default1'}}, ]); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panelClassList = overlayContainerElement.querySelector('.cdk-overlay-pane')!.classList; expect(panelClassList).toContain('default1'); }); it('should apply them if provided as array', () => { const fixture = createComponent(SimpleAutocomplete, [ { provide: MAT_AUTOCOMPLETE_DEFAULT_OPTIONS, useValue: {overlayPanelClass: ['default1', 'default2']}, }, ]); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const panelClassList = overlayContainerElement.querySelector('.cdk-overlay-pane')!.classList; expect(panelClassList).toContain('default1'); expect(panelClassList).toContain('default2'); }); });
116158
describe('misc', () => { it('should allow basic use without any forms directives', () => { expect(() => { const fixture = createComponent(AutocompleteWithoutForms); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; typeInElement(input, 'd'); fixture.detectChanges(); const options = overlayContainerElement.querySelectorAll( 'mat-option', ) as NodeListOf<HTMLElement>; expect(options.length).toBe(1); }).not.toThrowError(); }); it('should display an empty input when the value is undefined with ngModel', () => { const fixture = createComponent(AutocompleteWithNgModel); fixture.detectChanges(); expect(fixture.debugElement.query(By.css('input'))!.nativeElement.value).toBe(''); }); it('should display the number when the selected option is the number zero', fakeAsync(() => { const fixture = createComponent(AutocompleteWithNumbers); fixture.componentInstance.selectedNumber = 0; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); expect(fixture.debugElement.query(By.css('input'))!.nativeElement.value).toBe('0'); })); it('should work when input is wrapped in ngIf', () => { const fixture = createComponent(NgIfAutocomplete); fixture.detectChanges(); dispatchFakeEvent(fixture.debugElement.query(By.css('input'))!.nativeElement, 'focusin'); fixture.detectChanges(); expect(fixture.componentInstance.trigger.panelOpen) .withContext(`Expected panel state to read open when input is focused.`) .toBe(true); expect(overlayContainerElement.textContent) .withContext(`Expected panel to display when input is focused.`) .toContain('One'); expect(overlayContainerElement.textContent) .withContext(`Expected panel to display when input is focused.`) .toContain('Two'); }); it('should filter properly with ngIf after setting the active item', () => { const fixture = createComponent(NgIfAutocomplete); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); fixture.detectChanges(); const DOWN_ARROW_EVENT = createKeyboardEvent('keydown', DOWN_ARROW); fixture.componentInstance.trigger._handleKeydown(DOWN_ARROW_EVENT); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; typeInElement(input, 'o'); fixture.detectChanges(); expect(fixture.componentInstance.matOptions.length).toBe(2); }); it('should throw if the user attempts to open the panel too early', () => { const fixture = createComponent(AutocompleteWithoutPanel); fixture.detectChanges(); expect(() => { fixture.componentInstance.trigger.openPanel(); }).toThrow(getMatAutocompleteMissingPanelError()); }); it('should not throw on init, even if the panel is not defined', fakeAsync(() => { expect(() => { const fixture = createComponent(AutocompleteWithoutPanel); fixture.componentInstance.control.setValue('Something'); fixture.detectChanges(); tick(); }).not.toThrow(); })); it('should transfer the mat-autocomplete classes to the panel element', fakeAsync(() => { const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); tick(); fixture.detectChanges(); const autocomplete = fixture.debugElement.nativeElement.querySelector('mat-autocomplete'); const panel = overlayContainerElement.querySelector('.mat-mdc-autocomplete-panel')!; expect(autocomplete.classList).not.toContain('class-one'); expect(autocomplete.classList).not.toContain('class-two'); expect(panel.classList).toContain('class-one'); expect(panel.classList).toContain('class-two'); })); it('should remove old classes when the panel class changes', fakeAsync(() => { const fixture = createComponent(SimpleAutocomplete); fixture.detectChanges(); fixture.componentInstance.trigger.openPanel(); tick(); fixture.detectChanges(); const classList = overlayContainerElement.querySelector( '.mat-mdc-autocomplete-panel', )!.classList; expect(classList).toContain('mat-mdc-autocomplete-visible'); expect(classList).toContain('class-one'); expect(classList).toContain('class-two'); fixture.componentInstance.panelClass = 'class-three class-four'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(classList).not.toContain('class-one'); expect(classList).not.toContain('class-two'); expect(classList).toContain('mat-mdc-autocomplete-visible'); expect(classList).toContain('class-three'); expect(classList).toContain('class-four'); })); it('should reset correctly when closed programmatically', waitForAsync(async () => { const scrolledSubject = new Subject(); const fixture = createComponent(SimpleAutocomplete, [ { provide: ScrollDispatcher, useValue: {scrolled: () => scrolledSubject}, }, { provide: MAT_AUTOCOMPLETE_SCROLL_STRATEGY, useFactory: (overlay: Overlay) => () => overlay.scrollStrategies.close(), deps: [Overlay], }, ]); fixture.detectChanges(); const trigger = fixture.componentInstance.trigger; trigger.openPanel(); fixture.detectChanges(); await new Promise(r => setTimeout(r)); expect(trigger.panelOpen).withContext('Expected panel to be open.').toBe(true); scrolledSubject.next(); fixture.detectChanges(); expect(trigger.panelOpen).withContext('Expected panel to be closed.').toBe(false); })); it('should handle autocomplete being attached to number inputs', () => { const fixture = createComponent(AutocompleteWithNumberInputAndNgModel); fixture.detectChanges(); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; typeInElement(input, '1337'); fixture.detectChanges(); expect(fixture.componentInstance.selectedValue).toBe(1337); }); it('should not focus the option when DOWN key is pressed', () => { const fixture = createComponent(SimpleAutocomplete); const input = fixture.debugElement.query(By.css('input'))!.nativeElement; fixture.detectChanges(); const spy = spyOn(console, 'error'); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); dispatchKeyboardEvent(input, 'keydown', DOWN_ARROW); fixture.detectChanges(); // Note: for some reason the error here gets logged using console.error, rather than being // thrown, hence why we use a spy to assert against it, rather than `.not.toThrow`. expect(spy).not.toHaveBeenCalled(); }); });
116162
@Component({ template: ` @if (isVisible) { <mat-form-field> <input matInput placeholder="Choose" [matAutocomplete]="auto" [formControl]="optionCtrl"> </mat-form-field> } <mat-autocomplete #auto="matAutocomplete"> @for (option of filteredOptions | async; track option) { <mat-option [value]="option"> {{option}} </mat-option> } </mat-autocomplete> `, standalone: false, }) class NgIfAutocomplete { optionCtrl = new FormControl(''); filteredOptions: Observable<any>; isVisible = true; options = ['One', 'Two', 'Three']; @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; @ViewChildren(MatOption) matOptions: QueryList<MatOption>; constructor() { this.filteredOptions = this.optionCtrl.valueChanges.pipe( startWith(null), map(val => { return val ? this.options.filter(option => new RegExp(val, 'gi').test(option)) : this.options.slice(); }), ); } } @Component({ template: ` <mat-form-field> <input matInput placeholder="State" [matAutocomplete]="auto" (input)="onInput($event.target?.value)"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (state of filteredStates; track state) { <mat-option [value]="state"> <span> {{ state }} </span> </mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithoutForms { filteredStates: any[]; states = ['Alabama', 'California', 'Florida']; constructor() { this.filteredStates = this.states.slice(); } onInput(value: any) { this.filteredStates = this.states.filter(s => new RegExp(value, 'gi').test(s)); } } @Component({ template: ` <mat-form-field> <input matInput placeholder="State" [matAutocomplete]="auto" [(ngModel)]="selectedState" (ngModelChange)="onInput($event)"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (state of filteredStates; track state) { <mat-option [value]="state"> <span>{{ state }}</span> </mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithNgModel { filteredStates: any[]; selectedState: string; states = ['New York', 'Washington', 'Oregon']; @ViewChild(MatAutocompleteTrigger, {static: true}) trigger: MatAutocompleteTrigger; constructor() { this.filteredStates = this.states.slice(); } onInput(value: any) { this.filteredStates = this.states.filter(s => new RegExp(value, 'gi').test(s)); } } @Component({ template: ` <mat-form-field> <input matInput placeholder="Number" [matAutocomplete]="auto" [(ngModel)]="selectedNumber"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (number of numbers; track number) { <mat-option [value]="number"> <span>{{ number }}</span> </mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithNumbers { selectedNumber: number; numbers = [0, 1, 2]; } @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: ` <mat-form-field> <input type="text" matInput [matAutocomplete]="auto"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (option of options; track option) { <mat-option [value]="option">{{ option }}</mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithOnPushDelay implements OnInit { @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; options: string[]; ngOnInit() { setTimeout(() => { this.options = ['One']; }, 1000); } } @Component({ template: ` <input placeholder="Choose" [matAutocomplete]="auto" [formControl]="optionCtrl"> <mat-autocomplete #auto="matAutocomplete"> @for (option of filteredOptions | async; track option) { <mat-option [value]="option">{{option}}</mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithNativeInput { optionCtrl = new FormControl(''); filteredOptions: Observable<any>; options = ['En', 'To', 'Tre', 'Fire', 'Fem']; @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; @ViewChildren(MatOption) matOptions: QueryList<MatOption>; constructor() { this.filteredOptions = this.optionCtrl.valueChanges.pipe( startWith(null), map(val => { return val ? this.options.filter(option => new RegExp(val, 'gi').test(option)) : this.options.slice(); }), ); } } @Component({ template: `<input placeholder="Choose" [matAutocomplete]="auto" [formControl]="control">`, standalone: false, }) class AutocompleteWithoutPanel { @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; control = new FormControl(''); } @Component({ template: ` <mat-form-field> <input matInput placeholder="State" [matAutocomplete]="auto" [(ngModel)]="selectedState"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (group of stateGroups; track group) { <mat-optgroup [label]="group.title"> @for (state of group.states; track state) { <mat-option [value]="state"> <span>{{ state }}</span> </mat-option> } </mat-optgroup> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithGroups { @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; selectedState: string; stateGroups = [ { title: 'One', states: ['Alabama', 'California', 'Florida', 'Oregon'], }, { title: 'Two', states: ['Kansas', 'Massachusetts', 'New York', 'Pennsylvania'], }, { title: 'Three', states: ['Tennessee', 'Virginia', 'Wyoming', 'Alaska'], }, ]; } @Component({ template: ` <mat-form-field> <input matInput placeholder="State" [matAutocomplete]="auto" [(ngModel)]="selectedState"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @if (true) { @for (group of stateGroups; track group) { <mat-optgroup [label]="group.title"> @for (state of group.states; track state) { <mat-option [value]="state"> <span>{{ state }}</span> </mat-option> } </mat-optgroup> } } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithIndirectGroups extends AutocompleteWithGroups {} @Component({ template: ` <mat-form-field> <input matInput placeholder="State" [matAutocomplete]="auto" [(ngModel)]="selectedState"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete" (optionSelected)="optionSelected($event)"> @for (state of states; track state) { <mat-option [value]="state"> <span>{{ state }}</span> </mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithSelectEvent { selectedState: string; states = ['New York', 'Washington', 'Oregon']; optionSelected = jasmine.createSpy('optionSelected callback'); @ViewChild(MatAutocompleteTrigger) trigger: MatAutocompleteTrigger; @ViewChild(MatAutocomplete) autocomplete: MatAutocomplete; } @Component({ template: ` <input [formControl]="formControl" [matAutocomplete]="auto"/> <mat-autocomplete #auto="matAutocomplete"></mat-autocomplete> `, standalone: false, }) class PlainAutocompleteInputWithFormControl { formControl = new FormControl(''); } @Component({ template: ` <mat-form-field> <input type="number" matInput [matAutocomplete]="auto" [(ngModel)]="selectedValue"> </mat-form-field> <mat-autocomplete #auto="matAutocomplete"> @for (value of values; track value) { <mat-option [value]="value">{{value}}</mat-option> } </mat-autocomplete> `, standalone: false, }) class AutocompleteWithNumberInputAndNgModel { selectedValue: number; values = [1, 2, 3]; }
116246
Chips allow users to view information, make selections, filter content, and enter data. ### Static Chips Chips are always used inside a container. To create chips, start with a `<mat-chip-set>` element. Then, nest `<mat-chip>` elements inside the `<mat-chip-set>`. <!-- example(chips-overview) --> By default, `<mat-chip>` renders a chip with Material Design styles applied. For a chip with no styles applied, use `<mat-basic-chip>`. #### Disabled appearance Although `<mat-chip>` is not interactive, you can set the `disabled` Input to give it disabled appearance. ```html <mat-chip disabled>Orange</mat-chip> ``` ### Selection Chips Use `<mat-chip-listbox>` and `<mat-chip-option>` for selecting one or many items from a list. Start with creating a `<mat-chip-listbox>` element. If the user may select more than one option, add the `multiple` attribute. Nest a `<mat-chip-option>` element inside the `<mat-chip-listbox>` for each available option. #### Disabled `<mat-chip-option>` Use the `disabled` Input to disable a `<mat-chip-option>`. This gives the `<mat-chip-option>` a disabled appearance and prevents the user from interacting with it. ```html <mat-chip-option disabled>Orange</mat-chip-option> ``` #### Keyboard Interactions Users can move through the chips using the arrow keys and select/deselect them with space. Chips also gain focus when clicked, ensuring keyboard navigation starts at the currently focused chip. ### Chips connected to an input field Use `<mat-chip-grid>` and `<mat-chip-row>` for assisting users with text entry. Chips are always used inside a container. To create chips connected to an input field, start by creating a `<mat-chip-grid>` as the container. Add an `<input/>` element, and register it to the `<mat-chip-grid>` by passing the `matChipInputFor` Input. Always use an `<input/>` element with `<mat-chip-grid>`. Nest a `<mat-chip-row>` element inside the `<mat-chip-grid>` for each piece of data entered by the user. An example of using chips for text input. <!-- example(chips-input) --> ### Use with `@angular/forms` Chips are compatible with `@angular/forms` and supports both `FormsModule` and `ReactiveFormsModule`. <!-- example(chips-template-form) --> <!-- example(chips-reactive-form) --> #### Disabled `<mat-chip-row>` Use the `disabled` Input to disable a `<mat-chip-row>`. This gives the `<mat-chip-row>` a disabled appearance and prevents the user from interacting with it. ```html <mat-chip-row disabled>Orange</mat-chip-row> ``` #### Keyboard Interactions Users can move through the chips using the arrow keys and select/deselect them with the space. Chips also gain focus when clicked, ensuring keyboard navigation starts at the appropriate chip. Users can press delete to remove a chip. Pressing delete triggers the `removed` Output on the chip, so be sure to implement `removed` if you require that functionality. #### Autocomplete A `<mat-chip-grid>` can be combined with `<mat-autocomplete>` to enable free-form chip input with suggestions. <!-- example(chips-autocomplete) --> ### Icons You can add icons to chips to identify entities (like individuals) and provide additional functionality. #### Adding up to two icons with content projection You can add two additional icons to an individual chip. A chip has two slots to display icons using content projection. All variants of chips support adding icons including `<mat-chip>`, `<mat-chip-option>`, and `<mat-chip-row>`. A chip has a front slot for adding an avatar image. To add an avatar, nest an element with `matChipAvatar` attribute inside of `<mat-chip>`. <!-- example(chips-avatar) --> You can add an additional icon to the back slot by nesting an element with either the `matChipTrailingIcon` or `matChipRemove` attribute. #### Remove Button Sometimes the end user would like the ability to remove a chip. You can provide that functionality using `matChipRemove`. `matChipRemove` renders to the back slot of a chip and triggers the `removed` Output when clicked. To create a remove button, nest a `<button>` element with `matChipRemove` attribute inside the `<mat-chip-option>`. Be sure to implement the `removed` Output. ```html <mat-chip-option> Orange <button matChipRemove aria-label="Remove orange"> <mat-icon>cancel</mat-icon> </button> </mat-chip-option> ``` See the [accessibility](#accessibility) section for best practices on implementing the `removed` Output and creating accessible icons. ### Orientation By default, chips are displayed horizontally. To stack chips vertically, apply the `mat-mdc-chip-set-stacked` class to `<mat-chip-set>`, `<mat-chip-listbox>` or `<mat-chip-grid>`. <!-- example(chips-stacked) --> ### Specifying global configuration defaults Use the `MAT_CHIPS_DEFAULT_OPTIONS` token to specify default options for the chips module. ```html @NgModule({ providers: [ { provide: MAT_CHIPS_DEFAULT_OPTIONS, useValue: { separatorKeyCodes: [COMMA, SPACE] } } ] }) ``` ### Interaction Patterns The chips components support 3 user interaction patterns, each with its own container and chip elements: #### Listbox `<mat-chip-listbox>` and `<mat-chip-option>` : These elements implement a listbox accessibility pattern. Use them to present set of user selectable options. ```html <mat-chip-listbox aria-label="select a shirt size"> <mat-chip-option> Small </mat-chip-option> <mat-chip-option> Medium </mat-chip-option> <mat-chip-option> Large </mat-chip-option> </mat-chip-listbox> ``` #### Text Entry `<mat-chip-grid>` and `<mat-chip-row>` : These elements implement a grid accessibility pattern. Use them as part of a free form input that allows users to enter text to add chips. ```html <mat-form-field> <mat-chip-grid #myChipGrid [(ngModel)]="mySelection" aria-label="enter sandwich fillings"> @for (filling of fillings; track filling) { <mat-chip-row (removed)="remove(filling)"> {{filling.name}} <button matChipRemove> <mat-icon>cancel</mat-icon> </button> </mat-chip-row> } <input [matChipInputFor]="myChipGrid" [matChipInputSeparatorKeyCodes]="separatorKeysCodes" (matChipInputTokenEnd)="add($event)" /> </mat-chip-grid> </mat-form-field> ``` #### Static Content `<mat-chip-set>` and `<mat-chip>` as an unordered list : Present a list of items that are not interactive. This interaction pattern mimics using `ul` and `li` elements. Apply role="list" to the `<mat-list>`. Apply role="listitem" to each `<mat-list-item>`. ```html <mat-chip-set role="list"> <mat-chip role="listitem"> Sugar </mat-chip> <mat-chip role="listitem"> Spice </mat-chip> <mat-chip role="listitem"> Everything Nice </mat-chip> </mat-chip-set> ``` `<mat-chip-set>` and `<mat-chip>` : These elements do not implement any specific accessibility pattern. Add the appropriate accessibility depending on the context. Note that Angular Material does not intend `<mat-chip>`, `<mat-basic-chip>`, and `<mat-chip-set>` to be interactive. ```html <mat-chip-set> <mat-chip> John </mat-chip> <mat-chip> Paul </mat-chip> <mat-chip> James </mat-chip> </mat-chip-set> ``` ### Accessibility The [Interaction Patterns](#interaction-patterns) section describes the three variants of chips available. Choose the chip variant that best matches your use case. For both MatChipGrid and MatChipListbox, always apply an accessible label to the control via `aria-label` or `aria-labelledby`. Always apply MatChipRemove to a `<button>` element, never a `<mat-icon>` element. When using MatChipListbox, never nest other interactive controls inside of the `<mat-chip-option>` element. Nesting controls degrades the experience for assistive technology users. By default, `MatChipListbox` displays a checkmark to identify selected items. While you can hide the checkmark indicator for single-selection via `hideSingleSelectionIndicator`, this makes the component less accessible by making it harder or impossible for users to visually identify selected items. When a chip is editable, provide instructions to assistive technology how to edit the chip using a keyboard. One way to accomplish this is adding an `aria-description` attribute with instructions to press enter to edit the chip.
116292
{ protected _elementRef = inject<ElementRef<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>>(ElementRef); protected _platform = inject(Platform); ngControl = inject(NgControl, {optional: true, self: true})!; private _autofillMonitor = inject(AutofillMonitor); private _ngZone = inject(NgZone); protected _formField? = inject<MatFormField>(MAT_FORM_FIELD, {optional: true}); protected _uid = `mat-input-${nextUniqueId++}`; protected _previousNativeValue: any; private _inputValueAccessor: {value: any}; private _signalBasedValueAccessor?: {value: WritableSignal<any>}; private _previousPlaceholder: string | null; private _errorStateTracker: _ErrorStateTracker; private _webkitBlinkWheelListenerAttached = false; private _config = inject(MAT_INPUT_CONFIG, {optional: true}); /** Whether the component is being rendered on the server. */ readonly _isServer: boolean; /** Whether the component is a native html select. */ readonly _isNativeSelect: boolean; /** Whether the component is a textarea. */ readonly _isTextarea: boolean; /** Whether the input is inside of a form field. */ readonly _isInFormField: boolean; /** * Implemented as part of MatFormFieldControl. * @docs-private */ focused: boolean = false; /** * Implemented as part of MatFormFieldControl. * @docs-private */ readonly stateChanges: Subject<void> = new Subject<void>(); /** * Implemented as part of MatFormFieldControl. * @docs-private */ controlType: string = 'mat-input'; /** * Implemented as part of MatFormFieldControl. * @docs-private */ autofilled = false; /** * Implemented as part of MatFormFieldControl. * @docs-private */ @Input() get disabled(): boolean { return this._disabled; } set disabled(value: BooleanInput) { this._disabled = coerceBooleanProperty(value); // Browsers may not fire the blur event if the input is disabled too quickly. // Reset from here to ensure that the element doesn't become stuck. if (this.focused) { this.focused = false; this.stateChanges.next(); } } protected _disabled = false; /** * Implemented as part of MatFormFieldControl. * @docs-private */ @Input() get id(): string { return this._id; } set id(value: string) { this._id = value || this._uid; } protected _id: string; /** * Implemented as part of MatFormFieldControl. * @docs-private */ @Input() placeholder: string; /** * Name of the input. * @docs-private */ @Input() name: string; /** * Implemented as part of MatFormFieldControl. * @docs-private */ @Input() get required(): boolean { return this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false; } set required(value: BooleanInput) { this._required = coerceBooleanProperty(value); } protected _required: boolean | undefined; /** Input type of the element. */ @Input() get type(): string { return this._type; } set type(value: string) { this._type = value || 'text'; this._validateType(); // When using Angular inputs, developers are no longer able to set the properties on the native // input element. To ensure that bindings for `type` work, we need to sync the setter // with the native property. Textarea elements don't support the type property or attribute. if (!this._isTextarea && getSupportedInputTypes().has(this._type)) { (this._elementRef.nativeElement as HTMLInputElement).type = this._type; } this._ensureWheelDefaultBehavior(); } protected _type = 'text'; /** An object used to control when error messages are shown. */ @Input() get errorStateMatcher() { return this._errorStateTracker.matcher; } set errorStateMatcher(value: ErrorStateMatcher) { this._errorStateTracker.matcher = value; } /** * Implemented as part of MatFormFieldControl. * @docs-private */ @Input('aria-describedby') userAriaDescribedBy: string; /** * Implemented as part of MatFormFieldControl. * @docs-private */ @Input() get value(): string { return this._signalBasedValueAccessor ? this._signalBasedValueAccessor.value() : this._inputValueAccessor.value; } set value(value: any) { if (value !== this.value) { if (this._signalBasedValueAccessor) { this._signalBasedValueAccessor.value.set(value); } else { this._inputValueAccessor.value = value; } this.stateChanges.next(); } } /** Whether the element is readonly. */ @Input() get readonly(): boolean { return this._readonly; } set readonly(value: BooleanInput) { this._readonly = coerceBooleanProperty(value); } private _readonly = false; /** Whether the input should remain interactive when it is disabled. */ @Input({transform: booleanAttribute}) disabledInteractive: boolean; /** Whether the input is in an error state. */ get errorState() { return this._errorStateTracker.errorState; } set errorState(value: boolean) { this._errorStateTracker.errorState = value; } protected _neverEmptyInputTypes = [ 'date', 'datetime', 'datetime-local', 'month', 'time', 'week', ].filter(t => getSupportedInputTypes().has(t)); constructor(...args: unknown[]); constructor() { const parentForm = inject(NgForm, {optional: true}); const parentFormGroup = inject(FormGroupDirective, {optional: true}); const defaultErrorStateMatcher = inject(ErrorStateMatcher); const accessor = inject(MAT_INPUT_VALUE_ACCESSOR, {optional: true, self: true}); const element = this._elementRef.nativeElement; const nodeName = element.nodeName.toLowerCase(); if (accessor) { if (isSignal(accessor.value)) { this._signalBasedValueAccessor = accessor; } else { this._inputValueAccessor = accessor; } } else { // If no input value accessor was explicitly specified, use the element as the input value // accessor. this._inputValueAccessor = element; } this._previousNativeValue = this.value; // Force setter to be called in case id was not specified. this.id = this.id; // On some versions of iOS the caret gets stuck in the wrong place when holding down the delete // key. In order to get around this we need to "jiggle" the caret loose. Since this bug only // exists on iOS, we only bother to install the listener on iOS. if (this._platform.IOS) { this._ngZone.runOutsideAngular(() => { element.addEventListener('keyup', this._iOSKeyupListener); }); } this._errorStateTracker = new _ErrorStateTracker( defaultErrorStateMatcher, this.ngControl, parentFormGroup, parentForm, this.stateChanges, ); this._isServer = !this._platform.isBrowser; this._isNativeSelect = nodeName === 'select'; this._isTextarea = nodeName === 'textarea'; this._isInFormField = !!this._formField; this.disabledInteractive = this._config?.disabledInteractive || false; if (this._isNativeSelect) { this.controlType = (element as HTMLSelectElement).multiple ? 'mat-native-select-multiple' : 'mat-native-select'; } if (this._signalBasedValueAccessor) { effect(() => { // Read the value so the effect can register the dependency. this._signalBasedValueAccessor!.value(); this.stateChanges.next(); }); } } ngAfterViewInit() { if (this._platform.isBrowser) { this._autofillMonitor.monitor(this._elementRef.nativeElement).subscribe(event => { this.autofilled = event.isAutofilled; this.stateChanges.next(); }); } } ngOnChanges() { this.stateChanges.next(); } ngOnDestroy() { this.stateChanges.complete(); if (this._platform.isBrowser) { this._autofillMonitor.stopMonitoring(this._elementRef.nativeElement); } if (this._platform.IOS) { this._elementRef.nativeElement.removeEventListener('keyup', this._iOSKeyupListener); } if (this._webkitBlinkWheelListenerAttached) { this._elementRef.nativeElement.removeEventListener('wheel', this._webkitBlinkWheelListener); } }
116306
Please see the official documentation at https://material.angular.io/components/component/input
116343
class MatSlideToggle implements OnDestroy, AfterContentInit, OnChanges, ControlValueAccessor, Validator { private _elementRef = inject(ElementRef); protected _focusMonitor = inject(FocusMonitor); protected _changeDetectorRef = inject(ChangeDetectorRef); defaults = inject<MatSlideToggleDefaultOptions>(MAT_SLIDE_TOGGLE_DEFAULT_OPTIONS); private _onChange = (_: any) => {}; private _onTouched = () => {}; private _validatorOnChange = () => {}; private _uniqueId: string; private _checked: boolean = false; private _createChangeEvent(isChecked: boolean) { return new MatSlideToggleChange(this, isChecked); } /** Unique ID for the label element. */ _labelId: string; /** Returns the unique id for the visual hidden button. */ get buttonId(): string { return `${this.id || this._uniqueId}-button`; } /** Reference to the MDC switch element. */ @ViewChild('switch') _switchElement: ElementRef<HTMLElement>; /** Focuses the slide-toggle. */ focus(): void { this._switchElement.nativeElement.focus(); } /** Whether noop animations are enabled. */ _noopAnimations: boolean; /** Whether the slide toggle is currently focused. */ _focused: boolean; /** Name value will be applied to the input element if present. */ @Input() name: string | null = null; /** A unique id for the slide-toggle input. If none is supplied, it will be auto-generated. */ @Input() id: string; /** Whether the label should appear after or before the slide-toggle. Defaults to 'after'. */ @Input() labelPosition: 'before' | 'after' = 'after'; /** Used to set the aria-label attribute on the underlying input element. */ @Input('aria-label') ariaLabel: string | null = null; /** Used to set the aria-labelledby attribute on the underlying input element. */ @Input('aria-labelledby') ariaLabelledby: string | null = null; /** Used to set the aria-describedby attribute on the underlying input element. */ @Input('aria-describedby') ariaDescribedby: string; /** Whether the slide-toggle is required. */ @Input({transform: booleanAttribute}) required: boolean; // TODO(crisbeto): this should be a ThemePalette, but some internal apps were abusing // the lack of type checking previously and assigning random strings. /** * Theme color of the slide toggle. This API is supported in M2 themes only, * it has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() color: string | undefined; /** Whether the slide toggle is disabled. */ @Input({transform: booleanAttribute}) disabled: boolean = false; /** Whether the slide toggle has a ripple. */ @Input({transform: booleanAttribute}) disableRipple: boolean = false; /** Tabindex of slide toggle. */ @Input({transform: (value: unknown) => (value == null ? 0 : numberAttribute(value))}) tabIndex: number = 0; /** Whether the slide-toggle element is checked or not. */ @Input({transform: booleanAttribute}) get checked(): boolean { return this._checked; } set checked(value: boolean) { this._checked = value; this._changeDetectorRef.markForCheck(); } /** Whether to hide the icon inside of the slide toggle. */ @Input({transform: booleanAttribute}) hideIcon: boolean; /** Whether the slide toggle should remain interactive when it is disabled. */ @Input({transform: booleanAttribute}) disabledInteractive: boolean; /** An event will be dispatched each time the slide-toggle changes its value. */ @Output() readonly change = new EventEmitter<MatSlideToggleChange>(); /** * An event will be dispatched each time the slide-toggle input is toggled. * This event is always emitted when the user toggles the slide toggle, but this does not mean * the slide toggle's value has changed. */ @Output() readonly toggleChange: EventEmitter<void> = new EventEmitter<void>(); /** Returns the unique id for the visual hidden input. */ get inputId(): string { return `${this.id || this._uniqueId}-input`; } constructor(...args: unknown[]); constructor() { inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader); const tabIndex = inject(new HostAttributeToken('tabindex'), {optional: true}); const defaults = this.defaults; const animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true}); this.tabIndex = tabIndex == null ? 0 : parseInt(tabIndex) || 0; this.color = defaults.color || 'accent'; this._noopAnimations = animationMode === 'NoopAnimations'; this.id = this._uniqueId = `mat-mdc-slide-toggle-${++nextUniqueId}`; this.hideIcon = defaults.hideIcon ?? false; this.disabledInteractive = defaults.disabledInteractive ?? false; this._labelId = this._uniqueId + '-label'; } ngAfterContentInit() { this._focusMonitor.monitor(this._elementRef, true).subscribe(focusOrigin => { if (focusOrigin === 'keyboard' || focusOrigin === 'program') { this._focused = true; this._changeDetectorRef.markForCheck(); } else if (!focusOrigin) { // When a focused element becomes disabled, the browser *immediately* fires a blur event. // Angular does not expect events to be raised during change detection, so any state // change (such as a form control's ng-touched) will cause a changed-after-checked error. // See https://github.com/angular/angular/issues/17793. To work around this, we defer // telling the form control it has been touched until the next tick. Promise.resolve().then(() => { this._focused = false; this._onTouched(); this._changeDetectorRef.markForCheck(); }); } }); } ngOnChanges(changes: SimpleChanges): void { if (changes['required']) { this._validatorOnChange(); } } ngOnDestroy() { this._focusMonitor.stopMonitoring(this._elementRef); } /** Implemented as part of ControlValueAccessor. */ writeValue(value: any): void { this.checked = !!value; } /** Implemented as part of ControlValueAccessor. */ registerOnChange(fn: any): void { this._onChange = fn; } /** Implemented as part of ControlValueAccessor. */ registerOnTouched(fn: any): void { this._onTouched = fn; } /** Implemented as a part of Validator. */ validate(control: AbstractControl<boolean>): ValidationErrors | null { return this.required && control.value !== true ? {'required': true} : null; } /** Implemented as a part of Validator. */ registerOnValidatorChange(fn: () => void): void { this._validatorOnChange = fn; } /** Implemented as a part of ControlValueAccessor. */ setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; this._changeDetectorRef.markForCheck(); } /** Toggles the checked state of the slide-toggle. */ toggle(): void { this.checked = !this.checked; this._onChange(this.checked); } /** * Emits a change event on the `change` output. Also notifies the FormControl about the change. */ protected _emitChangeEvent() { this._onChange(this.checked); this.change.emit(this._createChangeEvent(this.checked)); } /** Method being called whenever the underlying button is clicked. */ _handleClick() { if (!this.disabled) { this.toggleChange.emit(); if (!this.defaults.disableToggleValue) { this.checked = !this.checked; this._onChange(this.checked); this.change.emit(new MatSlideToggleChange(this, this.checked)); } } } _getAriaLabelledBy() { if (this.ariaLabelledby) { return this.ariaLabelledby; } // Even though we have a `label` element with a `for` pointing to the button, we need the // `aria-labelledby`, because the button gets flagged as not having a label by tools like axe. return this.ariaLabel ? null : this._labelId; } }
116659
The `MatDialog` service can be used to open modal dialogs with Material Design styling and animations. <!-- example(dialog-overview) --> A dialog is opened by calling the `open` method with a component to be loaded and an optional config object. The `open` method will return an instance of `MatDialogRef`: ```ts let dialogRef = dialog.open(UserProfileComponent, { height: '400px', width: '600px', }); ``` The `MatDialogRef` provides a handle on the opened dialog. It can be used to close the dialog and to receive notifications when the dialog has been closed. Any notification Observables will complete when the dialog closes. ```ts dialogRef.afterClosed().subscribe(result => { console.log(`Dialog result: ${result}`); // Pizza! }); dialogRef.close('Pizza!'); ``` Components created via `MatDialog` can _inject_ `MatDialogRef` and use it to close the dialog in which they are contained. When closing, an optional result value can be provided. This result value is forwarded as the result of the `afterClosed` Observable. ```ts @Component({/* ... */}) export class YourDialog { constructor(public dialogRef: MatDialogRef<YourDialog>) { } closeDialog() { this.dialogRef.close('Pizza!'); } } ``` ### Specifying global configuration defaults Default dialog options can be specified by providing an instance of `MatDialogConfig` for MAT_DIALOG_DEFAULT_OPTIONS in your application's root module. ```ts @NgModule({ providers: [ {provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: {hasBackdrop: false}} ] }) ``` ### Sharing data with the Dialog component. If you want to share data with your dialog, you can use the `data` option to pass information to the dialog component. ```ts let dialogRef = dialog.open(YourDialog, { data: { name: 'austin' }, }); ``` To access the data in your dialog component, you have to use the MAT_DIALOG_DATA injection token: ```ts import {Component, Inject} from '@angular/core'; import {MAT_DIALOG_DATA} from '@angular/material/dialog'; @Component({ selector: 'your-dialog', template: 'passed in {{ data.name }}', }) export class YourDialog { constructor(@Inject(MAT_DIALOG_DATA) public data: {name: string}) { } } ``` Note that if you're using a template dialog (one that was opened with a `TemplateRef`), the data will be available implicitly in the template: ```html <ng-template let-data> Hello, {{data.name}} </ng-template> ``` <!-- example(dialog-data) --> ### Dialog content Several directives are available to make it easier to structure your dialog content: | Name | Description | |------------------------|---------------------------------------------------------------------------------------------------------------| | `mat-dialog-title` | \[Attr] Dialog title, applied to a heading element (e.g., `<h1>`, `<h2>`) | | `<mat-dialog-content>` | Primary scrollable content of the dialog. | | `<mat-dialog-actions>` | Container for action buttons at the bottom of the dialog. Button alignment can be controlled via the `align` attribute which can be set to `end` and `center`. | | `mat-dialog-close` | \[Attr] Added to a `<button>`, makes the button close the dialog with an optional result from the bound value.| For example: ```html <h2 mat-dialog-title>Delete all elements?</h2> <mat-dialog-content>This will delete all elements that are currently on this page and cannot be undone.</mat-dialog-content> <mat-dialog-actions> <button mat-button mat-dialog-close>Cancel</button> <!-- The mat-dialog-close directive optionally accepts a value as a result for the dialog. --> <button mat-button [mat-dialog-close]="true">Delete</button> </mat-dialog-actions> ``` Once a dialog opens, the dialog will automatically focus the first tabbable element. You can control which elements are tab stops with the `tabindex` attribute ```html <button mat-button tabindex="-1">Not Tabbable</button> ``` <!-- example(dialog-content) --> ### Controlling the dialog animation You can control the duration of the dialog's enter and exit animations using the `enterAnimationDuration` and `exitAnimationDuration` options. If you want to disable the dialog's animation completely, you can do so by setting the properties to `0ms`. <!-- example(dialog-animations) --> ### Accessibility `MatDialog` creates modal dialogs that implements the ARIA `role="dialog"` pattern by default. You can change the dialog's role to `alertdialog` via `MatDialogConfig`. You should provide an accessible label to this root dialog element by setting the `ariaLabel` or `ariaLabelledBy` properties of `MatDialogConfig`. You can additionally specify a description element ID via the `ariaDescribedBy` property of `MatDialogConfig`. #### Keyboard interaction By default, the escape key closes `MatDialog`. While you can disable this behavior via the `disableClose` property of `MatDialogConfig`, doing this breaks the expected interaction pattern for the ARIA `role="dialog"` pattern. #### Focus management When opened, `MatDialog` traps browser focus such that it cannot escape the root `role="dialog"` element. By default, the first tabbable element in the dialog receives focus. You can customize which element receives focus with the `autoFocus` property of `MatDialogConfig`, which supports the following values. | Value | Behavior | |------------------|--------------------------------------------------------------------------| | `first-tabbable` | Focus the first tabbable element. This is the default setting. | | `first-header` | Focus the first header element (`role="heading"`, `h1` through `h6`) | | `dialog` | Focus the root `role="dialog"` element. | | Any CSS selector | Focus the first element matching the given selector. | While the default setting applies the best behavior for most applications, special cases may benefit from these alternatives. Always test your application to verify the behavior that works best for your users. #### Focus restoration When closed, `MatDialog` restores focus to the element that previously held focus when the dialog opened. However, if that previously focused element no longer exists, you must add additional handling to return focus to an element that makes sense for the user's workflow. Opening a dialog from a menu is one common pattern that causes this situation. The menu closes upon clicking an item, thus the focused menu item is no longer in the DOM when the bottom sheet attempts to restore focus. You can add handling for this situation with the `afterClosed()` observable from `MatDialogRef`. <!-- example({"example":"dialog-from-menu", "file":"dialog-from-menu-example.ts", "region":"focus-restoration"}) -->
116661
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ViewContainerRef, Injector} from '@angular/core'; import {Direction} from '@angular/cdk/bidi'; import {ScrollStrategy} from '@angular/cdk/overlay'; import {_defaultParams} from './dialog-animations'; /** Options for where to set focus to automatically on dialog open */ export type AutoFocusTarget = 'dialog' | 'first-tabbable' | 'first-heading'; /** Valid ARIA roles for a dialog element. */ export type DialogRole = 'dialog' | 'alertdialog'; /** Possible overrides for a dialog's position. */ export interface DialogPosition { /** Override for the dialog's top position. */ top?: string; /** Override for the dialog's bottom position. */ bottom?: string; /** Override for the dialog's left position. */ left?: string; /** Override for the dialog's right position. */ right?: string; } /** * Configuration for opening a modal dialog with the MatDialog service. */ export class MatDialogConfig<D = any> { /** * Where the attached component should live in Angular's *logical* component tree. * This affects what is available for injection and the change detection order for the * component instantiated inside of the dialog. This does not affect where the dialog * content will be rendered. */ viewContainerRef?: ViewContainerRef; /** * Injector used for the instantiation of the component to be attached. If provided, * takes precedence over the injector indirectly provided by `ViewContainerRef`. */ injector?: Injector; /** ID for the dialog. If omitted, a unique one will be generated. */ id?: string; /** The ARIA role of the dialog element. */ role?: DialogRole = 'dialog'; /** Custom class for the overlay pane. */ panelClass?: string | string[] = ''; /** Whether the dialog has a backdrop. */ hasBackdrop?: boolean = true; /** Custom class for the backdrop. */ backdropClass?: string | string[] = ''; /** Whether the user can use escape or clicking on the backdrop to close the modal. */ disableClose?: boolean = false; /** Width of the dialog. */ width?: string = ''; /** Height of the dialog. */ height?: string = ''; /** Min-width of the dialog. If a number is provided, assumes pixel units. */ minWidth?: number | string; /** Min-height of the dialog. If a number is provided, assumes pixel units. */ minHeight?: number | string; /** Max-width of the dialog. If a number is provided, assumes pixel units. Defaults to 80vw. */ maxWidth?: number | string; /** Max-height of the dialog. If a number is provided, assumes pixel units. */ maxHeight?: number | string; /** Position overrides. */ position?: DialogPosition; /** Data being injected into the child component. */ data?: D | null = null; /** Layout direction for the dialog's content. */ direction?: Direction; /** ID of the element that describes the dialog. */ ariaDescribedBy?: string | null = null; /** ID of the element that labels the dialog. */ ariaLabelledBy?: string | null = null; /** Aria label to assign to the dialog element. */ ariaLabel?: string | null = null; /** Whether this is a modal dialog. Used to set the `aria-modal` attribute. */ ariaModal?: boolean = true; /** * Where the dialog should focus on open. * @breaking-change 14.0.0 Remove boolean option from autoFocus. Use string or * AutoFocusTarget instead. */ autoFocus?: AutoFocusTarget | string | boolean = 'first-tabbable'; /** * Whether the dialog should restore focus to the * previously-focused element, after it's closed. */ restoreFocus?: boolean = true; /** Whether to wait for the opening animation to finish before trapping focus. */ delayFocusTrap?: boolean = true; /** Scroll strategy to be used for the dialog. */ scrollStrategy?: ScrollStrategy; /** * Whether the dialog should close when the user goes backwards/forwards in history. * Note that this usually doesn't include clicking on links (unless the user is using * the `HashLocationStrategy`). */ closeOnNavigation?: boolean = true; /** * Alternate `ComponentFactoryResolver` to use when resolving the associated component. * @deprecated No longer used. Will be removed. * @breaking-change 20.0.0 */ componentFactoryResolver?: unknown; /** * Duration of the enter animation in ms. * Should be a number, string type is deprecated. * @breaking-change 17.0.0 Remove string signature. */ enterAnimationDuration?: string | number; /** * Duration of the exit animation in ms. * Should be a number, string type is deprecated. * @breaking-change 17.0.0 Remove string signature. */ exitAnimationDuration?: string | number; // TODO(jelbourn): add configuration for lifecycle hooks, ARIA labelling. }
116682
import {Component, inject} from '@angular/core'; import {TestBed, fakeAsync, flush} from '@angular/core/testing'; import {MAT_DIALOG_DATA, MatDialogRef, MatDialogState} from '@angular/material/dialog'; import {MatTestDialogOpener, MatTestDialogOpenerModule} from '@angular/material/dialog/testing'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; describe('MatTestDialogOpener', () => { beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [MatTestDialogOpenerModule, NoopAnimationsModule, ExampleComponent], }); })); it('should open a dialog when created', fakeAsync(() => { const fixture = TestBed.createComponent(MatTestDialogOpener.withComponent(ExampleComponent)); flush(); expect(fixture.componentInstance.dialogRef.getState()).toBe(MatDialogState.OPEN); expect(document.querySelector('mat-dialog-container')).toBeTruthy(); })); it('should throw an error if no dialog component is provided', () => { expect(() => TestBed.createComponent(MatTestDialogOpener)).toThrow( Error('MatTestDialogOpener does not have a component provided.'), ); }); it('should pass data to the component', async () => { const config = {data: 'test'}; const fixture = TestBed.createComponent( MatTestDialogOpener.withComponent(ExampleComponent, config), ); fixture.detectChanges(); await fixture.whenStable(); const dialogContainer = document.querySelector('mat-dialog-container'); expect(dialogContainer!.innerHTML).toContain('Data: test'); }); it('should get closed result data', fakeAsync(() => { const config = {data: 'test'}; const fixture = TestBed.createComponent( MatTestDialogOpener.withComponent<ExampleComponent, ExampleDialogResult>( ExampleComponent, config, ), ); flush(); const closeButton = document.querySelector('#close-btn') as HTMLElement; closeButton.click(); flush(); expect(fixture.componentInstance.closedResult).toEqual({reason: 'closed'}); })); }); interface ExampleDialogResult { reason: string; } /** Simple component for testing MatTestDialogOpener. */ @Component({ template: ` Data: {{data}} <button id="close-btn" (click)="close()">Close</button> `, standalone: true, }) class ExampleComponent { dialogRef = inject<MatDialogRef<ExampleComponent, ExampleDialogResult>>(MatDialogRef); data = inject(MAT_DIALOG_DATA); close() { this.dialogRef.close({reason: 'closed'}); } }
116687
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {ComponentType} from '@angular/cdk/overlay'; import { ChangeDetectionStrategy, Component, NgModule, NgZone, OnDestroy, ViewEncapsulation, inject, } from '@angular/core'; import {MatDialog, MatDialogConfig, MatDialogModule, MatDialogRef} from '@angular/material/dialog'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {Subscription} from 'rxjs'; /** Test component that immediately opens a dialog when bootstrapped. */ @Component({ selector: 'mat-test-dialog-opener', template: '', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class MatTestDialogOpener<T = unknown, R = unknown> implements OnDestroy { dialog = inject(MatDialog); /** Component that should be opened with the MatDialog `open` method. */ protected static component: ComponentType<unknown> | undefined; /** Config that should be provided to the MatDialog `open` method. */ protected static config: MatDialogConfig | undefined; /** MatDialogRef returned from the MatDialog `open` method. */ dialogRef: MatDialogRef<T, R>; /** Data passed to the `MatDialog` close method. */ closedResult: R | undefined; private readonly _afterClosedSubscription: Subscription; private readonly _ngZone = inject(NgZone); /** Static method that prepares this class to open the provided component. */ static withComponent<T = unknown, R = unknown>( component: ComponentType<T>, config?: MatDialogConfig, ) { MatTestDialogOpener.component = component; MatTestDialogOpener.config = config; return MatTestDialogOpener as ComponentType<MatTestDialogOpener<T, R>>; } constructor(...args: unknown[]); constructor() { if (!MatTestDialogOpener.component) { throw new Error(`MatTestDialogOpener does not have a component provided.`); } this.dialogRef = this._ngZone.run(() => this.dialog.open<T, R>( MatTestDialogOpener.component as ComponentType<T>, MatTestDialogOpener.config || {}, ), ); this._afterClosedSubscription = this.dialogRef.afterClosed().subscribe(result => { this.closedResult = result; }); } ngOnDestroy() { this._afterClosedSubscription.unsubscribe(); MatTestDialogOpener.component = undefined; MatTestDialogOpener.config = undefined; } } @NgModule({ imports: [MatDialogModule, NoopAnimationsModule, MatTestDialogOpener], }) export class MatTestDialogOpenerModule {}
116703
`<mat-form-field>` is a component used to wrap several Angular Material components and apply common [Text field](https://material.io/guidelines/components/text-fields.html) styles such as the underline, floating label, and hint messages. In this document, "form field" refers to the wrapper component `<mat-form-field>` and "form field control" refers to the component that the `<mat-form-field>` is wrapping (e.g. the input, textarea, select, etc.) The following Angular Material components are designed to work inside a `<mat-form-field>`: - [`<input matNativeControl>` &amp; `<textarea matNativeControl>`](https://material.angular.io/components/input/overview) - [`<select matNativeControl>`](https://material.angular.io/components/select/overview) - [`<mat-select>`](https://material.angular.io/components/select/overview) - [`<mat-chip-list>`](https://material.angular.io/components/chips/overview) <!-- example(form-field-overview) --> ### Form field appearance variants `mat-form-field` supports two different appearance variants which can be set via the `appearance` input: `fill` and `outline`. The `fill` appearance displays the form field with a filled background box and an underline, while the `outline` appearance shows the form field with a border all the way around. Out of the box, if you do not specify an `appearance` for the `<mat-form-field>` it will default to `fill`. However, this can be configured using a global provider to choose a different default appearance for your app. ```ts @NgModule({ providers: [ {provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: {appearance: 'outline'}} ] }) ``` <!-- example(form-field-appearance) --> ### Floating label The floating label is a text label displayed on top of the form field control when the control does not contain any text or when `<select matNativeControl>` does not show any option text. By default, when text is present the floating label floats above the form field control. The label for a form field can be specified by adding a `mat-label` element. If the form field control is marked with a `required` attribute, an asterisk will be appended to the label to indicate the fact that it is a required field. If unwanted, this can be disabled by setting the `hideRequiredMarker` property on `<mat-form-field>` The `floatLabel` property of `<mat-form-field>` can be used to change this default floating behavior. It can be set to `always` to float the label even when no text is present in the form field control, or to `auto` to restore the default behavior. <!-- example(form-field-label) --> The floating label behavior can be adjusted globally by providing a value for `MAT_FORM_FIELD_DEFAULT_OPTIONS` in your application's root module. Like the `floatLabel` input, the option can be either set to `always` or `auto`. ```ts @NgModule({ providers: [ {provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: {floatLabel: 'always'}} ] }) ``` ### Hint labels Hint labels are additional descriptive text that appears below the form field's underline. A `<mat-form-field>` can have up to two hint labels; one start-aligned (left in an LTR language, right in RTL), and one end-aligned. Hint labels are specified in one of two ways: either by using the `hintLabel` property of `<mat-form-field>`, or by adding a `<mat-hint>` element inside the form field. When adding a hint via the `hintLabel` property, it will be treated as the start hint. Hints added via the `<mat-hint>` hint element can be added to either side by setting the `align` property on `<mat-hint>` to either `start` or `end`. Attempting to add multiple hints to the same side will raise an error. <!-- example(form-field-hint) --> ### Error messages Error messages can be shown under the form field underline by adding `mat-error` elements inside the form field. Errors are hidden initially and will be displayed on invalid form fields after the user has interacted with the element or the parent form has been submitted. Since the errors occupy the same space as the hints, the hints are hidden when the errors are shown. If a form field can have more than one error state, it is up to the consumer to toggle which messages should be displayed. This can be done with CSS, `@if` or `@switch`. Multiple error messages can be shown at the same time if desired, but the `<mat-form-field>` only reserves enough space to display one error message at a time. Ensuring that enough space is available to display multiple errors is up to the user. <!-- example(form-field-error) --> ### Prefix & suffix Custom content can be included before and after the input tag, as a prefix or suffix. It will be included within the visual container that wraps the form control as per the Material specification. Adding the `matPrefix` directive to an element inside the `<mat-form-field>` will designate it as the prefix. Similarly, adding `matSuffix` will designate it as the suffix. If the prefix/suffix content is purely text-based, it is recommended to use the `matTextPrefix` or `matTextSuffix` directives which ensure that the text is aligned with the form control. <!-- example(form-field-prefix-suffix) --> ### Custom form field controls In addition to the form field controls that Angular Material provides, it is possible to create custom form field controls that work with `<mat-form-field>` in the same way. For additional information on this see the guide on [Creating Custom mat-form-field Controls](/guide/creating-a-custom-form-field-control). ### Theming The color of the form-field can be changed by specifying a `$color-variant` when applying the `mat.form-field-theme` or `mat.form-field-color` mixins (see the [theming guide](/guide/theming#using-component-color-variants) to learn more.) By default, the form-field uses the theme's primary palette. This can be changed to `'secondary'`, `'tertiary'`, or `'error'`. ### Accessibility By itself, `MatFormField` does not apply any additional accessibility treatment to a control. However, several of the form field's optional features interact with the control contained within the form field. When you provide a label via `<mat-label>`, `MatFormField` automatically associates this label with the field's control via a native `<label>` element, using the `for` attribute to reference the control's ID. If a floating label is specified, it will be automatically used as the label for the form field control. If no floating label is specified, the user should label the form field control themselves using `aria-label`, `aria-labelledby` or `<label for=...>`. When you provide informational text via `<mat-hint>` or `<mat-error>`, `MatFormField` automatically adds these elements' IDs to the control's `aria-describedby` attribute. Additionally, `MatError` applies `aria-live="polite"` by default such that assistive technology will announce errors when they appear. ### Troubleshooting #### Error: A hint was already declared for align="..." This error occurs if you have added multiple hints for the same side. Keep in mind that the `hintLabel` property adds a hint to the start side. #### Error: mat-form-field must contain a MatFormFieldControl This error occurs when you have not added a form field control to your form field. If your form field contains a native `<input>` or `<textarea>` element, make sure you've added the `matInput` directive to it and have imported `MatInputModule`. Other components that can act as a form field control include `<mat-select>`, `<mat-chip-list>`, and any custom form field controls you've created.
116841
@Component({ template: ` <table mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef mat-sort-header="a"> Column A</th> <td mat-cell *matCellDef="let row"> {{row.a}}</td> <td mat-footer-cell *matFooterCellDef> Footer A</td> </ng-container> <ng-container matColumnDef="column_b"> <th mat-header-cell *matHeaderCellDef> Column B</th> <td mat-cell *matCellDef="let row"> {{row.b}}</td> <td mat-footer-cell *matFooterCellDef> Footer B</td> </ng-container> <ng-container matColumnDef="column_c"> <th mat-header-cell *matHeaderCellDef> Column C</th> <td mat-cell *matCellDef="let row"> {{row.c}}</td> <td mat-footer-cell *matFooterCellDef> Footer C</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> <tr mat-footer-row *matFooterRowDef="columnsToRender"></tr> </table> <mat-paginator [pageSize]="5"></mat-paginator> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class ArrayDataSourceMatTableApp implements AfterViewInit { underlyingDataSource = new FakeDataSource(); dataSource = new MatTableDataSource<TestData>(); columnsToRender = ['column_a', 'column_b', 'column_c']; @ViewChild(MatTable) table: MatTable<TestData>; @ViewChild(MatPaginator) paginator: MatPaginator; @ViewChild(MatSort) sort: MatSort; @ViewChild(MatSortHeader) sortHeader: MatSortHeader; constructor() { this.underlyingDataSource.data = []; // Add three rows of data this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.connect().subscribe(data => { this.dataSource.data = data; }); } ngAfterViewInit() { this.dataSource.sort = this.sort; this.dataSource.paginator = this.paginator; } } @Component({ template: ` <table mat-table [dataSource]="dataSource" matSort> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef mat-sort-header="a"> Column A</th> <td mat-cell *matCellDef="let row"> {{row.a}}</td> </ng-container> <ng-container matColumnDef="column_b"> <th mat-header-cell *matHeaderCellDef> Column B</th> <td mat-cell *matCellDef="let row"> {{row.b}}</td> </ng-container> <ng-container matColumnDef="column_c"> <th mat-header-cell *matHeaderCellDef> Column C</th> <td mat-cell *matCellDef="let row"> {{row.c}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> </table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class MatTableWithSortApp implements OnInit { underlyingDataSource = new FakeDataSource(); dataSource = new MatTableDataSource<TestData>(); columnsToRender = ['column_a', 'column_b', 'column_c']; @ViewChild(MatTable) table: MatTable<TestData>; @ViewChild(MatSort) sort: MatSort; constructor() { this.underlyingDataSource.data = []; // Add three rows of data this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.connect().subscribe(data => { this.dataSource.data = data; }); } ngOnInit() { this.dataSource!.sort = this.sort; } } @Component({ template: ` <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef> Column A</th> <td mat-cell *matCellDef="let row"> {{row.a}}</td> </ng-container> <ng-container matColumnDef="column_b"> <th mat-header-cell *matHeaderCellDef> Column B</th> <td mat-cell *matCellDef="let row"> {{row.b}}</td> </ng-container> <ng-container matColumnDef="column_c"> <th mat-header-cell *matHeaderCellDef> Column C</th> <td mat-cell *matCellDef="let row"> {{row.c}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <tr mat-row *matRowDef="let row; columns: columnsToRender"></tr> </table> <mat-paginator [pageSize]="5"></mat-paginator> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class MatTableWithPaginatorApp implements OnInit { underlyingDataSource = new FakeDataSource(); dataSource = new MatTableDataSource<TestData>(); columnsToRender = ['column_a', 'column_b', 'column_c']; @ViewChild(MatTable) table: MatTable<TestData>; @ViewChild(MatPaginator) paginator: MatPaginator; constructor() { this.underlyingDataSource.data = []; // Add three rows of data this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.addData(); this.underlyingDataSource.connect().subscribe(data => { this.dataSource.data = data; }); } ngOnInit() { this.dataSource!.paginator = this.paginator; } } @Component({ template: ` <table mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <th mat-header-cell *matHeaderCellDef>Column A</th> <td mat-cell *matCellDef="let row">{{row.a}}</td> </ng-container> <tr mat-header-row *matHeaderRowDef="columnsToRender"></tr> <ng-container *matRowDef="let row; columns: columnsToRender"> <tr mat-row></tr> </ng-container> </table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class TableWithNgContainerRow { dataSource: FakeDataSource | null = new FakeDataSource(); columnsToRender = ['column_a']; } @Component({ template: ` <mat-table [dataSource]="dataSource"> <ng-container matColumnDef="column_a"> <mat-header-cell *matHeaderCellDef> Column A</mat-header-cell> <mat-cell *matCellDef="let row"> {{row.a}}</mat-cell> <mat-footer-cell *matFooterCellDef> Footer A</mat-footer-cell> </ng-container> <ng-container matColumnDef="column_b"> <mat-header-cell *matHeaderCellDef> Column B</mat-header-cell> <mat-cell *matCellDef="let row"> {{row.b}}</mat-cell> <mat-footer-cell *matFooterCellDef> Footer B</mat-footer-cell> </ng-container> <ng-container matColumnDef="column_c"> <mat-header-cell *matHeaderCellDef> Column C</mat-header-cell> <mat-cell *matCellDef="let row"> {{row.c}}</mat-cell> <mat-footer-cell *matFooterCellDef> Footer C</mat-footer-cell> </ng-container> <ng-container matColumnDef="special_column"> <mat-cell *matCellDef="let row"> fourth_row </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="columnsToRender"></mat-header-row> <mat-row *matRowDef="let row; columns: columnsToRender"></mat-row> <div *matNoDataRow>No data</div> <mat-footer-row *matFooterRowDef="columnsToRender"></mat-footer-row> </mat-table> `, standalone: true, imports: [MatTableModule, MatPaginatorModule, MatSortModule], }) class MatFlexTableApp { dataSource: FakeDataSource | null = new FakeDataSource(); columnsToRender = ['column_a', 'column_b', 'column_c']; @ViewChild(MatTable) table: MatTable<TestData>; } function getElements(element: Element, query: string): Element[] { return [].slice.call(element.querySelectorAll(query)); } function getHeaderRows(tableElement: Element): Element[] { return [].slice.call(tableElement.querySelectorAll('.mat-mdc-header-row'))!; } function getFooterRows(tableElement: Element): Element[] { return [].slice.call(tableElement.querySelectorAll('.mat-mdc-footer-row'))!; }
116846
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {MatCommonModule} from '@angular/material/core'; import {MatRecycleRows, MatTable} from './table'; import {CdkTableModule} from '@angular/cdk/table'; import { MatCell, MatCellDef, MatColumnDef, MatFooterCell, MatFooterCellDef, MatHeaderCell, MatHeaderCellDef, } from './cell'; import { MatFooterRow, MatFooterRowDef, MatHeaderRow, MatHeaderRowDef, MatRow, MatRowDef, MatNoDataRow, } from './row'; import {MatTextColumn} from './text-column'; const EXPORTED_DECLARATIONS = [ // Table MatTable, MatRecycleRows, // Template defs MatHeaderCellDef, MatHeaderRowDef, MatColumnDef, MatCellDef, MatRowDef, MatFooterCellDef, MatFooterRowDef, // Cell directives MatHeaderCell, MatCell, MatFooterCell, // Row directives MatHeaderRow, MatRow, MatFooterRow, MatNoDataRow, MatTextColumn, ]; @NgModule({ imports: [MatCommonModule, CdkTableModule, ...EXPORTED_DECLARATIONS], exports: [MatCommonModule, EXPORTED_DECLARATIONS], }) export class MatTableModule {}
116851
### Features The `MatTable` is focused on a single responsibility: efficiently render rows of data in a performant and accessible way. You'll notice that the table itself doesn't come out of the box with a lot of features, but expects that the table will be included in a composition of components that fills out its features. For example, you can add sorting and pagination to the table by using MatSort and MatPaginator and mutating the data provided to the table according to their outputs. To simplify the use case of having a table that can sort, paginate, and filter an array of data, the Angular Material library comes with a `MatTableDataSource` that has already implemented the logic of determining what rows should be rendered according to the current table state. To add these feature to the table, check out their respective sections below. #### Pagination To paginate the table's data, add a `<mat-paginator>` after the table. If you are using the `MatTableDataSource` for your table's data source, simply provide the `MatPaginator` to your data source. It will automatically listen for page changes made by the user and send the right paged data to the table. Otherwise if you are implementing the logic to paginate your data, you will want to listen to the paginator's `(page)` output and pass the right slice of data to your table. For more information on using and configuring the `<mat-paginator>`, check out the [mat-paginator docs](https://material.angular.io/components/paginator/overview). The `MatPaginator` is one provided solution to paginating your table's data, but it is not the only option. In fact, the table can work with any custom pagination UI or strategy since the `MatTable` and its interface is not tied to any one specific implementation. <!-- example(table-pagination) --> #### Sorting To add sorting behavior to the table, add the `matSort` directive to the table and add `mat-sort-header` to each column header cell that should trigger sorting. Note that you have to import `MatSortModule` in order to initialize the `matSort` directive (see [API docs](https://material.angular.io/components/sort/api)). ```html <!-- Name Column --> <ng-container matColumnDef="position"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th> <td mat-cell *matCellDef="let element"> {{element.position}} </td> </ng-container> ``` If you are using the `MatTableDataSource` for your table's data source, provide the `MatSort` directive to the data source and it will automatically listen for sorting changes and change the order of data rendered by the table. By default, the `MatTableDataSource` sorts with the assumption that the sorted column's name matches the data property name that the column displays. For example, the following column definition is named `position`, which matches the name of the property displayed in the row cell. Note that if the data properties do not match the column names, or if a more complex data property accessor is required, then a custom `sortingDataAccessor` function can be set to override the default data accessor on the `MatTableDataSource`. When updating the data soure asynchronously avoid doing so by recreating the entire `MatTableDataSource` as this could break sorting. Rather update it through the `MatTableDataSource.data` property. If you are not using the `MatTableDataSource`, but instead implementing custom logic to sort your data, listen to the sort's `(matSortChange)` event and re-order your data according to the sort state. If you are providing a data array directly to the table, don't forget to call `renderRows()` on the table, since it will not automatically check the array for changes. <!-- example(table-sorting) --> For more information on using and configuring the sorting behavior, check out the [matSort docs](https://material.angular.io/components/sort/overview). The `MatSort` is one provided solution to sorting your table's data, but it is not the only option. In fact, the table can work with any custom sorting UI or strategy since the `MatTable` and its interface is not tied to any one specific implementation. #### Filtering Angular Material does not provide a specific component to be used for filtering the `MatTable` since there is no single common approach to adding a filter UI to table data. A general strategy is to add an input where users can type in a filter string and listen to this input to change what data is offered from the data source to the table. If you are using the `MatTableDataSource`, simply provide the filter string to the `MatTableDataSource`. The data source will reduce each row data to a serialized form and will filter out the row if it does not contain the filter string. By default, the row data reducing function will concatenate all the object values and convert them to lowercase. For example, the data object `{id: 123, name: 'Mr. Smith', favoriteColor: 'blue'}` will be reduced to `123mr. smithblue`. If your filter string was `blue` then it would be considered a match because it is contained in the reduced string, and the row would be displayed in the table. To override the default filtering behavior, a custom `filterPredicate` function can be set which takes a data object and filter string and returns true if the data object is considered a match. If you want to show a message when not data matches the filter, you can use the `*matNoDataRow` directive. <!--- example(table-filtering) --> #### Selection Right now there is no formal support for adding a selection UI to the table, but Angular Material does offer the right components and pieces to set this up. The following steps are one solution but it is not the only way to incorporate row selection in your table. ##### 1. Add a selection model Get started by setting up a `SelectionModel` from `@angular/cdk/collections` that will maintain the selection state. ```js const initialSelection = []; const allowMultiSelect = true; this.selection = new SelectionModel<MyDataType>(allowMultiSelect, initialSelection); ``` ##### 2. Define a selection column Add a column definition for displaying the row checkboxes, including a main toggle checkbox for the header. The column name should be added to the list of displayed columns provided to the header and data row. ```html <ng-container matColumnDef="select"> <th mat-header-cell *matHeaderCellDef> <mat-checkbox (change)="$event ? toggleAllRows() : null" [checked]="selection.hasValue() && isAllSelected()" [indeterminate]="selection.hasValue() && !isAllSelected()"> </mat-checkbox> </th> <td mat-cell *matCellDef="let row"> <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(row) : null" [checked]="selection.isSelected(row)"> </mat-checkbox> </td> </ng-container> ``` ##### 3. Add event handling logic Implement the behavior in your component's logic to handle the header's main toggle and checking if all rows are selected. ```js /** Whether the number of selected elements matches the total number of rows. */ isAllSelected() { const numSelected = this.selection.selected.length; const numRows = this.dataSource.data.length; return numSelected == numRows; } /** Selects all rows if they are not all selected; otherwise clear selection. */ toggleAllRows() { this.isAllSelected() ? this.selection.clear() : this.dataSource.data.forEach(row => this.selection.select(row)); } ``` ##### 4. Include overflow styling Finally, adjust the styling for the select column so that its overflow is not hidden. This allows the ripple effect to extend beyond the cell. ```css .mat-column-select { overflow: initial; } ``` <!--- example(table-selection) --> #### Footer row A footer row can be added to the table by adding a footer row definition to the table and adding footer cell templates to column definitions. The footer row will be rendered after the rendered data rows. ```html <ng-container matColumnDef="cost"> <th mat-header-cell *matHeaderCellDef> Cost </th> <td mat-cell *matCellDef="let data"> {{data.cost}} </td> <td mat-footer-cell *matFooterCellDef> {{totalCost}} </td> </ng-container> ... <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr> <tr mat-row *matRowDef="let myRowData; columns: columnsToDisplay"></tr> <tr mat-footer-row *matFooterRowDef="columnsToDisplay"></tr> ``` <!--- example(table-footer-row) -->
116855
export class MatTableDataSource<T, P extends MatPaginator = MatPaginator> extends DataSource<T> { /** Stream that emits when a new data array is set on the data source. */ private readonly _data: BehaviorSubject<T[]>; /** Stream emitting render data to the table (depends on ordered data changes). */ private readonly _renderData = new BehaviorSubject<T[]>([]); /** Stream that emits when a new filter string is set on the data source. */ private readonly _filter = new BehaviorSubject<string>(''); /** Used to react to internal changes of the paginator that are made by the data source itself. */ private readonly _internalPageChanges = new Subject<void>(); /** * Subscription to the changes that should trigger an update to the table's rendered rows, such * as filtering, sorting, pagination, or base data changes. */ _renderChangesSubscription: Subscription | null = null; /** * The filtered set of data that has been matched by the filter string, or all the data if there * is no filter. Useful for knowing the set of data the table represents. * For example, a 'selectAll()' function would likely want to select the set of filtered data * shown to the user rather than all the data. */ filteredData: T[]; /** Array of data that should be rendered by the table, where each object represents one row. */ get data() { return this._data.value; } set data(data: T[]) { data = Array.isArray(data) ? data : []; this._data.next(data); // Normally the `filteredData` is updated by the re-render // subscription, but that won't happen if it's inactive. if (!this._renderChangesSubscription) { this._filterData(data); } } /** * Filter term that should be used to filter out objects from the data array. To override how * data objects match to this filter string, provide a custom function for filterPredicate. */ get filter(): string { return this._filter.value; } set filter(filter: string) { this._filter.next(filter); // Normally the `filteredData` is updated by the re-render // subscription, but that won't happen if it's inactive. if (!this._renderChangesSubscription) { this._filterData(this.data); } } /** * Instance of the MatSort directive used by the table to control its sorting. Sort changes * emitted by the MatSort will trigger an update to the table's rendered data. */ get sort(): MatSort | null { return this._sort; } set sort(sort: MatSort | null) { this._sort = sort; this._updateChangeSubscription(); } private _sort: MatSort | null; /** * Instance of the paginator component used by the table to control what page of the data is * displayed. Page changes emitted by the paginator will trigger an update to the * table's rendered data. * * Note that the data source uses the paginator's properties to calculate which page of data * should be displayed. If the paginator receives its properties as template inputs, * e.g. `[pageLength]=100` or `[pageIndex]=1`, then be sure that the paginator's view has been * initialized before assigning it to this data source. */ get paginator(): P | null { return this._paginator; } set paginator(paginator: P | null) { this._paginator = paginator; this._updateChangeSubscription(); } private _paginator: P | null; /** * Data accessor function that is used for accessing data properties for sorting through * the default sortData function. * This default function assumes that the sort header IDs (which defaults to the column name) * matches the data's properties (e.g. column Xyz represents data['Xyz']). * May be set to a custom function for different behavior. * @param data Data object that is being accessed. * @param sortHeaderId The name of the column that represents the data. */ sortingDataAccessor: (data: T, sortHeaderId: string) => string | number = ( data: T, sortHeaderId: string, ): string | number => { const value = (data as unknown as Record<string, any>)[sortHeaderId]; if (_isNumberValue(value)) { const numberValue = Number(value); // Numbers beyond `MAX_SAFE_INTEGER` can't be compared reliably so we leave them as strings. // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER return numberValue < MAX_SAFE_INTEGER ? numberValue : value; } return value; }; /** * Gets a sorted copy of the data array based on the state of the MatSort. Called * after changes are made to the filtered data or when sort changes are emitted from MatSort. * By default, the function retrieves the active sort and its direction and compares data * by retrieving data using the sortingDataAccessor. May be overridden for a custom implementation * of data ordering. * @param data The array of data that should be sorted. * @param sort The connected MatSort that holds the current sort state. */ sortData: (data: T[], sort: MatSort) => T[] = (data: T[], sort: MatSort): T[] => { const active = sort.active; const direction = sort.direction; if (!active || direction == '') { return data; } return data.sort((a, b) => { let valueA = this.sortingDataAccessor(a, active); let valueB = this.sortingDataAccessor(b, active); // If there are data in the column that can be converted to a number, // it must be ensured that the rest of the data // is of the same type so as not to order incorrectly. const valueAType = typeof valueA; const valueBType = typeof valueB; if (valueAType !== valueBType) { if (valueAType === 'number') { valueA += ''; } if (valueBType === 'number') { valueB += ''; } } // If both valueA and valueB exist (truthy), then compare the two. Otherwise, check if // one value exists while the other doesn't. In this case, existing value should come last. // This avoids inconsistent results when comparing values to undefined/null. // If neither value exists, return 0 (equal). let comparatorResult = 0; if (valueA != null && valueB != null) { // Check if one value is greater than the other; if equal, comparatorResult should remain 0. if (valueA > valueB) { comparatorResult = 1; } else if (valueA < valueB) { comparatorResult = -1; } } else if (valueA != null) { comparatorResult = 1; } else if (valueB != null) { comparatorResult = -1; } return comparatorResult * (direction == 'asc' ? 1 : -1); }); }; /** * Checks if a data object matches the data source's filter string. By default, each data object * is converted to a string of its properties and returns true if the filter has * at least one occurrence in that string. By default, the filter string has its whitespace * trimmed and the match is case-insensitive. May be overridden for a custom implementation of * filter matching. * @param data Data object used to check against the filter. * @param filter Filter string that has been set on the data source. * @returns Whether the filter matches against the data */ filterPredicate: (data: T, filter: string) => boolean = (data: T, filter: string): boolean => { // Transform the data into a lowercase string of all property values. const dataStr = Object.keys(data as unknown as Record<string, any>) .reduce((currentTerm: string, key: string) => { // Use an obscure Unicode character to delimit the words in the concatenated string. // This avoids matches where the values of two columns combined will match the user's query // (e.g. `Flute` and `Stop` will match `Test`). The character is intended to be something // that has a very low chance of being typed in by somebody in a text field. This one in // particular is "White up-pointing triangle with dot" from // https://en.wikipedia.org/wiki/List_of_Unicode_characters return currentTerm + (data as unknown as Record<string, any>)[key] + '◬'; }, '') .toLowerCase(); // Transform the filter by converting it to lowercase and removing whitespace. const transformedFilter = filter.trim().toLowerCase(); return dataStr.indexOf(transformedFilter) != -1; };
116872
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {SelectionModel} from '@angular/cdk/collections'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, InjectionToken, Input, OnDestroy, OnInit, Output, QueryList, ViewChild, ViewEncapsulation, inject, } from '@angular/core'; import {ThemePalette} from '@angular/material/core'; import {MatListBase, MatListItemBase} from './list-base'; import {LIST_OPTION, ListOption, MatListOptionTogglePosition} from './list-option-types'; import {MatListItemLine, MatListItemTitle} from './list-item-sections'; import {NgTemplateOutlet} from '@angular/common'; import {CdkObserveContent} from '@angular/cdk/observers'; /** * Injection token that can be used to reference instances of an `SelectionList`. It serves * as alternative token to an actual implementation which would result in circular references. * @docs-private */ export const SELECTION_LIST = new InjectionToken<SelectionList>('SelectionList'); /** * Interface describing the containing list of a list option. This is used to avoid * circular dependencies between the list-option and the selection list. * @docs-private */ export interface SelectionList extends MatListBase { multiple: boolean; color: ThemePalette; selectedOptions: SelectionModel<MatListOption>; hideSingleSelectionIndicator: boolean; compareWith: (o1: any, o2: any) => boolean; _value: string[] | null; _reportValueChange(): void; _emitChangeEvent(options: MatListOption[]): void; _onTouched(): void; } @Component({ selector: 'mat-list-option', exportAs: 'matListOption', styleUrl: 'list-option.css', host: { 'class': 'mat-mdc-list-item mat-mdc-list-option mdc-list-item', 'role': 'option', // As per MDC, only list items without checkbox or radio indicator should receive the // `--selected` class. '[class.mdc-list-item--selected]': 'selected && !_selectionList.multiple && _selectionList.hideSingleSelectionIndicator', // Based on the checkbox/radio position and whether there are icons or avatars, we apply MDC's // list-item `--leading` and `--trailing` classes. '[class.mdc-list-item--with-leading-avatar]': '_hasProjected("avatars", "before")', '[class.mdc-list-item--with-leading-icon]': '_hasProjected("icons", "before")', '[class.mdc-list-item--with-trailing-icon]': '_hasProjected("icons", "after")', '[class.mat-mdc-list-option-with-trailing-avatar]': '_hasProjected("avatars", "after")', // Based on the checkbox/radio position, we apply the `--leading` or `--trailing` MDC classes // which ensure that the checkbox/radio is positioned correctly within the list item. '[class.mdc-list-item--with-leading-checkbox]': '_hasCheckboxAt("before")', '[class.mdc-list-item--with-trailing-checkbox]': '_hasCheckboxAt("after")', '[class.mdc-list-item--with-leading-radio]': '_hasRadioAt("before")', '[class.mdc-list-item--with-trailing-radio]': '_hasRadioAt("after")', // Utility class that makes it easier to target the case where there's both a leading // and a trailing icon. Avoids having to write out all the combinations. '[class.mat-mdc-list-item-both-leading-and-trailing]': '_hasBothLeadingAndTrailing()', '[class.mat-accent]': 'color !== "primary" && color !== "warn"', '[class.mat-warn]': 'color === "warn"', '[class._mat-animation-noopable]': '_noopAnimations', '[attr.aria-selected]': 'selected', '(blur)': '_handleBlur()', '(click)': '_toggleOnInteraction()', }, templateUrl: 'list-option.html', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [ {provide: MatListItemBase, useExisting: MatListOption}, {provide: LIST_OPTION, useExisting: MatListOption}, ], imports: [NgTemplateOutlet, CdkObserveContent], }) export
116873
class MatListOption extends MatListItemBase implements ListOption, OnInit, OnDestroy { private _selectionList = inject<SelectionList>(SELECTION_LIST); private _changeDetectorRef = inject(ChangeDetectorRef); @ContentChildren(MatListItemLine, {descendants: true}) _lines: QueryList<MatListItemLine>; @ContentChildren(MatListItemTitle, {descendants: true}) _titles: QueryList<MatListItemTitle>; @ViewChild('unscopedContent') _unscopedContent: ElementRef<HTMLSpanElement>; /** * Emits when the selected state of the option has changed. * Use to facilitate two-data binding to the `selected` property. * @docs-private */ @Output() readonly selectedChange: EventEmitter<boolean> = new EventEmitter<boolean>(); /** Whether the label should appear before or after the checkbox/radio. Defaults to 'after' */ @Input() togglePosition: MatListOptionTogglePosition = 'after'; /** * Whether the label should appear before or after the checkbox/radio. Defaults to 'after' * * @deprecated Use `togglePosition` instead. * @breaking-change 17.0.0 */ @Input() get checkboxPosition(): MatListOptionTogglePosition { return this.togglePosition; } set checkboxPosition(value: MatListOptionTogglePosition) { this.togglePosition = value; } /** * Theme color of the list option. This sets the color of the checkbox/radio. * This API is supported in M2 themes only, it has no effect in M3 themes. * * For information on applying color variants in M3, see * https://material.angular.io/guide/theming#using-component-color-variants. */ @Input() get color(): ThemePalette { return this._color || this._selectionList.color; } set color(newValue: ThemePalette) { this._color = newValue; } private _color: ThemePalette; /** Value of the option */ @Input() get value(): any { return this._value; } set value(newValue: any) { if (this.selected && newValue !== this.value && this._inputsInitialized) { this.selected = false; } this._value = newValue; } private _value: any; /** Whether the option is selected. */ @Input() get selected(): boolean { return this._selectionList.selectedOptions.isSelected(this); } set selected(value: BooleanInput) { const isSelected = coerceBooleanProperty(value); if (isSelected !== this._selected) { this._setSelected(isSelected); if (isSelected || this._selectionList.multiple) { this._selectionList._reportValueChange(); } } } private _selected = false; /** * This is set to true after the first OnChanges cycle so we don't * clear the value of `selected` in the first cycle. */ private _inputsInitialized = false; ngOnInit() { const list = this._selectionList; if (list._value && list._value.some(value => list.compareWith(this._value, value))) { this._setSelected(true); } const wasSelected = this._selected; // List options that are selected at initialization can't be reported properly to the form // control. This is because it takes some time until the selection-list knows about all // available options. Also it can happen that the ControlValueAccessor has an initial value // that should be used instead. Deferring the value change report to the next tick ensures // that the form control value is not being overwritten. Promise.resolve().then(() => { if (this._selected || wasSelected) { this.selected = true; this._changeDetectorRef.markForCheck(); } }); this._inputsInitialized = true; } override ngOnDestroy(): void { super.ngOnDestroy(); if (this.selected) { // We have to delay this until the next tick in order // to avoid changed after checked errors. Promise.resolve().then(() => { this.selected = false; }); } } /** Toggles the selection state of the option. */ toggle(): void { this.selected = !this.selected; } /** Allows for programmatic focusing of the option. */ focus(): void { this._hostElement.focus(); } /** Gets the text label of the list option. Used for the typeahead functionality in the list. */ getLabel() { const titleElement = this._titles?.get(0)?._elementRef.nativeElement; // If there is no explicit title element, the unscoped text content // is treated as the list item title. const labelEl = titleElement || this._unscopedContent?.nativeElement; return labelEl?.textContent || ''; } /** Whether a checkbox is shown at the given position. */ _hasCheckboxAt(position: MatListOptionTogglePosition): boolean { return this._selectionList.multiple && this._getTogglePosition() === position; } /** Where a radio indicator is shown at the given position. */ _hasRadioAt(position: MatListOptionTogglePosition): boolean { return ( !this._selectionList.multiple && this._getTogglePosition() === position && !this._selectionList.hideSingleSelectionIndicator ); } /** Whether icons or avatars are shown at the given position. */ _hasIconsOrAvatarsAt(position: 'before' | 'after'): boolean { return this._hasProjected('icons', position) || this._hasProjected('avatars', position); } /** Gets whether the given type of element is projected at the specified position. */ _hasProjected(type: 'icons' | 'avatars', position: 'before' | 'after'): boolean { // If the checkbox/radio is shown at the specified position, neither icons or // avatars can be shown at the position. return ( this._getTogglePosition() !== position && (type === 'avatars' ? this._avatars.length !== 0 : this._icons.length !== 0) ); } _handleBlur() { this._selectionList._onTouched(); } /** Gets the current position of the checkbox/radio. */ _getTogglePosition() { return this.togglePosition || 'after'; } /** * Sets the selected state of the option. * @returns Whether the value has changed. */ _setSelected(selected: boolean): boolean { if (selected === this._selected) { return false; } this._selected = selected; if (selected) { this._selectionList.selectedOptions.select(this); } else { this._selectionList.selectedOptions.deselect(this); } this.selectedChange.emit(selected); this._changeDetectorRef.markForCheck(); return true; } /** * Notifies Angular that the option needs to be checked in the next change detection run. * Mainly used to trigger an update of the list option if the disabled state of the selection * list changed. */ _markForCheck() { this._changeDetectorRef.markForCheck(); } /** Toggles the option's value based on a user interaction. */ _toggleOnInteraction() { if (!this.disabled) { if (this._selectionList.multiple) { this.selected = !this.selected; this._selectionList._emitChangeEvent([this]); } else if (!this.selected) { this.selected = true; this._selectionList._emitChangeEvent([this]); } } } /** Sets the tabindex of the list option. */ _setTabindex(value: number) { this._hostElement.setAttribute('tabindex', value + ''); } protected _hasBothLeadingAndTrailing(): boolean { const hasLeading = this._hasProjected('avatars', 'before') || this._hasProjected('icons', 'before') || this._hasCheckboxAt('before') || this._hasRadioAt('before'); const hasTrailing = this._hasProjected('icons', 'after') || this._hasProjected('avatars', 'after') || this._hasCheckboxAt('after') || this._hasRadioAt('after'); return hasLeading && hasTrailing; } }
116879
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {FocusKeyManager} from '@angular/cdk/a11y'; import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {SelectionModel} from '@angular/cdk/collections'; import {A, ENTER, SPACE, hasModifierKey} from '@angular/cdk/keycodes'; import {_getFocusedElementPierceShadowDom} from '@angular/cdk/platform'; import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, Input, NgZone, OnChanges, OnDestroy, Output, QueryList, SimpleChanges, ViewEncapsulation, forwardRef, inject, } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {ThemePalette} from '@angular/material/core'; import {Subject} from 'rxjs'; import {takeUntil} from 'rxjs/operators'; import {MatListBase} from './list-base'; import {MatListOption, SELECTION_LIST, SelectionList} from './list-option'; export const MAT_SELECTION_LIST_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MatSelectionList), multi: true, }; /** Change event that is being fired whenever the selected state of an option changes. */ export class MatSelectionListChange { constructor( /** Reference to the selection list that emitted the event. */ public source: MatSelectionList, /** Reference to the options that have been changed. */ public options: MatListOption[], ) {} } @Component({ selector: 'mat-selection-list', exportAs: 'matSelectionList', host: { 'class': 'mat-mdc-selection-list mat-mdc-list-base mdc-list', 'role': 'listbox', '[attr.aria-multiselectable]': 'multiple', '(keydown)': '_handleKeydown($event)', }, template: '<ng-content></ng-content>', styleUrl: 'list.css', encapsulation: ViewEncapsulation.None, providers: [ MAT_SELECTION_LIST_VALUE_ACCESSOR, {provide: MatListBase, useExisting: MatSelectionList}, {provide: SELECTION_LIST, useExisting: MatSelectionList}, ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatSelectionList extends MatListBase implements SelectionList, ControlValueAccessor, AfterViewInit, OnChanges, OnDestroy
116882
`<mat-list>` is a container component that wraps and formats a series of `<mat-list-item>`. As the base list component, it provides Material Design styling, but no behavior of its own. <!-- example(list-overview) --> List items can be constructed in two ways depending the content they need to show: ### Simple lists If a list item needs to show a single line of textual information, the text can be inserted directly into the `<mat-list-item>` element. ```html <mat-list> <mat-list-item>Pepper</mat-list-item> <mat-list-item>Salt</mat-list-item> <mat-list-item>Paprika</mat-list-item> </mat-list> ``` ### Multi-line lists List items that have more than one line of text have to use the `matListItemTitle` directive to indicate their title text for accessibility purposes, in addition to the `matListItemLine` directive for each subsequent line of text. ```html <mat-list> <mat-list-item> <span matListItemTitle>Pepper</span> <span matListItemLine>Produced by a plant</span> </mat-list-item> <mat-list-item> <span matListItemTitle>Salt</span> <span matListItemLine>Extracted from sea water</span> </mat-list-item> <mat-list-item> <span matListItemTitle>Paprika</span> <span matListItemLine>Produced by dried and ground red peppers</span> </mat-list-item> </mat-list> ``` To activate text wrapping, the `lines` input has to be set on the `<mat-list-item>` indicating the number of lines of text. The following directives can be used to style the content of a list item: | Directive | Description | |---------------------|----------------------------------------------------------------------------| | `matListItemTitle` | Indicates the title of the list item. Required for multi-line list items. | | `matListItemLine` | Wraps a line of text within a list item. | | `matListItemIcon` | Icon typically placed at the beginning of a list item. | | `matListItemAvatar` | Image typically placed at the beginning of a list item. | | `matListItemMeta` | Inserts content in the meta section at the end of a list item. | ### Navigation lists Use `mat-nav-list` tags for navigation lists (i.e. lists that have anchor tags). Simple navigation lists can use the `mat-list-item` attribute on anchor tag elements directly: ```html <mat-nav-list> @for (link of list; track link) { <a mat-list-item href="..." [activated]="link.isActive">{{ link }}</a> } </mat-nav-list> ``` For more complex navigation lists (e.g. with more than one target per item), wrap the anchor element in an `<mat-list-item>`. ```html <mat-nav-list> @for (link of links; track link) { <mat-list-item [activated]="link.isActive"> <a matListItemTitle href="...">{{ link }}</a> <button mat-icon-button (click)="showInfo(link)" matListItemMeta> <mat-icon>info</mat-icon> </button> </mat-list-item> } </mat-nav-list> ``` ### Action lists Use the `<mat-action-list>` element when each item in the list performs some _action_. Each item in an action list is a `<button>` element. Simple action lists can use the `mat-list-item` attribute on button tag elements directly: ```html <mat-action-list> <button mat-list-item (click)="save()">Save</button> <button mat-list-item (click)="undo()">Undo</button> </mat-action-list> ``` ### Selection lists A selection list provides an interface for selecting values, where each list item is an option. <!-- example(list-selection) --> The options within a selection-list should not contain further interactive controls, such as buttons and anchors. ### Multi-line lists For lists that require multiple lines per item, annotate each line with an `matListItemLine` attribute. Whichever heading tag is appropriate for your DOM hierarchy should be used (not necessarily `<h3>` as shown in the example). ```html <!-- two line list --> <mat-list> @for (message of messages; track message) { <mat-list-item> <h3 matListItemTitle>{{message.from}}</h3> <p matListItemLine> <span>{{message.subject}}</span> <span class="demo-2"> -- {{message.content}}</span> </p> </mat-list-item> } </mat-list> <!-- three line list --> <mat-list> @for (message of messages; track message) { <mat-list-item> <h3 matListItemTitle>{{message.from}}</h3> <p matListItemLine>{{message.subject}}</p> <p matListItemLine class="demo-2">{{message.content}}</p> </mat-list-item> } </mat-list> ``` ### Lists with icons To add an icon to your list item, use the `matListItemIcon` attribute. ```html <mat-list> @for (message of messages; track message) { <mat-list-item> <mat-icon matListItemIcon>folder</mat-icon> <h3 matListItemTitle>{{message.from}}</h3> <p matListItemLine> <span>{{message.subject}}</span> <span class="demo-2"> -- {{message.content}}</span> </p> </mat-list-item> } </mat-list> ``` ### Lists with avatars To include an avatar image, add an image tag with an `matListItemAvatar` attribute. ```html <mat-list> @for (message of messages; track message) { <mat-list-item> <img matListItemAvatar src="..." alt="..."> <h3 matListItemTitle>{{message.from}}</h3> <p matListItemLine> <span>{{message.subject}}</span> <span class="demo-2"> -- {{message.content}}</span> </p> </mat-list-item> } </mat-list> ``` ### Lists with multiple sections Subheaders can be added to a list by annotating a heading tag with an `matSubheader` attribute. To add a divider, use `<mat-divider>`. ```html <mat-list> <h3 matSubheader>Folders</h3> @for (folder of folders; track folder) { <mat-list-item> <mat-icon matListIcon>folder</mat-icon> <h4 matListItemTitle>{{folder.name}}</h4> <p matListItemLine class="demo-2"> {{folder.updated}} </p> </mat-list-item> } <mat-divider></mat-divider> <h3 matSubheader>Notes</h3> @for (note of notes; track note) { <mat-list-item> <mat-icon matListIcon>note</mat-icon> <h4 matListItemTitle>{{note.name}}</h4> <p matListItemLine class="demo-2"> {{note.updated}} </p> </mat-list-item> } </mat-list> ``` ### Accessibility Angular Material offers multiple varieties of list so that you can choose the type that best applies to your use-case. #### Navigation You should use `MatNavList` when every item in the list is an anchor that navigate to another URL. The root `<mat-nav-list>` element sets `role="navigation"` and should contain only anchor elements with the `mat-list-item` attribute. You should not nest any interactive elements inside these anchors, including buttons and checkboxes. Always provide an accessible label for the `<mat-nav-list>` element via `aria-label` or `aria-labelledby`. #### Selection You should use `MatSelectionList` and `MatListOption` for lists that allow the user to select one or more values. This list variant uses the `role="listbox"` interaction pattern, handling all associated keyboard input and focus management. You should not nest any interactive elements inside these options, including buttons and anchors. Always provide an accessible label for the `<mat-selection-list>` element via `aria-label` or `aria-labelledby` that describes the selection being made. By default, `MatSelectionList` displays radio or checkmark indicators to identify selected items. While you can hide the radio indicator for single-selection via `hideSingleSelectionIndicator`, this makes the component less accessible by making it harder or impossible for users to visually identify selected items. #### Custom scenarios By default, the list assumes that it will be used in a purely decorative fashion and thus it sets no roles, ARIA attributes, or keyboard shortcuts. This is equivalent to having a sequence of `<div>` elements on the page. Any interactive content within the list should be given an appropriate accessibility treatment based on the specific workflow of your application. If the list is used to present a list of non-interactive content items, then the list element should be given `role="list"` and each list item should be given `role="listitem"`.
116890
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import {NgModule} from '@angular/core'; import {MatPseudoCheckboxModule, MatRippleModule, MatCommonModule} from '@angular/material/core'; import {MatDividerModule} from '@angular/material/divider'; import {MatActionList} from './action-list'; import {MatList, MatListItem} from './list'; import {MatListOption} from './list-option'; import {MatListSubheaderCssMatStyler} from './subheader'; import { MatListItemLine, MatListItemTitle, MatListItemMeta, MatListItemAvatar, MatListItemIcon, } from './list-item-sections'; import {MatNavList} from './nav-list'; import {MatSelectionList} from './selection-list'; import {ObserversModule} from '@angular/cdk/observers'; @NgModule({ imports: [ ObserversModule, MatCommonModule, MatRippleModule, MatPseudoCheckboxModule, MatList, MatActionList, MatNavList, MatSelectionList, MatListItem, MatListOption, MatListSubheaderCssMatStyler, MatListItemAvatar, MatListItemIcon, MatListItemLine, MatListItemTitle, MatListItemMeta, ], exports: [ MatList, MatActionList, MatNavList, MatSelectionList, MatListItem, MatListOption, MatListItemAvatar, MatListItemIcon, MatListSubheaderCssMatStyler, MatDividerModule, MatListItemLine, MatListItemTitle, MatListItemMeta, ], }) export class MatListModule {}
116900
it('should be able to deselect all options, even if they are disabled', () => { const list: MatSelectionList = selectionList.componentInstance; list.options.forEach(option => option.toggle()); expect(list.options.toArray().every(option => option.selected)).toBe(true); list.options.forEach(option => (option.disabled = true)); fixture.detectChanges(); list.deselectAll(); fixture.detectChanges(); expect(list.options.toArray().every(option => option.selected)).toBe(false); }); it('should update the list value when an item is selected programmatically', () => { const list: MatSelectionList = selectionList.componentInstance; expect(list.selectedOptions.isEmpty()).toBe(true); listOptions[0].componentInstance.selected = true; listOptions[2].componentInstance.selected = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(list.selectedOptions.isEmpty()).toBe(false); expect(list.selectedOptions.isSelected(listOptions[0].componentInstance)).toBe(true); expect(list.selectedOptions.isSelected(listOptions[2].componentInstance)).toBe(true); }); it('should update the item selected state when it is selected via the model', () => { const list: MatSelectionList = selectionList.componentInstance; const item: MatListOption = listOptions[0].componentInstance; expect(item.selected).toBe(false); list.selectedOptions.select(item); fixture.detectChanges(); expect(item.selected).toBe(true); }); it('should set aria-multiselectable to true on the selection list element', () => { expect(selectionList.nativeElement.getAttribute('aria-multiselectable')).toBe('true'); }); it('should be able to reach list options that are indirect descendants', () => { const descendatsFixture = TestBed.createComponent(SelectionListWithIndirectChildOptions); descendatsFixture.detectChanges(); listOptions = descendatsFixture.debugElement.queryAll(By.directive(MatListOption)); selectionList = descendatsFixture.debugElement.query(By.directive(MatSelectionList))!; const list: MatSelectionList = selectionList.componentInstance; expect(list.options.toArray().every(option => option.selected)).toBe(false); list.selectAll(); descendatsFixture.detectChanges(); expect(list.options.toArray().every(option => option.selected)).toBe(true); }); it('should disable list item ripples when the ripples on the list have been disabled', fakeAsync(() => { const rippleTarget = fixture.nativeElement.querySelector( '.mat-mdc-list-option:not(.mdc-list-item--disabled)', ); dispatchMouseEvent(rippleTarget, 'mousedown'); dispatchMouseEvent(rippleTarget, 'mouseup'); // Flush the ripple enter animation. dispatchFakeEvent(rippleTarget.querySelector('.mat-ripple-element')!, 'transitionend'); expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) .withContext('Expected ripples to be enabled by default.') .toBe(1); // Flush the ripple exit animation. dispatchFakeEvent(rippleTarget.querySelector('.mat-ripple-element')!, 'transitionend'); expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) .withContext('Expected ripples to go away.') .toBe(0); fixture.componentInstance.listRippleDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); dispatchMouseEvent(rippleTarget, 'mousedown'); dispatchMouseEvent(rippleTarget, 'mouseup'); expect(rippleTarget.querySelectorAll('.mat-ripple-element').length) .withContext('Expected no ripples after list ripples are disabled.') .toBe(0); })); it('can bind both selected and value at the same time', () => { const componentFixture = TestBed.createComponent(SelectionListWithSelectedOptionAndValue); componentFixture.detectChanges(); const listItemEl = componentFixture.debugElement.query(By.directive(MatListOption))!; expect(listItemEl.componentInstance.selected).toBe(true); expect(listItemEl.componentInstance.value).toBe(componentFixture.componentInstance.itemValue); }); it('should have a focus indicator', () => { const optionNativeElements = listOptions.map(option => option.nativeElement as HTMLElement); expect( optionNativeElements.every( element => element.querySelector('.mat-focus-indicator') !== null, ), ).toBe(true); }); it('should hide the internal SVG', () => { listOptions.forEach(option => { const svg = option.nativeElement.querySelector('.mdc-checkbox svg'); expect(svg.getAttribute('aria-hidden')).toBe('true'); }); }); }); describe('multiple-selection with list option selected', () => { let fixture: ComponentFixture<SelectionListWithSelectedOption>; let listOptionElements: DebugElement[]; let selectionList: DebugElement; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MatListModule, SelectionListWithSelectedOption], }); })); beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(SelectionListWithSelectedOption); listOptionElements = fixture.debugElement.queryAll(By.directive(MatListOption))!; selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!; fixture.detectChanges(); })); it('should set its initial selected state in the selectedOptions', () => { let options = listOptionElements.map(optionEl => optionEl.injector.get<MatListOption>(MatListOption), ); let selectedOptions = selectionList.componentInstance.selectedOptions; expect(selectedOptions.isSelected(options[0])).toBeFalse(); expect(selectedOptions.isSelected(options[1])).toBeTrue(); expect(selectedOptions.isSelected(options[2])).toBeTrue(); expect(selectedOptions.isSelected(options[3])).toBeFalse(); }); it('should focus the first selected option on first focus if an item is pre-selected', fakeAsync(() => { // MDC manages the focus through setting a `tabindex` on the designated list item. We // assert that the proper tabindex is set on the pre-selected option at index 1, and // ensure that other options are not reachable through tab. expect(listOptionElements.map(el => el.nativeElement.tabIndex)).toEqual([-1, 0, -1, -1]); })); }); describe('single-selection with list option selected', () => { let fixture: ComponentFixture<SingleSelectionListWithSelectedOption>; let listOptionElements: DebugElement[]; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MatListModule, SingleSelectionListWithSelectedOption], }); })); beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(SingleSelectionListWithSelectedOption); listOptionElements = fixture.debugElement.queryAll(By.directive(MatListOption))!; fixture.detectChanges(); })); it('displays radio indicators by default', () => { expect( listOptionElements[0].nativeElement.querySelector('input[type="radio"]'), ).not.toBeNull(); expect( listOptionElements[1].nativeElement.querySelector('input[type="radio"]'), ).not.toBeNull(); expect(listOptionElements[0].nativeElement.classList).not.toContain( 'mdc-list-item--selected', ); expect(listOptionElements[1].nativeElement.classList).not.toContain( 'mdc-list-item--selected', ); }); }); describe('with token to hide radio indicators', () => { let fixture: ComponentFixture<SingleSelectionListWithSelectedOption>; let listOptionElements: DebugElement[]; beforeEach(waitForAsync(() => { const matListConfig: MatListConfig = {hideSingleSelectionIndicator: true}; TestBed.configureTestingModule({ imports: [MatListModule, SingleSelectionListWithSelectedOption], providers: [{provide: MAT_LIST_CONFIG, useValue: matListConfig}], }); })); beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(SingleSelectionListWithSelectedOption); listOptionElements = fixture.debugElement.queryAll(By.directive(MatListOption))!; fixture.detectChanges(); })); it('does not display radio indicators', () => { expect(listOptionElements[0].nativeElement.querySelector('input[type="radio"]')).toBeNull(); expect(listOptionElements[1].nativeElement.querySelector('input[type="radio"]')).toBeNull(); expect(listOptionElements[0].nativeElement.classList).not.toContain( 'mdc-list-item--selected', ); expect(listOptionElements[1].nativeElement.getAttribute('aria-selected')) .withContext('Expected second option to be selected') .toBe('true'); expect(listOptionElements[1].nativeElement.classList).toContain('mdc-list-item--selected'); }); });
116905
describe('and formControl', () => { let fixture: ComponentFixture<SelectionListWithFormControl>; let listOptions: MatListOption[]; let selectionList: MatSelectionList; beforeEach(() => { fixture = TestBed.createComponent(SelectionListWithFormControl); fixture.detectChanges(); selectionList = fixture.debugElement.query(By.directive(MatSelectionList))!.componentInstance; listOptions = fixture.debugElement .queryAll(By.directive(MatListOption)) .map(optionDebugEl => optionDebugEl.componentInstance); }); it('should be able to disable options from the control', () => { selectionList.focus(); expect(selectionList.disabled) .withContext('Expected the selection list to be enabled.') .toBe(false); expect(listOptions.every(option => !option.disabled)) .withContext('Expected every list option to be enabled.') .toBe(true); expect( listOptions.some( option => option._elementRef.nativeElement.getAttribute('tabindex') === '0', ), ) .withContext('Expected one list item to be in the tab order') .toBe(true); fixture.componentInstance.formControl.disable(); fixture.detectChanges(); expect(selectionList.disabled) .withContext('Expected the selection list to be disabled.') .toBe(true); expect(listOptions.every(option => option.disabled)) .withContext('Expected every list option to be disabled.') .toBe(true); expect( listOptions.every( option => option._elementRef.nativeElement.getAttribute('tabindex') === '-1', ), ) .withContext('Expected every list option to be removed from the tab order') .toBe(true); }); it('should be able to update the disabled property after form control disabling', () => { expect(listOptions.every(option => !option.disabled)) .withContext('Expected every list option to be enabled.') .toBe(true); fixture.componentInstance.formControl.disable(); fixture.detectChanges(); expect(listOptions.every(option => option.disabled)) .withContext('Expected every list option to be disabled.') .toBe(true); // Previously the selection list has been disabled through FormControl#disable. Now we // want to verify that we can still change the disabled state through updating the disabled // property. Calling FormControl#disable should not lock the disabled property. // See: https://github.com/angular/material2/issues/12107 selectionList.disabled = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(listOptions.every(option => !option.disabled)) .withContext('Expected every list option to be enabled.') .toBe(true); }); it('should be able to set the value through the form control', () => { expect(listOptions.every(option => !option.selected)) .withContext('Expected every list option to be unselected.') .toBe(true); fixture.componentInstance.formControl.setValue(['opt2', 'opt3']); fixture.detectChanges(); expect(listOptions[1].selected) .withContext('Expected second option to be selected.') .toBe(true); expect(listOptions[2].selected) .withContext('Expected third option to be selected.') .toBe(true); fixture.componentInstance.formControl.setValue(null); fixture.detectChanges(); expect(listOptions.every(option => !option.selected)) .withContext('Expected every list option to be unselected.') .toBe(true); }); it('should deselect option whose value no longer matches', () => { const option = listOptions[1]; fixture.componentInstance.formControl.setValue(['opt2']); fixture.detectChanges(); expect(option.selected).withContext('Expected option to be selected.').toBe(true); option.value = 'something-different'; fixture.detectChanges(); expect(option.selected).withContext('Expected option not to be selected.').toBe(false); expect(fixture.componentInstance.formControl.value).toEqual([]); }); it('should mark options as selected when the value is set before they are initialized', () => { fixture.destroy(); fixture = TestBed.createComponent(SelectionListWithFormControl); fixture.componentInstance.formControl.setValue(['opt2', 'opt3']); fixture.detectChanges(); listOptions = fixture.debugElement .queryAll(By.directive(MatListOption)) .map(optionDebugEl => optionDebugEl.componentInstance); expect(listOptions[1].selected) .withContext('Expected second option to be selected.') .toBe(true); expect(listOptions[2].selected) .withContext('Expected third option to be selected.') .toBe(true); }); it('should not clear the form control when the list is destroyed', fakeAsync(() => { const option = listOptions[1]; option.selected = true; fixture.detectChanges(); expect(fixture.componentInstance.formControl.value).toEqual(['opt2']); fixture.componentInstance.renderList = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(fixture.componentInstance.formControl.value).toEqual(['opt2']); })); it('should mark options added at a later point as selected', () => { fixture.componentInstance.formControl.setValue(['opt4']); fixture.detectChanges(); fixture.componentInstance.renderExtraOption = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); listOptions = fixture.debugElement .queryAll(By.directive(MatListOption)) .map(optionDebugEl => optionDebugEl.componentInstance); expect(listOptions.length).toBe(4); expect(listOptions[3].selected).toBe(true); }); }); describe('preselected values', () => { it('should add preselected options to the model value', fakeAsync(() => { const fixture = TestBed.createComponent(SelectionListWithPreselectedOption); const listOptions = fixture.debugElement .queryAll(By.directive(MatListOption)) .map(optionDebugEl => optionDebugEl.componentInstance); fixture.detectChanges(); tick(); expect(listOptions[1].selected).toBe(true); expect(fixture.componentInstance.selectedOptions).toEqual(['opt2']); })); it('should handle preselected option both through the model and the view', fakeAsync(() => { const fixture = TestBed.createComponent(SelectionListWithPreselectedOptionAndModel); const listOptions = fixture.debugElement .queryAll(By.directive(MatListOption)) .map(optionDebugEl => optionDebugEl.componentInstance); fixture.detectChanges(); tick(); expect(listOptions[0].selected).toBe(true); expect(listOptions[1].selected).toBe(true); expect(fixture.componentInstance.selectedOptions).toEqual(['opt1', 'opt2']); })); it('should show the item as selected when preselected inside OnPush parent', fakeAsync(() => { const fixture = TestBed.createComponent(SelectionListWithPreselectedFormControlOnPush); fixture.detectChanges(); const option = fixture.debugElement.queryAll(By.directive(MatListOption))[1]; const checkbox = option.nativeElement.querySelector( '.mdc-checkbox__native-control', ) as HTMLInputElement; fixture.detectChanges(); flush(); fixture.detectChanges(); expect(option.componentInstance.selected).toBe(true); expect(checkbox.checked).toBe(true); })); }); describe('with custom compare function', () => { it('should use a custom comparator to determine which options are selected', fakeAsync(() => { const fixture = TestBed.createComponent(SelectionListWithCustomComparator); const testComponent = fixture.componentInstance; testComponent.compareWith = jasmine .createSpy('comparator', (o1: any, o2: any) => { return o1 && o2 && o1.id === o2.id; }) .and.callThrough(); testComponent.selectedOptions = [{id: 2, label: 'Two'}]; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); expect(testComponent.compareWith).toHaveBeenCalled(); expect(testComponent.optionInstances.toArray()[1].selected).toBe(true); })); }); }); @Component({ template: ` <mat-selection-list id="selection-list-1" (selectionChange)="onSelectionChange($event)" [disableRipple]="listRippleDisabled" [color]="selectionListColor" [multiple]="multiple"> <mat-list-option togglePosition="before" disabled="true" value="inbox" [color]="firstOptionColor"> Inbox (disabled selection-option) </mat-list-option> <mat-list-option id="testSelect" togglePosition="before" class="test-native-focus" value="starred"> Starred </mat-list-option> <mat-list-option togglePosition="before" value="sent-mail"> Sent Mail </mat-list-option> <mat-list-option togglePosition="before" value="archive"> Archive </mat-list-option> @if (showLastOption) { <mat-list-option togglePosition="before" value="drafts"> Drafts </mat-list-option> } </mat-selection-list>`, standalone: true, imports: [MatListModule], }) class SelectionListWithListOptions { showLastOption = true; listRippleDisabled = false; multiple = true; selectionListColor: ThemePalette; firstOptionColor: ThemePalette; onSelectionChange(_change: MatSelectionListChange) {} }
116906
@Component({ template: ` <mat-selection-list id="selection-list-2"> <mat-list-option togglePosition="after"> Inbox (disabled selection-option) </mat-list-option> <mat-list-option id="testSelect" togglePosition="after"> Starred </mat-list-option> <mat-list-option togglePosition="after"> Sent Mail </mat-list-option> <mat-list-option togglePosition="after"> Drafts </mat-list-option> </mat-selection-list>`, standalone: true, imports: [MatListModule], }) class SelectionListWithCheckboxPositionAfter {} @Component({ template: ` <mat-selection-list id="selection-list-3" [disabled]="disabled"> <mat-list-option togglePosition="after"> Inbox (disabled selection-option) </mat-list-option> <mat-list-option id="testSelect" togglePosition="after"> Starred </mat-list-option> <mat-list-option togglePosition="after"> Sent Mail </mat-list-option> <mat-list-option togglePosition="after"> Drafts </mat-list-option> </mat-selection-list>`, standalone: true, imports: [MatListModule], }) class SelectionListWithListDisabled { disabled: boolean = true; } @Component({ template: ` <mat-selection-list> <mat-list-option [disabled]="disableItem">Item</mat-list-option> </mat-selection-list> `, standalone: true, imports: [MatListModule], }) class SelectionListWithDisabledOption { disableItem: boolean = false; } @Component({ template: ` <mat-selection-list> <mat-list-option>Not selected - Item #1</mat-list-option> <mat-list-option [selected]="true">Pre-selected - Item #2</mat-list-option> <mat-list-option [selected]="true">Pre-selected - Item #3</mat-list-option> <mat-list-option>Not selected - Item #4</mat-list-option> </mat-selection-list>`, standalone: true, imports: [MatListModule], }) class SelectionListWithSelectedOption {} @Component({ template: ` <mat-selection-list [multiple]="false"> <mat-list-option>Not selected - Item #1</mat-list-option> <mat-list-option [selected]="true">Pre-selected - Item #2</mat-list-option> </mat-selection-list>`, standalone: true, imports: [MatListModule], }) class SingleSelectionListWithSelectedOption {} @Component({ template: ` <mat-selection-list> <mat-list-option [selected]="true" [value]="itemValue">Item</mat-list-option> </mat-selection-list>`, standalone: true, imports: [MatListModule], }) class SelectionListWithSelectedOptionAndValue { itemValue = 'item1'; } @Component({ template: ` <mat-selection-list id="selection-list-4"> <mat-list-option togglePosition="after" class="test-focus" id="123"> Inbox </mat-list-option> </mat-selection-list>`, standalone: true, imports: [MatListModule], }) class SelectionListWithOnlyOneOption {} @Component({ template: ` <mat-selection-list [(ngModel)]="selectedOptions" (ngModelChange)="modelChangeSpy()" [multiple]="multiple"> @for (option of options; track option) { <mat-list-option [value]="option">{{option}}</mat-list-option> } </mat-selection-list>`, standalone: true, imports: [MatListModule, FormsModule, ReactiveFormsModule], }) class SelectionListWithModel { modelChangeSpy = jasmine.createSpy('model change spy'); selectedOptions: string[] = []; multiple = true; options = ['opt1', 'opt2', 'opt3']; } @Component({ template: ` @if (renderList) { <mat-selection-list [formControl]="formControl"> <mat-list-option value="opt1">Option 1</mat-list-option> <mat-list-option value="opt2">Option 2</mat-list-option> <mat-list-option value="opt3">Option 3</mat-list-option> @if (renderExtraOption) { <mat-list-option value="opt4">Option 4</mat-list-option> } </mat-selection-list> } `, standalone: true, imports: [MatListModule, FormsModule, ReactiveFormsModule], }) class SelectionListWithFormControl { formControl = new FormControl([] as string[]); renderList = true; renderExtraOption = false; } @Component({ template: ` <mat-selection-list [(ngModel)]="selectedOptions"> <mat-list-option value="opt1">Option 1</mat-list-option> <mat-list-option value="opt2" selected>Option 2</mat-list-option> </mat-selection-list>`, standalone: true, imports: [MatListModule, FormsModule, ReactiveFormsModule], }) class SelectionListWithPreselectedOption { selectedOptions: string[]; } @Component({ template: ` <mat-selection-list [(ngModel)]="selectedOptions"> <mat-list-option value="opt1">Option 1</mat-list-option> <mat-list-option value="opt2" selected>Option 2</mat-list-option> </mat-selection-list>`, standalone: true, imports: [MatListModule, FormsModule, ReactiveFormsModule], }) class SelectionListWithPreselectedOptionAndModel { selectedOptions = ['opt1']; } @Component({ changeDetection: ChangeDetectionStrategy.OnPush, template: ` <mat-selection-list [formControl]="formControl"> @for (opt of opts; track opt) { <mat-list-option [value]="opt">{{opt}}</mat-list-option> } </mat-selection-list> `, standalone: true, imports: [MatListModule, FormsModule, ReactiveFormsModule], }) class SelectionListWithPreselectedFormControlOnPush { opts = ['opt1', 'opt2', 'opt3']; formControl = new FormControl(['opt2']); } @Component({ template: ` <mat-selection-list [(ngModel)]="selectedOptions" [compareWith]="compareWith"> @for (option of options; track option) { <mat-list-option [value]="option">{{option.label}}</mat-list-option> } </mat-selection-list>`, standalone: true, imports: [MatListModule, FormsModule, ReactiveFormsModule], }) class SelectionListWithCustomComparator { @ViewChildren(MatListOption) optionInstances: QueryList<MatListOption>; selectedOptions: {id: number; label: string}[] = []; compareWith?: (o1: any, o2: any) => boolean; options = [ {id: 1, label: 'One'}, {id: 2, label: 'Two'}, {id: 3, label: 'Three'}, ]; } @Component({ template: ` <mat-selection-list> <mat-list-option [togglePosition]="togglePosition"> <div matListItemAvatar>I</div> Inbox </mat-list-option> </mat-selection-list> `, standalone: true, imports: [MatListModule], }) class SelectionListWithAvatar { togglePosition: MatListOptionTogglePosition | undefined; } @Component({ template: ` <mat-selection-list> <mat-list-option [togglePosition]="togglePosition"> <div matListItemIcon>I</div> Inbox </mat-list-option> </mat-selection-list> `, standalone: true, imports: [MatListModule], }) class SelectionListWithIcon { togglePosition: MatListOptionTogglePosition | undefined; } @Component({ // Note the blank `@if` which we need in order to hit the bug that we're testing. template: ` <mat-selection-list> @if (true) { <mat-list-option [value]="1">One</mat-list-option> <mat-list-option [value]="2">Two</mat-list-option> } </mat-selection-list>`, standalone: true, imports: [MatListModule], }) class SelectionListWithIndirectChildOptions { @ViewChildren(MatListOption) optionInstances: QueryList<MatListOption>; } @Component({ template: ` <mat-selection-list> <mat-list-option [(selected)]="selected">Item</mat-list-option> </mat-selection-list> `, standalone: true, imports: [MatListModule], }) class ListOptionWithTwoWayBinding { selected = false; }
116946
`<mat-menu>` is a floating panel containing list of options. <!-- example(menu-overview) --> By itself, the `<mat-menu>` element does not render anything. The menu is attached to and opened via application of the `matMenuTriggerFor` directive: <!-- example({"example": "menu-overview", "file": "menu-overview-example.html", "region": "mat-menu-trigger-for"}) --> ### Toggling the menu programmatically The menu exposes an API to open/close programmatically. Please note that in this case, an `matMenuTriggerFor` directive is still necessary to attach the menu to a trigger element in the DOM. ```ts class MyComponent { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; someMethod() { this.trigger.openMenu(); } } ``` ### Icons Menus support displaying `mat-icon` elements before the menu item text. <!-- example({"example": "menu-icons", "file": "menu-icons-example.html"}) --> ### Customizing menu position By default, the menu will display below (y-axis), after (x-axis), without overlapping its trigger. The position can be changed using the `xPosition` (`before | after`) and `yPosition` (`above | below`) attributes. The menu can be forced to overlap the trigger using the `overlapTrigger` attribute. <!-- example({"example": "menu-position", "file": "menu-position-example.html", "region": "menu-position"}) --> ### Nested menu Material supports the ability for an `mat-menu-item` to open a sub-menu. To do so, you have to define your root menu and sub-menus, in addition to setting the `[matMenuTriggerFor]` on the `mat-menu-item` that should trigger the sub-menu: <!-- example({"example": "menu-nested", "file": "menu-nested-example.html", "region": "sub-menu"}) --> ### Lazy rendering By default, the menu content will be initialized even when the panel is closed. To defer initialization until the menu is open, the content can be provided as an `ng-template` with the `matMenuContent` attribute: ```html <mat-menu #appMenu="matMenu"> <ng-template matMenuContent> <button mat-menu-item>Settings</button> <button mat-menu-item>Help</button> </ng-template> </mat-menu> <button mat-icon-button [matMenuTriggerFor]="appMenu"> <mat-icon>more_vert</mat-icon> </button> ``` ### Passing in data to a menu When using lazy rendering, additional context data can be passed to the menu panel via the `matMenuTriggerData` input. This allows for a single menu instance to be rendered with a different set of data, depending on the trigger that opened it: ```html <mat-menu #appMenu="matMenu"> <ng-template matMenuContent let-name="name"> <button mat-menu-item>Settings</button> <button mat-menu-item>Log off {{name}}</button> </ng-template> </mat-menu> <button mat-icon-button [matMenuTriggerFor]="appMenu" [matMenuTriggerData]="{name: 'Sally'}"> <mat-icon>more_vert</mat-icon> </button> <button mat-icon-button [matMenuTriggerFor]="appMenu" [matMenuTriggerData]="{name: 'Bob'}"> <mat-icon>more_vert</mat-icon> </button> ``` ### Keyboard interaction | Keyboard shortcut | Action | |------------------------|---------------------------------------------| | <kbd>Down Arrow</kbd> | Focus the next menu item. | | <kbd>Up Arrow</kbd> | Focus the previous menu item. | | <kbd>Left Arrow</kbd> | Close the current menu if it is a sub-menu. | | <kbd>Right Arrow</kbd> | Opens the current menu item's sub-menu. | | <kbd>Enter</kbd> | Activate the focused menu item. | | <kbd>Escape</kbd> | Close all open menus. | ### Accessibility Angular Material's menu component consists of two connected parts: the trigger and the pop-up menu. The menu trigger is a standard button element augmented with `aria-haspopup`, `aria-expanded`, and `aria-controls` to create the relationship to the pop-up panel. The pop-up menu implements the `role="menu"` pattern, handling keyboard interaction and focus management. Upon opening, the trigger will focus the first focusable menu item. Upon close, the menu will return focus to its trigger. Avoid creating a menu in which all items are disabled, instead hiding or disabling the menu trigger. Angular Material does not support the `menuitemcheckbox` or `menuitemradio` roles. Always provide an accessible label via `aria-label` or `aria-labelledby` for any menu triggers or menu items without descriptive text content. MatMenu should not contain any interactive controls aside from MatMenuItem.
116972
@Component({ selector: 'custom-menu', template: ` <ng-template> Custom Menu header <ng-content></ng-content> </ng-template> `, exportAs: 'matCustomMenu', standalone: false, }) class CustomMenuPanel implements MatMenuPanel { direction: Direction; xPosition: MenuPositionX = 'after'; yPosition: MenuPositionY = 'below'; overlapTrigger = true; parentMenu: MatMenuPanel; @ViewChild(TemplateRef) templateRef: TemplateRef<any>; @Output() readonly close = new EventEmitter<void | 'click' | 'keydown' | 'tab'>(); focusFirstItem = () => {}; resetActiveItem = () => {}; setPositionClasses = () => {}; } @Component({ template: ` <button [matMenuTriggerFor]="menu">Toggle menu</button> <custom-menu #menu="matCustomMenu"> <button mat-menu-item> Custom Content </button> </custom-menu> `, standalone: false, }) class CustomMenu { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; } @Component({ template: ` <button [matMenuTriggerFor]="root" #rootTrigger="matMenuTrigger" #rootTriggerEl>Toggle menu</button> <button [matMenuTriggerFor]="levelTwo" #alternateTrigger="matMenuTrigger">Toggle alternate menu</button> <mat-menu #root="matMenu" (closed)="rootCloseCallback($event)"> <button mat-menu-item id="level-one-trigger" [matMenuTriggerFor]="levelOne" #levelOneTrigger="matMenuTrigger">One</button> <button mat-menu-item>Two</button> @if (showLazy) { <button mat-menu-item id="lazy-trigger" [matMenuTriggerFor]="lazy" #lazyTrigger="matMenuTrigger">Three</button> } </mat-menu> <mat-menu #levelOne="matMenu" (closed)="levelOneCloseCallback($event)"> <button mat-menu-item>Four</button> <button mat-menu-item id="level-two-trigger" [matMenuTriggerFor]="levelTwo" #levelTwoTrigger="matMenuTrigger">Five</button> <button mat-menu-item>Six</button> </mat-menu> <mat-menu #levelTwo="matMenu" (closed)="levelTwoCloseCallback($event)"> <button mat-menu-item>Seven</button> <button mat-menu-item>Eight</button> <button mat-menu-item>Nine</button> </mat-menu> <mat-menu #lazy="matMenu"> <button mat-menu-item>Ten</button> <button mat-menu-item>Eleven</button> <button mat-menu-item>Twelve</button> </mat-menu> `, standalone: false, }) class NestedMenu { @ViewChild('root') rootMenu: MatMenu; @ViewChild('rootTrigger') rootTrigger: MatMenuTrigger; @ViewChild('rootTriggerEl') rootTriggerEl: ElementRef<HTMLElement>; @ViewChild('alternateTrigger') alternateTrigger: MatMenuTrigger; readonly rootCloseCallback = jasmine.createSpy('root menu closed callback'); @ViewChild('levelOne') levelOneMenu: MatMenu; @ViewChild('levelOneTrigger') levelOneTrigger: MatMenuTrigger; readonly levelOneCloseCallback = jasmine.createSpy('level one menu closed callback'); @ViewChild('levelTwo') levelTwoMenu: MatMenu; @ViewChild('levelTwoTrigger') levelTwoTrigger: MatMenuTrigger; readonly levelTwoCloseCallback = jasmine.createSpy('level one menu closed callback'); @ViewChild('lazy') lazyMenu: MatMenu; @ViewChild('lazyTrigger') lazyTrigger: MatMenuTrigger; showLazy = false; } @Component({ template: ` <button [matMenuTriggerFor]="root" #rootTrigger="matMenuTrigger">Toggle menu</button> <mat-menu #root="matMenu"> <button mat-menu-item [matMenuTriggerFor]="levelOne" #levelOneTrigger="matMenuTrigger">One</button> </mat-menu> <mat-menu #levelOne="matMenu" class="mat-elevation-z24"> <button mat-menu-item>Two</button> </mat-menu> `, standalone: false, }) class NestedMenuCustomElevation { @ViewChild('rootTrigger') rootTrigger: MatMenuTrigger; @ViewChild('levelOneTrigger') levelOneTrigger: MatMenuTrigger; } @Component({ template: ` <button [matMenuTriggerFor]="root" #rootTriggerEl>Toggle menu</button> <mat-menu #root="matMenu"> @for (item of items; track $index) { <button mat-menu-item class="level-one-trigger" [matMenuTriggerFor]="levelOne">{{item}}</button> } </mat-menu> <mat-menu #levelOne="matMenu"> <button mat-menu-item>Four</button> <button mat-menu-item>Five</button> </mat-menu> `, standalone: false, }) class NestedMenuRepeater { @ViewChild('rootTriggerEl') rootTriggerEl: ElementRef<HTMLElement>; @ViewChild('levelOneTrigger') levelOneTrigger: MatMenuTrigger; items = ['one', 'two', 'three']; } @Component({ template: ` <button [matMenuTriggerFor]="root" #rootTriggerEl>Toggle menu</button> <mat-menu #root="matMenu"> <button mat-menu-item class="level-one-trigger" [matMenuTriggerFor]="levelOne">One</button> <mat-menu #levelOne="matMenu"> <button mat-menu-item class="level-two-item">Two</button> </mat-menu> </mat-menu> `, standalone: false, }) class SubmenuDeclaredInsideParentMenu { @ViewChild('rootTriggerEl') rootTriggerEl: ElementRef; } @Component({ selector: 'mat-icon', template: '<ng-content></ng-content>', standalone: false, }) class FakeIcon {} @Component({ template: ` <button [matMenuTriggerFor]="menu" #triggerEl>Toggle menu</button> <mat-menu #menu="matMenu"> <ng-template matMenuContent> <button mat-menu-item>Item</button> <button mat-menu-item>Another item</button> </ng-template> </mat-menu> `, standalone: false, }) class SimpleLazyMenu { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; @ViewChild('triggerEl') triggerEl: ElementRef<HTMLElement>; @ViewChildren(MatMenuItem) items: QueryList<MatMenuItem>; } @Component({ template: ` <button [matMenuTriggerFor]="menu" [matMenuTriggerData]="{label: 'one'}" #triggerOne="matMenuTrigger">One</button> <button [matMenuTriggerFor]="menu" [matMenuTriggerData]="{label: 'two'}" #triggerTwo="matMenuTrigger">Two</button> <mat-menu #menu="matMenu"> <ng-template let-label="label" matMenuContent> <button mat-menu-item>{{label}}</button> </ng-template> </mat-menu> `, standalone: false, }) class LazyMenuWithContext { @ViewChild('triggerOne') triggerOne: MatMenuTrigger; @ViewChild('triggerTwo') triggerTwo: MatMenuTrigger; } @Component({ template: ` <button [matMenuTriggerFor]="one">Toggle menu</button> <mat-menu #one="matMenu"> <button mat-menu-item>One</button> </mat-menu> <mat-menu #two="matMenu"> <button mat-menu-item>Two</button> </mat-menu> `, standalone: false, }) class DynamicPanelMenu { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; @ViewChild('one') firstMenu: MatMenu; @ViewChild('two') secondMenu: MatMenu; } @Component({ template: ` <button [matMenuTriggerFor]="menu">Toggle menu</button> <mat-menu #menu="matMenu"> <button mat-menu-item role="menuitemcheckbox" aria-checked="true">Checked</button> <button mat-menu-item role="menuitemcheckbox" aria-checked="false">Not checked</button> </mat-menu> `, standalone: false, }) class MenuWithCheckboxItems { @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; }
117071
{ protected _viewportRuler = inject(ViewportRuler); protected _changeDetectorRef = inject(ChangeDetectorRef); readonly _elementRef = inject(ElementRef); private _dir = inject(Directionality, {optional: true}); protected _parentFormField = inject<MatFormField>(MAT_FORM_FIELD, {optional: true}); ngControl = inject(NgControl, {self: true, optional: true})!; private _liveAnnouncer = inject(LiveAnnouncer); protected _defaultOptions = inject(MAT_SELECT_CONFIG, {optional: true}); /** All of the defined select options. */ @ContentChildren(MatOption, {descendants: true}) options: QueryList<MatOption>; // TODO(crisbeto): this is only necessary for the non-MDC select, but it's technically a // public API so we have to keep it. It should be deprecated and removed eventually. /** All of the defined groups of options. */ @ContentChildren(MAT_OPTGROUP, {descendants: true}) optionGroups: QueryList<MatOptgroup>; /** User-supplied override of the trigger element. */ @ContentChild(MAT_SELECT_TRIGGER) customTrigger: MatSelectTrigger; /** * This position config ensures that the top "start" corner of the overlay * is aligned with with the top "start" of the origin by default (overlapping * the trigger completely). If the panel cannot fit below the trigger, it * will fall back to a position above the trigger. */ _positions: ConnectedPosition[] = [ { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', }, { originX: 'end', originY: 'bottom', overlayX: 'end', overlayY: 'top', }, { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', panelClass: 'mat-mdc-select-panel-above', }, { originX: 'end', originY: 'top', overlayX: 'end', overlayY: 'bottom', panelClass: 'mat-mdc-select-panel-above', }, ]; /** Scrolls a particular option into the view. */ _scrollOptionIntoView(index: number): void { const option = this.options.toArray()[index]; if (option) { const panel: HTMLElement = this.panel.nativeElement; const labelCount = _countGroupLabelsBeforeOption(index, this.options, this.optionGroups); const element = option._getHostElement(); if (index === 0 && labelCount === 1) { // If we've got one group label before the option and we're at the top option, // scroll the list to the top. This is better UX than scrolling the list to the // top of the option, because it allows the user to read the top group's label. panel.scrollTop = 0; } else { panel.scrollTop = _getOptionScrollPosition( element.offsetTop, element.offsetHeight, panel.scrollTop, panel.offsetHeight, ); } } } /** Called when the panel has been opened and the overlay has settled on its final position. */ private _positioningSettled() { this._scrollOptionIntoView(this._keyManager.activeItemIndex || 0); } /** Creates a change event object that should be emitted by the select. */ private _getChangeEvent(value: any) { return new MatSelectChange(this, value); } /** Factory function used to create a scroll strategy for this select. */ private _scrollStrategyFactory = inject(MAT_SELECT_SCROLL_STRATEGY); /** Whether or not the overlay panel is open. */ private _panelOpen = false; /** Comparison function to specify which option is displayed. Defaults to object equality. */ private _compareWith = (o1: any, o2: any) => o1 === o2; /** Unique id for this input. */ private _uid = `mat-select-${nextUniqueId++}`; /** Current `aria-labelledby` value for the select trigger. */ private _triggerAriaLabelledBy: string | null = null; /** * Keeps track of the previous form control assigned to the select. * Used to detect if it has changed. */ private _previousControl: AbstractControl | null | undefined; /** Emits whenever the component is destroyed. */ protected readonly _destroy = new Subject<void>(); /** Tracks the error state of the select. */ private _errorStateTracker: _ErrorStateTracker; /** * Emits whenever the component state changes and should cause the parent * form-field to update. Implemented as part of `MatFormFieldControl`. * @docs-private */ readonly stateChanges = new Subject<void>(); /** * Disable the automatic labeling to avoid issues like #27241. * @docs-private */ readonly disableAutomaticLabeling = true; /** * Implemented as part of MatFormFieldControl. * @docs-private */ @Input('aria-describedby') userAriaDescribedBy: string; /** Deals with the selection logic. */ _selectionModel: SelectionModel<MatOption>; /** Manages keyboard events for options in the panel. */ _keyManager: ActiveDescendantKeyManager<MatOption>; /** Ideal origin for the overlay panel. */ _preferredOverlayOrigin: CdkOverlayOrigin | ElementRef | undefined; /** Width of the overlay panel. */ _overlayWidth: string | number; /** `View -> model callback called when value changes` */ _onChange: (value: any) => void = () => {}; /** `View -> model callback called when select has been touched` */ _onTouched = () => {}; /** ID for the DOM node containing the select's value. */ _valueId = `mat-select-value-${nextUniqueId++}`; /** Emits when the panel element is finished transforming in. */ readonly _panelDoneAnimatingStream = new Subject<string>(); /** Strategy that will be used to handle scrolling while the select panel is open. */ _scrollStrategy: ScrollStrategy; _overlayPanelClass: string | string[] = this._defaultOptions?.overlayPanelClass || ''; /** Whether the select is focused. */ get focused(): boolean { return this._focused || this._panelOpen; } private _focused = false; /** A name for this control that can be used by `mat-form-field`. */ controlType = 'mat-select'; /** Trigger that opens the select. */ @ViewChild('trigger') trigger: ElementRef; /** Panel containing the select options. */ @ViewChild('panel') panel: ElementRef; /** Overlay pane containing the options. */ @ViewChild(CdkConnectedOverlay) protected _overlayDir: CdkConnectedOverlay; /** Classes to be passed to the select panel. Supports the same syntax as `ngClass`. */ @Input() panelClass: string | string[] | Set<string> | {[key: string]: any}; /** Whether the select is disabled. */ @Input({transform: booleanAttribute}) disabled: boolean = false; /** Whether ripples in the select are disabled. */ @Input({transform: booleanAttribute}) disableRipple: boolean = false; /** Tab index of the select. */ @Input({ transform: (value: unknown) => (value == null ? 0 : numberAttribute(value)), }) tabIndex: number = 0; /** Whether checkmark indicator for single-selection options is hidden. */ @Input({transform: booleanAttribute}) get hideSingleSelectionIndicator(): boolean { return this._hideSingleSelectionIndicator; } set hideSingleSelectionIndicator(value: boolean) { this._hideSingleSelectionIndicator = value; this._syncParentProperties(); } private _hideSingleSelectionIndicator: boolean = this._defaultOptions?.hideSingleSelectionIndicator ?? false; /** Placeholder to be shown if no value has been selected. */ @Input() get placeholder(): string { return this._placeholder; } set placeholder(value: string) { this._placeholder = value; this.stateChanges.next(); } private _placeholder: string; /** Whether the component is required. */ @Input({transform: booleanAttribute}) get required(): boolean { return this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false; } set required(value: boolean) { this._required = value; this.stateChanges.next(); } private _required: boolean | undefined; /** Whether the user should be allowed to select multiple options. */ @Input({transform: booleanAttribute}) get multiple(): boolean { return this._multiple; } set multiple(value: boolean) { if (this._selectionModel && (typeof ngDevMode === 'undefined' || ngDevMode)) { throw getMatSelectDynamicMultipleError(); } this._multiple = value; } private _multiple: boolean = false;
117079
`<mat-select>` is a form control for selecting a value from a set of options, similar to the native `<select>` element. You can read more about selects in the [Material Design spec](https://material.io/design/components/menus.html). It is designed to work inside of a [`<mat-form-field>`](https://material.angular.io/components/form-field/overview) element. To add options to the select, add `<mat-option>` elements to the `<mat-select>`. Each `<mat-option>` has a `value` property that can be used to set the value that will be selected if the user chooses this option. The content of the `<mat-option>` is what will be shown to the user. Angular Material also supports use of the native `<select>` element inside of `<mat-form-field>`. The native control has several performance, accessibility, and usability advantages. See [the documentation for form-field](https://material.angular.io/components/form-field) for more information. To use a native select inside `<mat-form-field>`, import `MatInputModule` and add the `matNativeControl` attribute to the `<select>` element. <!-- example(select-overview) --> ### Getting and setting the select value The `<mat-select>` supports 2-way binding to the `value` property without the need for Angular forms. <!-- example(select-value-binding) --> Both`<mat-select>` and `<select>` support all of the form directives from the core `FormsModule` (`NgModel`) and `ReactiveFormsModule` (`FormControl`, `FormGroup`, etc.) As with native `<select>`, `<mat-select>` also supports a `compareWith` function. (Additional information about using a custom `compareWith` function can be found in the [Angular forms documentation](https://angular.dev/api/forms/SelectControlValueAccessor#compareWith)). <!-- example(select-form) --> ### Form field features There are a number of `<mat-form-field>` features that can be used with both `<select>` and `<mat-select>`. These include error messages, hint text, prefix & suffix, and theming. For additional information about these features, see the [form field documentation](https://material.angular.io/components/form-field/overview). <!-- example(select-hint-error) --> ### Setting a static placeholder The placeholder is text shown when the `<mat-form-field>` label is floating but the `<mat-select>` is empty. It is used to give the user an additional hint about the value they should select. The placeholder can be specified by setting the `placeholder` attribute on the `<mat-select>` element. In some cases that `<mat-form-field>` may use the placeholder as the label (see the [form field label documentation](https://material.angular.io/components/form-field/overview#floating-label)). ### Disabling the select or individual options It is possible to disable the entire select or individual options in the select by using the disabled property on the `<select>` or `<mat-select>` and the `<option>` or `<mat-option>` elements respectively. When working with Reactive Forms, the select component can be disabled/enabled via form controls. This can be accomplished by creating a `FormControl` with the disabled property `FormControl({value: '', disabled: true})` or using `FormControl.enable()`, `FormControl.disable()`. <!-- example(select-disabled) --> ### Resetting the select value If you want one of your options to reset the select's value, you can omit specifying its value. <!-- example(select-reset) --> ### Creating groups of options The `<mat-optgroup>` element can be used to group common options under a subheading. The name of the group can be set using the `label` property of `<mat-optgroup>`. Like individual `<mat-option>` elements, an entire `<mat-optgroup>` can be disabled or enabled by setting the `disabled` property on the group. <!-- example(select-optgroup) --> ### Multiple selection `<mat-select>` defaults to single-selection mode, but can be configured to allow multiple selection by setting the `multiple` property. This will allow the user to select multiple values at once. When using the `<mat-select>` in multiple selection mode, its value will be a sorted list of all selected values rather than a single value. Using multiple selection with a native select element (`<select multiple>`) is discouraged inside `<mat-form-field>`, as the inline listbox appearance is inconsistent with other Material Design components. <!-- example(select-multiple) --> ### Customizing the trigger label If you want to display a custom trigger label inside a `<mat-select>`, you can use the `<mat-select-trigger>` element. <!-- example(select-custom-trigger) --> ### Disabling the ripple effect By default, when a user clicks on a `<mat-option>`, a ripple animation is shown. This can be disabled by setting the `disableRipple` property on `<mat-select>`. <!-- example(select-no-ripple) --> ### Adding custom styles to the dropdown panel In order to facilitate easily styling the dropdown panel, `<mat-select>` has a `panelClass` property which can be used to apply additional CSS classes to the dropdown panel. <!-- example(select-panel-class) --> ### Changing when error messages are shown The `<mat-form-field>` allows you to [associate error messages](https://material.angular.io/components/form-field/overview#error-messages) with your `<select>` or `<mat-select>`. By default, these error messages are shown when the control is invalid and either the user has interacted with (touched) the element or the parent form has been submitted. If you wish to override this behavior (e.g. to show the error as soon as the invalid control is dirty or when a parent form group is invalid), you can use the `errorStateMatcher` property of the `<mat-select>`. The property takes an instance of an `ErrorStateMatcher` object. An `ErrorStateMatcher` must implement a single method `isErrorState` which takes the `FormControl` for this `<mat-select>` as well as the parent form and returns a boolean indicating whether errors should be shown. (`true` indicating that they should be shown, and `false` indicating that they should not.) <!-- example(select-error-state-matcher) --> A global error state matcher can be specified by setting the `ErrorStateMatcher` provider. This applies to all inputs. For convenience, `ShowOnDirtyErrorStateMatcher` is available in order to globally cause input errors to show when the input is dirty and invalid. ```ts @NgModule({ providers: [ {provide: ErrorStateMatcher, useClass: ShowOnDirtyErrorStateMatcher} ] }) ``` ### Keyboard interaction | Keyboard shortcut | Action | |----------------------------------------|-----------------------------------------------------------------------| | <kbd>Down Arrow</kbd> | Navigate to the next option. | | <kbd>Up Arrow</kbd> | Navigate to the previous option. | | <kbd>Enter</kbd> | If closed, open the select panel. If open, selects the active option. | | <kbd>Escape</kbd> | Close the select panel. | | <kbd>Alt</kbd> + <kbd>Up Arrow</kbd> | Close the select panel. | | <kbd>Alt</kbd> + <kbd>Down Arrow</kbd> | Open the select panel if there are any matching options. | ### Accessibility When possible, prefer a native `<select>` element over `MatSelect`. The native control provides the most accessible experience across the widest range of platforms. `MatSelect` implements the combobox pattern detailed in the [1.2 version of the ARIA specification](https://www.w3.org/TR/wai-aria-1.2). The combobox trigger controls a `role="listbox"` element opened in a pop-up. Previous versions of the ARIA specification required that `role="combobox"` apply to a text input control, but the 1.2 version of the specification supports a wider variety of interaction patterns. This newer usage of ARIA works in all browser and screen-reader combinations supported by Angular Material. Because the pop-up uses the `role="listbox"` pattern, you should _not_ put other interactive controls, such as buttons or checkboxes, inside a select option. Nesting interactive controls like this interferes with most assistive technology. Always provide an accessible label for the select. This can be done by adding a `<mat-label>` inside of `<mat-form-field>`, the `aria-label` attribute, or the `aria-labelledby` attribute. By default, `MatSelect` displays a checkmark to identify selected items. While you can hide the checkmark indicator for single-selection via `hideSingleSelectionIndicator`, this makes the component less accessible by making it harder or impossible for users to visually identify selected items.
117081
Please see the official documentation at https://material.angular.io/components/component/select
117084
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { animate, animateChild, AnimationTriggerMetadata, query, state, style, transition, trigger, } from '@angular/animations'; /** * The following are all the animations for the mat-select component, with each * const containing the metadata for one animation. * * The values below match the implementation of the AngularJS Material mat-select animation. * @docs-private */ export const matSelectAnimations: { /** * @deprecated No longer being used. To be removed. * @breaking-change 12.0.0 */ readonly transformPanelWrap: AnimationTriggerMetadata; readonly transformPanel: AnimationTriggerMetadata; } = { /** * This animation ensures the select's overlay panel animation (transformPanel) is called when * closing the select. * This is needed due to https://github.com/angular/angular/issues/23302 */ transformPanelWrap: trigger('transformPanelWrap', [ transition('* => void', query('@transformPanel', [animateChild()], {optional: true})), ]), /** This animation transforms the select's overlay panel on and off the page. */ transformPanel: trigger('transformPanel', [ state( 'void', style({ opacity: 0, transform: 'scale(1, 0.8)', }), ), transition( 'void => showing', animate( '120ms cubic-bezier(0, 0, 0.2, 1)', style({ opacity: 1, transform: 'scale(1, 1)', }), ), ), transition('* => void', animate('100ms linear', style({opacity: 0}))), ]), };
117102
it('should not throw when toggling an icon that has a binding in IE11', () => { iconRegistry.addSvgIcon('fluffy', trustUrl('cat.svg')); const fixture = TestBed.createComponent(IconWithBindingAndNgIf); fixture.detectChanges(); http.expectOne('cat.svg').flush(FAKE_SVGS.cat); expect(() => { fixture.componentInstance.showIcon = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.showIcon = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); }).not.toThrow(); }); it('should be able to configure the viewBox for the icon set', () => { iconRegistry.addSvgIconSet(trustUrl('arrow-set.svg'), {viewBox: '0 0 43 43'}); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); let svgElement: SVGElement; testComponent.iconName = 'left-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('arrow-set.svg').flush(FAKE_SVGS.arrows); svgElement = verifyAndGetSingleSvgChild(matIconElement); expect(svgElement.getAttribute('viewBox')).toBe('0 0 43 43'); }); it('should remove the SVG element from the DOM when the binding is cleared', () => { iconRegistry.addSvgIconSet(trustUrl('arrow-set.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const testComponent = fixture.componentInstance; const icon = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'left-arrow'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('arrow-set.svg').flush(FAKE_SVGS.arrows); expect(icon.querySelector('svg')).toBeTruthy(); testComponent.iconName = undefined; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(icon.querySelector('svg')).toBeFalsy(); }); it('should keep non-SVG user content inside the icon element', fakeAsync(() => { iconRegistry.addSvgIcon('fido', trustUrl('dog.svg')); const fixture = TestBed.createComponent(SvgIconWithUserContent); const testComponent = fixture.componentInstance; const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); testComponent.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); http.expectOne('dog.svg').flush(FAKE_SVGS.dog); const userDiv = iconElement.querySelector('div'); expect(userDiv).toBeTruthy(); expect(iconElement.textContent.trim()).toContain('Hello'); tick(); })); it('should cancel in-progress fetches if the icon changes', fakeAsync(() => { // Register an icon that will resolve immediately. iconRegistry.addSvgIconLiteral('fluffy', trustHtml(FAKE_SVGS.cat)); // Register a different icon that takes some time to resolve. iconRegistry.addSvgIcon('fido', trustUrl('dog.svg')); const fixture = TestBed.createComponent(IconFromSvgName); const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon'); // Assign the slow icon first. fixture.componentInstance.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); // Assign the quick icon while the slow one is still in-flight. fixture.componentInstance.iconName = 'fluffy'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); // Expect for the in-flight request to have been cancelled. expect(http.expectOne('dog.svg').cancelled).toBe(true); // Expect the last icon to have been assigned. verifyPathChildElement(verifyAndGetSingleSvgChild(iconElement), 'meow'); })); it('should cancel in-progress fetches if the component is destroyed', fakeAsync(() => { iconRegistry.addSvgIcon('fido', trustUrl('dog.svg')); const fixture = TestBed.createComponent(IconFromSvgName); fixture.componentInstance.iconName = 'fido'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.destroy(); expect(http.expectOne('dog.svg').cancelled).toBe(true); })); });
117142
it('should allow manually dismissing with an action', fakeAsync(() => { const dismissCompleteSpy = jasmine.createSpy('dismiss complete spy'); const actionCompleteSpy = jasmine.createSpy('action complete spy'); const snackBarRef = snackBar.open('Some content'); viewContainerFixture.detectChanges(); snackBarRef.afterDismissed().subscribe({complete: dismissCompleteSpy}); snackBarRef.onAction().subscribe({complete: actionCompleteSpy}); snackBarRef.dismissWithAction(); viewContainerFixture.detectChanges(); flush(); expect(dismissCompleteSpy).toHaveBeenCalled(); expect(actionCompleteSpy).toHaveBeenCalled(); })); it('should indicate in `afterClosed` whether it was dismissed by an action', fakeAsync(() => { const dismissSpy = jasmine.createSpy('dismiss spy'); const snackBarRef = snackBar.open('Some content'); viewContainerFixture.detectChanges(); snackBarRef.afterDismissed().subscribe(dismissSpy); snackBarRef.dismissWithAction(); viewContainerFixture.detectChanges(); flush(); expect(dismissSpy).toHaveBeenCalledWith(jasmine.objectContaining({dismissedByAction: true})); })); it('should complete the onAction stream when not closing via an action', fakeAsync(() => { const actionCompleteSpy = jasmine.createSpy('action complete spy'); const snackBarRef = snackBar.open('Some content'); viewContainerFixture.detectChanges(); snackBarRef.onAction().subscribe({complete: actionCompleteSpy}); snackBarRef.dismiss(); viewContainerFixture.detectChanges(); flush(); expect(actionCompleteSpy).toHaveBeenCalled(); })); it('should dismiss automatically after a specified timeout', fakeAsync(() => { const config = new MatSnackBarConfig(); config.duration = 250; const snackBarRef = snackBar.open('content', 'test', config); const afterDismissSpy = jasmine.createSpy('after dismiss spy'); snackBarRef.afterDismissed().subscribe(afterDismissSpy); viewContainerFixture.detectChanges(); tick(); expect(afterDismissSpy).not.toHaveBeenCalled(); tick(1000); viewContainerFixture.detectChanges(); tick(); expect(afterDismissSpy).toHaveBeenCalled(); })); it('should add extra classes to the container', () => { snackBar.open(simpleMessage, simpleActionLabel, {panelClass: ['one', 'two']}); viewContainerFixture.detectChanges(); let containerClasses = overlayContainerElement.querySelector('mat-snack-bar-container')!.classList; expect(containerClasses).toContain('one'); expect(containerClasses).toContain('two'); }); it('should set the layout direction', () => { snackBar.open(simpleMessage, simpleActionLabel, {direction: 'rtl'}); viewContainerFixture.detectChanges(); let pane = overlayContainerElement.querySelector('.cdk-global-overlay-wrapper')!; expect(pane.getAttribute('dir')) .withContext('Expected the pane to be in RTL mode.') .toBe('rtl'); }); it('should be able to override the default config', fakeAsync(() => { viewContainerFixture.destroy(); TestBed.resetTestingModule() .overrideProvider(MAT_SNACK_BAR_DEFAULT_OPTIONS, { deps: [], useFactory: () => ({panelClass: 'custom-class'}), }) .configureTestingModule({imports: [MatSnackBarModule, NoopAnimationsModule]}); snackBar = TestBed.inject(MatSnackBar); overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement(); snackBar.open(simpleMessage); flush(); expect(overlayContainerElement.querySelector('mat-snack-bar-container')!.classList) .withContext('Expected class applied through the defaults to be applied.') .toContain('custom-class'); })); it('should dismiss the open snack bar on destroy', fakeAsync(() => { snackBar.open(simpleMessage); viewContainerFixture.detectChanges(); expect(overlayContainerElement.childElementCount).toBeGreaterThan(0); snackBar.ngOnDestroy(); viewContainerFixture.detectChanges(); flush(); expect(overlayContainerElement.childElementCount).toBe(0); })); it('should cap the timeout to the maximum accepted delay in setTimeout', fakeAsync(() => { const config = new MatSnackBarConfig(); config.duration = Infinity; snackBar.open('content', 'test', config); viewContainerFixture.detectChanges(); spyOn(window, 'setTimeout').and.callThrough(); tick(100); expect(window.setTimeout).toHaveBeenCalledWith(jasmine.any(Function), Math.pow(2, 31) - 1); flush(); })); it('should only keep one snack bar in the DOM if multiple are opened at the same time', fakeAsync(() => { for (let i = 0; i < 10; i++) { snackBar.open('Snack time!', 'Chew'); viewContainerFixture.detectChanges(); } flush(); expect(overlayContainerElement.querySelectorAll('mat-snack-bar-container').length).toBe(1); })); describe('with custom component', () => { it('should open a custom component', () => { const snackBarRef = snackBar.openFromComponent(BurritosNotification); expect(snackBarRef.instance instanceof BurritosNotification) .withContext('Expected the snack bar content component to be BurritosNotification') .toBe(true); expect(overlayContainerElement.textContent!.trim()) .withContext('Expected component to have the proper text.') .toBe('Burritos are on the way.'); }); it('should inject the snack bar reference into the component', () => { const snackBarRef = snackBar.openFromComponent(BurritosNotification); expect(snackBarRef.instance.snackBarRef) .withContext('Expected component to have an injected snack bar reference.') .toBe(snackBarRef); }); it('should have exactly one MDC label element', () => { snackBar.openFromComponent(BurritosNotification); viewContainerFixture.detectChanges(); expect(overlayContainerElement.querySelectorAll('.mdc-snackbar__label').length).toBe(1); }); it('should be able to inject arbitrary user data', () => { const snackBarRef = snackBar.openFromComponent(BurritosNotification, { data: { burritoType: 'Chimichanga', }, }); expect(snackBarRef.instance.data) .withContext('Expected component to have a data object.') .toBeTruthy(); expect(snackBarRef.instance.data.burritoType) .withContext('Expected the injected data object to be the one the user provided.') .toBe('Chimichanga'); }); it('should allow manually dismissing with an action', fakeAsync(() => { const dismissCompleteSpy = jasmine.createSpy('dismiss complete spy'); const actionCompleteSpy = jasmine.createSpy('action complete spy'); const snackBarRef = snackBar.openFromComponent(BurritosNotification); viewContainerFixture.detectChanges(); snackBarRef.afterDismissed().subscribe({complete: dismissCompleteSpy}); snackBarRef.onAction().subscribe({complete: actionCompleteSpy}); snackBarRef.dismissWithAction(); viewContainerFixture.detectChanges(); flush(); expect(dismissCompleteSpy).toHaveBeenCalled(); expect(actionCompleteSpy).toHaveBeenCalled(); })); }); describe('with TemplateRef', () => { let templateFixture: ComponentFixture<ComponentWithTemplateRef>; beforeEach(() => { templateFixture = TestBed.createComponent(ComponentWithTemplateRef); templateFixture.detectChanges(); }); it('should be able to open a snack bar using a TemplateRef', () => { templateFixture.componentInstance.localValue = 'Pizza'; templateFixture.changeDetectorRef.markForCheck(); snackBar.openFromTemplate(templateFixture.componentInstance.templateRef); templateFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; expect(containerElement.textContent).toContain('Fries'); expect(containerElement.textContent).toContain('Pizza'); templateFixture.componentInstance.localValue = 'Pasta'; templateFixture.changeDetectorRef.markForCheck(); templateFixture.detectChanges(); expect(containerElement.textContent).toContain('Pasta'); }); it('should be able to pass in contextual data when opening with a TemplateRef', () => { snackBar.openFromTemplate(templateFixture.componentInstance.templateRef, { data: {value: 'Oranges'}, }); templateFixture.detectChanges(); const containerElement = overlayContainerElement.querySelector('mat-snack-bar-container')!; expect(containerElement.textContent).toContain('Oranges'); }); }); });
117153
class MatSnackBarContainer extends BasePortalOutlet implements OnDestroy { private _ngZone = inject(NgZone); private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); private _changeDetectorRef = inject(ChangeDetectorRef); private _platform = inject(Platform); snackBarConfig = inject(MatSnackBarConfig); private _document = inject(DOCUMENT); private _trackedModals = new Set<Element>(); /** The number of milliseconds to wait before announcing the snack bar's content. */ private readonly _announceDelay: number = 150; /** The timeout for announcing the snack bar's content. */ private _announceTimeoutId: number; /** Whether the component has been destroyed. */ private _destroyed = false; /** The portal outlet inside of this container into which the snack bar content will be loaded. */ @ViewChild(CdkPortalOutlet, {static: true}) _portalOutlet: CdkPortalOutlet; /** Subject for notifying that the snack bar has announced to screen readers. */ readonly _onAnnounce: Subject<void> = new Subject(); /** Subject for notifying that the snack bar has exited from view. */ readonly _onExit: Subject<void> = new Subject(); /** Subject for notifying that the snack bar has finished entering the view. */ readonly _onEnter: Subject<void> = new Subject(); /** The state of the snack bar animations. */ _animationState = 'void'; /** aria-live value for the live region. */ _live: AriaLivePoliteness; /** * Element that will have the `mdc-snackbar__label` class applied if the attached component * or template does not have it. This ensures that the appropriate structure, typography, and * color is applied to the attached view. */ @ViewChild('label', {static: true}) _label: ElementRef; /** * Role of the live region. This is only for Firefox as there is a known issue where Firefox + * JAWS does not read out aria-live message. */ _role?: 'status' | 'alert'; /** Unique ID of the aria-live element. */ readonly _liveElementId = `mat-snack-bar-container-live-${uniqueId++}`; constructor(...args: unknown[]); constructor() { super(); const config = this.snackBarConfig; // Use aria-live rather than a live role like 'alert' or 'status' // because NVDA and JAWS have show inconsistent behavior with live roles. if (config.politeness === 'assertive' && !config.announcementMessage) { this._live = 'assertive'; } else if (config.politeness === 'off') { this._live = 'off'; } else { this._live = 'polite'; } // Only set role for Firefox. Set role based on aria-live because setting role="alert" implies // aria-live="assertive" which may cause issues if aria-live is set to "polite" above. if (this._platform.FIREFOX) { if (this._live === 'polite') { this._role = 'status'; } if (this._live === 'assertive') { this._role = 'alert'; } } } /** Attach a component portal as content to this snack bar container. */ attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> { this._assertNotAttached(); const result = this._portalOutlet.attachComponentPortal(portal); this._afterPortalAttached(); return result; } /** Attach a template portal as content to this snack bar container. */ attachTemplatePortal<C>(portal: TemplatePortal<C>): EmbeddedViewRef<C> { this._assertNotAttached(); const result = this._portalOutlet.attachTemplatePortal(portal); this._afterPortalAttached(); return result; } /** * Attaches a DOM portal to the snack bar container. * @deprecated To be turned into a method. * @breaking-change 10.0.0 */ override attachDomPortal = (portal: DomPortal) => { this._assertNotAttached(); const result = this._portalOutlet.attachDomPortal(portal); this._afterPortalAttached(); return result; }; /** Handle end of animations, updating the state of the snackbar. */ onAnimationEnd(event: AnimationEvent) { const {fromState, toState} = event; if ((toState === 'void' && fromState !== 'void') || toState === 'hidden') { this._completeExit(); } if (toState === 'visible') { // Note: we shouldn't use `this` inside the zone callback, // because it can cause a memory leak. const onEnter = this._onEnter; this._ngZone.run(() => { onEnter.next(); onEnter.complete(); }); } } /** Begin animation of snack bar entrance into view. */ enter(): void { if (!this._destroyed) { this._animationState = 'visible'; // _animationState lives in host bindings and `detectChanges` does not refresh host bindings // so we have to call `markForCheck` to ensure the host view is refreshed eventually. this._changeDetectorRef.markForCheck(); this._changeDetectorRef.detectChanges(); this._screenReaderAnnounce(); } } /** Begin animation of the snack bar exiting from view. */ exit(): Observable<void> { // It's common for snack bars to be opened by random outside calls like HTTP requests or // errors. Run inside the NgZone to ensure that it functions correctly. this._ngZone.run(() => { // Note: this one transitions to `hidden`, rather than `void`, in order to handle the case // where multiple snack bars are opened in quick succession (e.g. two consecutive calls to // `MatSnackBar.open`). this._animationState = 'hidden'; this._changeDetectorRef.markForCheck(); // Mark this element with an 'exit' attribute to indicate that the snackbar has // been dismissed and will soon be removed from the DOM. This is used by the snackbar // test harness. this._elementRef.nativeElement.setAttribute('mat-exit', ''); // If the snack bar hasn't been announced by the time it exits it wouldn't have been open // long enough to visually read it either, so clear the timeout for announcing. clearTimeout(this._announceTimeoutId); }); return this._onExit; } /** Makes sure the exit callbacks have been invoked when the element is destroyed. */ ngOnDestroy() { this._destroyed = true; this._clearFromModals(); this._completeExit(); } /** * Removes the element in a microtask. Helps prevent errors where we end up * removing an element which is in the middle of an animation. */ private _completeExit() { queueMicrotask(() => { this._onExit.next(); this._onExit.complete(); }); } /** * Called after the portal contents have been attached. Can be * used to modify the DOM once it's guaranteed to be in place. */ private _afterPortalAttached() { const element: HTMLElement = this._elementRef.nativeElement; const panelClasses = this.snackBarConfig.panelClass; if (panelClasses) { if (Array.isArray(panelClasses)) { // Note that we can't use a spread here, because IE doesn't support multiple arguments. panelClasses.forEach(cssClass => element.classList.add(cssClass)); } else { element.classList.add(panelClasses); } } this._exposeToModals(); // Check to see if the attached component or template uses the MDC template structure, // specifically the MDC label. If not, the container should apply the MDC label class to this // component's label container, which will apply MDC's label styles to the attached view. const label = this._label.nativeElement; const labelClass = 'mdc-snackbar__label'; label.classList.toggle(labelClass, !label.querySelector(`.${labelClass}`)); } /** * Some browsers won't expose the accessibility node of the live element if there is an * `aria-modal` and the live element is outside of it. This method works around the issue by * pointing the `aria-owns` of all modals to the live element. */
117227
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import {createTestApp, getFileContent} from '@angular/cdk/schematics/testing'; import {COLLECTION_PATH} from '../../paths'; import {Schema} from './schema'; describe('material-navigation-schematic', () => { let runner: SchematicTestRunner; const baseOptions: Schema = { name: 'foo', project: 'material', }; beforeEach(() => { runner = new SchematicTestRunner('schematics', COLLECTION_PATH); }); function expectNavigationSchematicModuleImports(tree: UnitTestTree) { const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toMatch(/MatToolbarModule,\s+/); expect(moduleContent).toMatch(/MatButtonModule,\s+/); expect(moduleContent).toMatch(/MatSidenavModule,\s+/); expect(moduleContent).toMatch(/MatIconModule,\s+/); expect(moduleContent).toMatch(/MatListModule\s+],/); expect(moduleContent).toContain(`import { MatButtonModule } from '@angular/material/button';`); expect(moduleContent).toContain(`import { MatIconModule } from '@angular/material/icon';`); expect(moduleContent).toContain(`import { MatListModule } from '@angular/material/list';`); expect(moduleContent).toContain( `import { MatToolbarModule } from '@angular/material/toolbar';`, ); expect(moduleContent).toContain( `import { MatSidenavModule } from '@angular/material/sidenav';`, ); } it('should create navigation files and add them to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('navigation', baseOptions, app); const files = tree.files; expect(files).toContain('/projects/material/src/app/foo/foo.component.css'); expect(files).toContain('/projects/material/src/app/foo/foo.component.html'); expect(files).toContain('/projects/material/src/app/foo/foo.component.spec.ts'); expect(files).toContain('/projects/material/src/app/foo/foo.component.ts'); const moduleContent = getFileContent(tree, '/projects/material/src/app/app.module.ts'); expect(moduleContent).toMatch(/import.*Foo.*from '.\/foo\/foo.component'/); expect(moduleContent).toMatch(/declarations:\s*\[[^\]]+?,\r?\n\s+FooComponent\r?\n/m); }); it('should add navigation imports to module', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('navigation', baseOptions, app); expectNavigationSchematicModuleImports(tree); }); it('should support `nav` as schematic alias', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('nav', baseOptions, app); expectNavigationSchematicModuleImports(tree); }); it('should throw if no name has been specified', async () => { const appTree = await createTestApp(runner); await expectAsync( runner.runSchematic('navigation', {project: 'material'}, appTree), ).toBeRejectedWithError(/required property 'name'/); }); describe('standalone option', () => { it('should generate a standalone component', async () => { const app = await createTestApp(runner, {standalone: false}); const tree = await runner.runSchematic('navigation', {...baseOptions, standalone: true}, app); const module = getFileContent(tree, '/projects/material/src/app/app.module.ts'); const component = getFileContent(tree, '/projects/material/src/app/foo/foo.component.ts'); const requiredModules = [ 'MatToolbarModule', 'MatButtonModule', 'MatSidenavModule', 'MatListModule', 'MatIconModule', ]; requiredModules.forEach(name => { expect(module).withContext('Module should not import dependencies').not.toContain(name); expect(component).withContext('Component should import dependencies').toContain(name); }); expect(module).not.toContain('FooComponent'); expect(component).toContain('standalone: true'); expect(component).toContain('imports: ['); }); it('should infer the standalone option from the project structure', async () => { const app = await createTestApp(runner, {standalone: true}); const tree = await runner.runSchematic('navigation', baseOptions, app); const componentContent = getFileContent( tree, '/projects/material/src/app/foo/foo.component.ts', ); expect(tree.exists('/projects/material/src/app/app.module.ts')).toBe(false); expect(componentContent).toContain('standalone: true'); expect(componentContent).toContain('imports: ['); }); }); describe('style option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'navigation', {style: 'scss', ...baseOptions}, await createTestApp(runner), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.scss'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'navigation', baseOptions, await createTestApp(runner, {style: 'less'}), ); expect(tree.files).toContain('/projects/material/src/app/foo/foo.component.less'); }); }); describe('inlineStyle option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'navigation', {inlineStyle: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'navigation', baseOptions, await createTestApp(runner, {inlineStyle: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.css'); }); }); describe('inlineTemplate option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'navigation', {inlineTemplate: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'navigation', baseOptions, await createTestApp(runner, {inlineTemplate: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.html'); }); }); describe('skipTests option', () => { it('should respect the option value', async () => { const tree = await runner.runSchematic( 'navigation', {skipTests: true, ...baseOptions}, await createTestApp(runner), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); it('should fall back to the @schematics/angular:component option value', async () => { const tree = await runner.runSchematic( 'navigation', baseOptions, await createTestApp(runner, {skipTests: true}), ); expect(tree.files).not.toContain('/projects/material/src/app/foo/foo.component.spec.ts'); }); }); describe('router option', () => { it('should respect the option value if routing true', async () => { const tree = await runner.runSchematic( 'navigation', {routing: true, ...baseOptions}, await createTestApp(runner), ); const template = tree.readContent('/projects/material/src/app/foo/foo.component.html'); expect(template).toContain('<a mat-list-item routerLink="/">Link 1</a>'); }); it('should respect the option value if routing false', async () => { const tree = await runner.runSchematic( 'navigation', {routing: false, ...baseOptions}, await createTestApp(runner), ); const template = tree.readContent('/projects/material/src/app/foo/foo.component.html'); expect(template).toContain('<a mat-list-item href="#">Link 1</a>'); }); }); });