_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
components/src/material/tooltip/BUILD.bazel_0_1667
load( "//tools:defaults.bzl", "extract_tokens", "markdown_to_html", "ng_module", "ng_test_library", "ng_web_test_suite", "sass_binary", "sass_library", ) package(default_visibility = ["//visibility:public"]) ng_module( name = "tooltip", srcs = glob( ["**/*.ts"], exclude = [ "**/*.spec.ts", ], ), assets = [ ":tooltip_scss", ] + glob(["**/*.html"]), deps = [ "//src/cdk/coercion", "//src/cdk/overlay", "//src/cdk/portal", "//src/material/core", ], ) sass_library( name = "tooltip_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "tooltip_scss", src = "tooltip.scss", deps = [ "//src/material/core:core_scss_lib", ], ) ng_test_library( name = "tooltip_tests_lib", srcs = glob( ["**/*.spec.ts"], exclude = [ "**/*.e2e.spec.ts", ], ), deps = [ ":tooltip", "//src/cdk/a11y", "//src/cdk/bidi", "//src/cdk/keycodes", "//src/cdk/overlay", "//src/cdk/platform", "//src/cdk/testing/private", "@npm//@angular/animations", "@npm//@angular/platform-browser", "@npm//rxjs", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":tooltip_tests_lib", ], ) markdown_to_html( name = "overview", srcs = [":tooltip.md"], ) extract_tokens( name = "tokens", srcs = [":tooltip_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "commit_id": "ea0d1ba7b", "end_byte": 1667, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/tooltip/BUILD.bazel" }
components/src/material/tooltip/tooltip.html_0_262
<div #tooltip class="mdc-tooltip mat-mdc-tooltip" [ngClass]="tooltipClass" (animationend)="_handleAnimationEnd($event)" [class.mdc-tooltip--multiline]="_isMultiline"> <div class="mat-mdc-tooltip-surface mdc-tooltip__surface">{{message}}</div> </div>
{ "commit_id": "ea0d1ba7b", "end_byte": 262, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.html" }
components/src/material/tooltip/index.ts_0_234
/** * @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 */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/tooltip/index.ts" }
components/src/material/tooltip/tooltip.md_0_4098
The Angular Material tooltip provides a text label that is displayed when the user hovers over or longpresses an element. <!-- example(tooltip-overview) --> ### Positioning The tooltip will be displayed below the element by default, but this can be configured using the `matTooltipPosition` input. The tooltip can be displayed above, below, left, or right of the element. If the tooltip should switch left/right positions in an RTL layout direction, then the input values `before` and `after` should be used instead of `left` and `right`, respectively. | Position | Description | |-----------|--------------------------------------------------------------------------------------| | `above` | Always display above the element | | `below` | Always display beneath the element | | `left` | Always display to the left of the element | | `right` | Always display to the right of the element | | `before` | Display to the left in left-to-right layout and to the right in right-to-left layout | | `after` | Display to the right in left-to-right layout and to the left in right-to-left layout | Based on the position in which the tooltip is shown, the `.mat-tooltip-panel` element will receive a CSS class that can be used for style (e.g. to add an arrow). The possible classes are `mat-tooltip-panel-above`, `mat-tooltip-panel-below`, `mat-tooltip-panel-left`, `mat-tooltip-panel-right`. <!-- example(tooltip-position) --> To display the tooltip relative to the mouse or touch that triggered it, use the `matTooltipPositionAtOrigin` input. With this setting turned on, the tooltip will display relative to the origin of the trigger rather than the host element. In cases where the tooltip is not triggered by a touch event or mouse click, it will display the same as if this setting was turned off. ### Showing and hiding By default, the tooltip will be immediately shown when the user's mouse hovers over the tooltip's trigger element and immediately hides when the user's mouse leaves. On mobile, the tooltip displays when the user longpresses the element and hides after a delay of 1500ms. #### Show and hide delays To add a delay before showing or hiding the tooltip, you can use the inputs `matTooltipShowDelay` and `matTooltipHideDelay` to provide a delay time in milliseconds. The following example has a tooltip that waits one second to display after the user hovers over the button, and waits two seconds to hide after the user moves the mouse away. <!-- example(tooltip-delay) --> #### Changing the default delay behavior You can configure your app's tooltip default show/hide delays by configuring and providing your options using the `MAT_TOOLTIP_DEFAULT_OPTIONS` injection token. <!-- example(tooltip-modified-defaults) --> #### Manually showing and hiding the tooltip To manually cause the tooltip to show or hide, you can call the `show` and `hide` directive methods, which both accept a number in milliseconds to delay before applying the display change. <!-- example(tooltip-manual) --> #### Disabling the tooltip from showing To completely disable a tooltip, set `matTooltipDisabled`. While disabled, a tooltip will never be shown. ### Accessibility `MatTooltip` adds an `aria-describedby` description that provides a reference to a visually hidden element containing the tooltip's message. This provides screen-readers the information needed to read out the tooltip's contents when the user focuses on tooltip's trigger. The element referenced by `aria-describedby` is not the tooltip itself, but instead an invisible copy of the tooltip content that is always present in the DOM. Avoid interactions that exclusively show a tooltip with pointer events like click and mouseenter. Always ensure that keyboard users can perform the same set of actions available to mouse and touch users.
{ "commit_id": "ea0d1ba7b", "end_byte": 4098, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/tooltip/tooltip.md" }
components/src/material/tooltip/testing/tooltip-harness-filters.ts_0_424
/** * @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 {BaseHarnessFilters} from '@angular/cdk/testing'; /** A set of criteria that can be used to filter a list of `MatTooltipHarness` instances. */ export interface TooltipHarnessFilters extends BaseHarnessFilters {}
{ "commit_id": "ea0d1ba7b", "end_byte": 424, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/tooltip/testing/tooltip-harness-filters.ts" }
components/src/material/tooltip/testing/tooltip-harness.ts_0_2869
/** * @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 { ComponentHarness, ComponentHarnessConstructor, HarnessPredicate, } from '@angular/cdk/testing'; import {TooltipHarnessFilters} from './tooltip-harness-filters'; /** Harness for interacting with a mat-tooltip in tests. */ export class MatTooltipHarness extends ComponentHarness { static hostSelector = '.mat-mdc-tooltip-trigger'; private _optionalPanel = this.documentRootLocatorFactory().locatorForOptional('.mat-mdc-tooltip'); private _hiddenClass = 'mat-mdc-tooltip-hide'; private _disabledClass = 'mat-mdc-tooltip-disabled'; private _showAnimationName = 'mat-mdc-tooltip-show'; private _hideAnimationName = 'mat-mdc-tooltip-hide'; /** * Gets a `HarnessPredicate` that can be used to search for a tooltip trigger with specific * attributes. * @param options Options for narrowing the search. * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatTooltipHarness>( this: ComponentHarnessConstructor<T>, options: TooltipHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options); } /** Shows the tooltip. */ async show(): Promise<void> { const host = await this.host(); // We need to dispatch both `touchstart` and a hover event, because the tooltip binds // different events depending on the device. The `changedTouches` is there in case the // element has ripples. await host.dispatchEvent('touchstart', {changedTouches: []}); await host.hover(); const panel = await this._optionalPanel(); await panel?.dispatchEvent('animationend', {animationName: this._showAnimationName}); } /** Hides the tooltip. */ async hide(): Promise<void> { const host = await this.host(); // We need to dispatch both `touchstart` and a hover event, because // the tooltip binds different events depending on the device. await host.dispatchEvent('touchend'); await host.mouseAway(); const panel = await this._optionalPanel(); await panel?.dispatchEvent('animationend', {animationName: this._hideAnimationName}); } /** Gets whether the tooltip is open. */ async isOpen(): Promise<boolean> { const panel = await this._optionalPanel(); return !!panel && !(await panel.hasClass(this._hiddenClass)); } /** Gets whether the tooltip is disabled */ async isDisabled(): Promise<boolean> { const host = await this.host(); return host.hasClass(this._disabledClass); } /** Gets a promise for the tooltip panel's text. */ async getTooltipText(): Promise<string> { const panel = await this._optionalPanel(); return panel ? panel.text() : ''; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2869, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/tooltip/testing/tooltip-harness.ts" }
components/src/material/tooltip/testing/tooltip-harness.spec.ts_0_2984
import {Component, provideZoneChangeDetection} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {MatTooltipModule} from '@angular/material/tooltip'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {MatTooltipHarness} from './tooltip-harness'; describe('MatTooltipHarness', () => { let fixture: ComponentFixture<TooltipHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ providers: [provideZoneChangeDetection()], }); }); beforeEach(() => { TestBed.configureTestingModule({ imports: [MatTooltipModule, NoopAnimationsModule, TooltipHarnessTest], }); fixture = TestBed.createComponent(TooltipHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should load all tooltip harnesses', async () => { const tooltips = await loader.getAllHarnesses(MatTooltipHarness); expect(tooltips.length).toBe(3); }); it('should be able to show a tooltip', async () => { const tooltip = await loader.getHarness(MatTooltipHarness.with({selector: '#one'})); expect(await tooltip.isOpen()).toBe(false); await tooltip.show(); expect(await tooltip.isOpen()).toBe(true); }); it('should be able to hide a tooltip', async () => { const tooltip = await loader.getHarness(MatTooltipHarness.with({selector: '#one'})); expect(await tooltip.isOpen()).toBe(false); await tooltip.show(); expect(await tooltip.isOpen()).toBe(true); await tooltip.hide(); expect(await tooltip.isOpen()).toBe(false); }); it('should be able to get the text of a tooltip', async () => { const tooltip = await loader.getHarness(MatTooltipHarness.with({selector: '#one'})); await tooltip.show(); expect(await tooltip.getTooltipText()).toBe('Tooltip message'); }); it('should return empty when getting the tooltip text while closed', async () => { const tooltip = await loader.getHarness(MatTooltipHarness.with({selector: '#one'})); expect(await tooltip.getTooltipText()).toBe(''); }); it('should get disabled state', async () => { const enabled = await loader.getHarness(MatTooltipHarness.with({selector: '#one'})); const disabled = await loader.getHarness(MatTooltipHarness.with({selector: '#three'})); expect(await enabled.isDisabled()).toBe(false); expect(await disabled.isDisabled()).toBe(true); }); }); @Component({ template: ` <button [matTooltip]='message' id='one'>Trigger 1</button> <button matTooltip='Static message' id='two'>Trigger 2</button> <button matTooltip='Disabled Tooltip' [matTooltipDisabled]='true' id='three'>Trigger 3</button> `, standalone: true, imports: [MatTooltipModule], }) class TooltipHarnessTest { message = 'Tooltip message'; }
{ "commit_id": "ea0d1ba7b", "end_byte": 2984, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/tooltip/testing/tooltip-harness.spec.ts" }
components/src/material/tooltip/testing/public-api.ts_0_282
/** * @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 */ export * from './tooltip-harness'; export * from './tooltip-harness-filters';
{ "commit_id": "ea0d1ba7b", "end_byte": 282, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/tooltip/testing/public-api.ts" }
components/src/material/tooltip/testing/BUILD.bazel_0_737
load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "testing", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src/cdk/testing", ], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), ) ng_test_library( name = "unit_tests_lib", srcs = glob(["**/*.spec.ts"]), deps = [ ":testing", "//src/cdk/testing", "//src/cdk/testing/testbed", "//src/material/tooltip", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":unit_tests_lib", ], )
{ "commit_id": "ea0d1ba7b", "end_byte": 737, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/tooltip/testing/BUILD.bazel" }
components/src/material/tooltip/testing/index.ts_0_234
/** * @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 */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/tooltip/testing/index.ts" }
components/src/material/sidenav/sidenav-module.ts_0_938
/** * @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 {CdkScrollableModule} from '@angular/cdk/scrolling'; import {NgModule} from '@angular/core'; import {MatCommonModule} from '@angular/material/core'; import {MatDrawer, MatDrawerContainer, MatDrawerContent} from './drawer'; import {MatSidenav, MatSidenavContainer, MatSidenavContent} from './sidenav'; @NgModule({ imports: [ MatCommonModule, CdkScrollableModule, MatDrawer, MatDrawerContainer, MatDrawerContent, MatSidenav, MatSidenavContainer, MatSidenavContent, ], exports: [ CdkScrollableModule, MatCommonModule, MatDrawer, MatDrawerContainer, MatDrawerContent, MatSidenav, MatSidenavContainer, MatSidenavContent, ], }) export class MatSidenavModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 938, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/sidenav-module.ts" }
components/src/material/sidenav/sidenav-container.html_0_355
@if (hasBackdrop) { <div class="mat-drawer-backdrop" (click)="_onBackdropClicked()" [class.mat-drawer-shown]="_isShowingBackdrop()"></div> } <ng-content select="mat-sidenav"></ng-content> <ng-content select="mat-sidenav-content"> </ng-content> @if (!_content) { <mat-sidenav-content> <ng-content></ng-content> </mat-sidenav-content> }
{ "commit_id": "ea0d1ba7b", "end_byte": 355, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/sidenav-container.html" }
components/src/material/sidenav/drawer-container.html_0_351
@if (hasBackdrop) { <div class="mat-drawer-backdrop" (click)="_onBackdropClicked()" [class.mat-drawer-shown]="_isShowingBackdrop()"></div> } <ng-content select="mat-drawer"></ng-content> <ng-content select="mat-drawer-content"> </ng-content> @if (!_content) { <mat-drawer-content> <ng-content></ng-content> </mat-drawer-content> }
{ "commit_id": "ea0d1ba7b", "end_byte": 351, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer-container.html" }
components/src/material/sidenav/drawer-animations.ts_0_1399
/** * @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, state, style, transition, trigger, AnimationTriggerMetadata, } from '@angular/animations'; /** * Animations used by the Material drawers. * @docs-private */ export const matDrawerAnimations: { readonly transformDrawer: AnimationTriggerMetadata; } = { /** Animation that slides a drawer in and out. */ transformDrawer: trigger('transform', [ // We remove the `transform` here completely, rather than setting it to zero, because: // 1. Having a transform can cause elements with ripples or an animated // transform to shift around in Chrome with an RTL layout (see #10023). // 2. 3d transforms causes text to appear blurry on IE and Edge. state( 'open, open-instant', style({ 'transform': 'none', 'visibility': 'visible', }), ), state( 'void', style({ // Avoids the shadow showing up when closed in SSR. 'box-shadow': 'none', 'visibility': 'hidden', }), ), transition('void => open-instant', animate('0ms')), transition( 'void <=> open, open-instant => void', animate('400ms cubic-bezier(0.25, 0.8, 0.25, 1)'), ), ]), };
{ "commit_id": "ea0d1ba7b", "end_byte": 1399, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer-animations.ts" }
components/src/material/sidenav/public-api.ts_0_530
/** * @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 */ export * from './sidenav-module'; export { throwMatDuplicatedDrawerError, MatDrawerToggleResult, MAT_DRAWER_DEFAULT_AUTOSIZE, MAT_DRAWER_DEFAULT_AUTOSIZE_FACTORY, MatDrawerContent, MatDrawer, MatDrawerContainer, MatDrawerMode, } from './drawer'; export * from './sidenav'; export * from './drawer-animations';
{ "commit_id": "ea0d1ba7b", "end_byte": 530, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/public-api.ts" }
components/src/material/sidenav/_sidenav-theme.scss_0_2623
@use 'sass:map'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/tokens/m2/mat/sidenav' as tokens-mat-sidenav; @use '../core/tokens/token-utils'; @use '../core/style/sass-utils'; @mixin base($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, base)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-sidenav.$prefix, tokens-mat-sidenav.get-unthemable-tokens() ); } } } @mixin color($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, color)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mat-sidenav.$prefix, tokens-mat-sidenav.get-color-tokens($theme) ); } } } @mixin typography($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, typography)); } @else { } } @mixin density($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, density)); } @else { } } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mat-sidenav.$prefix, tokens: tokens-mat-sidenav.get-token-slots(), ), ); } @mixin overrides($tokens: ()) { @include token-utils.batch-create-token-values($tokens, _define-overrides()...); } @mixin theme($theme) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-sidenav') { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme)); } @else { @include base($theme); @if inspection.theme-has($theme, color) { @include color($theme); } @if inspection.theme-has($theme, density) { @include density($theme); } @if inspection.theme-has($theme, typography) { @include typography($theme); } } } } @mixin _theme-from-tokens($tokens) { @include validation.selector-defined( 'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector' ); @if ($tokens != ()) { @include token-utils.create-token-values( tokens-mat-sidenav.$prefix, map.get($tokens, tokens-mat-sidenav.$prefix) ); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2623, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/_sidenav-theme.scss" }
components/src/material/sidenav/sidenav.spec.ts_0_4665
import {Component, ViewChild} from '@angular/core'; import {TestBed, fakeAsync, tick, waitForAsync} from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {MatSidenav, MatSidenavContainer, MatSidenavModule} from './index'; describe('MatSidenav', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MatSidenavModule, NoopAnimationsModule, SidenavWithFixedPosition, IndirectDescendantSidenav, NestedSidenavContainers, ], }); })); it('should be fixed position when in fixed mode', () => { const fixture = TestBed.createComponent(SidenavWithFixedPosition); fixture.detectChanges(); const sidenavEl = fixture.debugElement.query(By.directive(MatSidenav))!.nativeElement; expect(sidenavEl.classList).toContain('mat-sidenav-fixed'); fixture.componentInstance.fixed = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(sidenavEl.classList).not.toContain('mat-sidenav-fixed'); }); it('should set fixed bottom and top when in fixed mode', () => { const fixture = TestBed.createComponent(SidenavWithFixedPosition); fixture.detectChanges(); const sidenavEl = fixture.debugElement.query(By.directive(MatSidenav))!.nativeElement; expect(sidenavEl.style.top).toBe('20px'); expect(sidenavEl.style.bottom).toBe('30px'); fixture.componentInstance.fixed = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(sidenavEl.style.top).toBeFalsy(); expect(sidenavEl.style.bottom).toBeFalsy(); }); it('should pick up sidenavs that are not direct descendants', fakeAsync(() => { const fixture = TestBed.createComponent(IndirectDescendantSidenav); fixture.detectChanges(); expect(fixture.componentInstance.sidenav.opened).toBe(false); fixture.componentInstance.container.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(fixture.componentInstance.sidenav.opened).toBe(true); })); it('should not pick up sidenavs from nested containers', fakeAsync(() => { const fixture = TestBed.createComponent(NestedSidenavContainers); const instance = fixture.componentInstance; fixture.detectChanges(); expect(instance.outerSidenav.opened).toBe(false); expect(instance.innerSidenav.opened).toBe(false); instance.outerContainer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(instance.outerSidenav.opened).toBe(true); expect(instance.innerSidenav.opened).toBe(false); instance.innerContainer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(instance.outerSidenav.opened).toBe(true); expect(instance.innerSidenav.opened).toBe(true); })); }); @Component({ template: ` <mat-sidenav-container> <mat-sidenav #drawer [fixedInViewport]="fixed" [fixedTopGap]="fixedTop" [fixedBottomGap]="fixedBottom"> Drawer. </mat-sidenav> <mat-sidenav-content> Some content. </mat-sidenav-content> </mat-sidenav-container>`, standalone: true, imports: [MatSidenavModule], }) class SidenavWithFixedPosition { fixed = true; fixedTop = 20; fixedBottom = 30; } @Component({ // Note that we need the `@if` so that there's an embedded // view between the container and the sidenav. template: ` <mat-sidenav-container #container> @if (true) { <mat-sidenav #sidenav>Sidenav.</mat-sidenav> } <mat-sidenav-content>Some content.</mat-sidenav-content> </mat-sidenav-container>`, standalone: true, imports: [MatSidenavModule], }) class IndirectDescendantSidenav { @ViewChild('container') container: MatSidenavContainer; @ViewChild('sidenav') sidenav: MatSidenav; } @Component({ template: ` <mat-sidenav-container #outerContainer> <mat-sidenav #outerSidenav>Sidenav</mat-sidenav> <mat-sidenav-content> <mat-sidenav-container #innerContainer> <mat-sidenav #innerSidenav>Sidenav</mat-sidenav> </mat-sidenav-container> </mat-sidenav-content> </mat-sidenav-container> `, standalone: true, imports: [MatSidenavModule], }) class NestedSidenavContainers { @ViewChild('outerContainer') outerContainer: MatSidenavContainer; @ViewChild('outerSidenav') outerSidenav: MatSidenav; @ViewChild('innerContainer') innerContainer: MatSidenavContainer; @ViewChild('innerSidenav') innerSidenav: MatSidenav; }
{ "commit_id": "ea0d1ba7b", "end_byte": 4665, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/sidenav.spec.ts" }
components/src/material/sidenav/README.md_0_98
Please see the official documentation at https://material.angular.io/components/component/sidenav
{ "commit_id": "ea0d1ba7b", "end_byte": 98, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/README.md" }
components/src/material/sidenav/drawer.spec.ts_0_1287
import {A11yModule} from '@angular/cdk/a11y'; import {Direction} from '@angular/cdk/bidi'; import {ESCAPE} from '@angular/cdk/keycodes'; import {CdkScrollable} from '@angular/cdk/scrolling'; import { createKeyboardEvent, dispatchEvent, dispatchKeyboardEvent, } from '@angular/cdk/testing/private'; import {Component, ElementRef, ErrorHandler, ViewChild} from '@angular/core'; import { ComponentFixture, TestBed, discardPeriodicTasks, fakeAsync, flush, tick, waitForAsync, } from '@angular/core/testing'; import {By} from '@angular/platform-browser'; import {BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations'; import {MatDrawer, MatDrawerContainer, MatSidenavModule} from './index'; describe('MatDrawer', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MatSidenavModule, A11yModule, NoopAnimationsModule, BasicTestApp, DrawerContainerNoDrawerTestApp, DrawerSetToOpenedFalse, DrawerSetToOpenedTrue, DrawerDynamicPosition, DrawerWithFocusableElements, DrawerOpenBinding, DrawerWithoutFocusableElements, IndirectDescendantDrawer, NestedDrawerContainers, ], }); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 1287, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.spec.ts" }
components/src/material/sidenav/drawer.spec.ts_1291_11298
describe('methods', () => { it('should be able to open', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const testComponent: BasicTestApp = fixture.debugElement.componentInstance; const container = fixture.debugElement.query(By.css('mat-drawer-container'))!.nativeElement; fixture.debugElement.query(By.css('.open'))!.nativeElement.click(); fixture.detectChanges(); expect(testComponent.openCount).toBe(0); expect(testComponent.openStartCount).toBe(0); expect(container.classList).not.toContain('mat-drawer-container-has-open'); tick(); expect(testComponent.openStartCount).toBe(1); fixture.detectChanges(); expect(testComponent.openCount).toBe(1); expect(testComponent.openStartCount).toBe(1); expect(container.classList).toContain('mat-drawer-container-has-open'); })); it('should be able to close', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const testComponent: BasicTestApp = fixture.debugElement.componentInstance; const container = fixture.debugElement.query(By.css('mat-drawer-container'))!.nativeElement; fixture.debugElement.query(By.css('.open'))!.nativeElement.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); fixture.debugElement.query(By.css('.close'))!.nativeElement.click(); fixture.detectChanges(); expect(testComponent.closeCount).toBe(0); expect(testComponent.closeStartCount).toBe(0); expect(container.classList).toContain('mat-drawer-container-has-open'); flush(); expect(testComponent.closeStartCount).toBe(1); fixture.detectChanges(); expect(testComponent.closeCount).toBe(1); expect(testComponent.closeStartCount).toBe(1); expect(container.classList).not.toContain('mat-drawer-container-has-open'); })); it('should resolve the open method promise with the new state of the drawer', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const drawer: MatDrawer = fixture.debugElement.query( By.directive(MatDrawer), )!.componentInstance; drawer.open().then(result => expect(result).toBe('open')); fixture.detectChanges(); tick(); fixture.detectChanges(); })); it('should resolve the close method promise with the new state of the drawer', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const drawer = fixture.debugElement.query(By.directive(MatDrawer))!; const drawerInstance: MatDrawer = drawer.componentInstance; drawerInstance.open(); fixture.detectChanges(); flush(); fixture.detectChanges(); drawerInstance.close().then(result => expect(result).toBe('close')); fixture.detectChanges(); flush(); fixture.detectChanges(); })); it('should be able to close while the open animation is running', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const testComponent: BasicTestApp = fixture.debugElement.componentInstance; fixture.debugElement.query(By.css('.open'))!.nativeElement.click(); fixture.detectChanges(); expect(testComponent.openCount).toBe(0); expect(testComponent.closeCount).toBe(0); tick(); fixture.debugElement.query(By.css('.close'))!.nativeElement.click(); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(testComponent.openCount).toBe(1); expect(testComponent.closeCount).toBe(1); })); it('does not throw when created without a drawer', fakeAsync(() => { expect(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); tick(); }).not.toThrow(); })); it('should emit the backdropClick event when the backdrop is clicked', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const testComponent: BasicTestApp = fixture.debugElement.componentInstance; const openButtonElement = fixture.debugElement.query(By.css('.open'))!.nativeElement; openButtonElement.click(); fixture.detectChanges(); flush(); expect(testComponent.backdropClickedCount).toBe(0); fixture.debugElement.query(By.css('.mat-drawer-backdrop'))!.nativeElement.click(); fixture.detectChanges(); flush(); expect(testComponent.backdropClickedCount).toBe(1); openButtonElement.click(); fixture.detectChanges(); flush(); fixture.debugElement.query(By.css('.close'))!.nativeElement.click(); fixture.detectChanges(); flush(); expect(testComponent.backdropClickedCount).toBe(1); })); it('should close when pressing escape', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const testComponent: BasicTestApp = fixture.debugElement.componentInstance; const drawer = fixture.debugElement.query(By.directive(MatDrawer))!; drawer.componentInstance.open(); fixture.detectChanges(); tick(); expect(testComponent.openCount).withContext('Expected one open event.').toBe(1); expect(testComponent.openStartCount).withContext('Expected one open start event.').toBe(1); expect(testComponent.closeCount).withContext('Expected no close events.').toBe(0); expect(testComponent.closeStartCount).withContext('Expected no close start events.').toBe(0); const event = dispatchKeyboardEvent(drawer.nativeElement, 'keydown', ESCAPE); fixture.detectChanges(); flush(); expect(testComponent.closeCount).withContext('Expected one close event.').toBe(1); expect(testComponent.closeStartCount).withContext('Expected one close start event.').toBe(1); expect(event.defaultPrevented).toBe(true); })); it('should not close when pressing escape with a modifier', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const testComponent: BasicTestApp = fixture.debugElement.componentInstance; const drawer = fixture.debugElement.query(By.directive(MatDrawer))!; drawer.componentInstance.open(); fixture.detectChanges(); tick(); expect(testComponent.closeCount).withContext('Expected no close events.').toBe(0); expect(testComponent.closeStartCount).withContext('Expected no close start events.').toBe(0); const event = createKeyboardEvent('keydown', ESCAPE, undefined, {alt: true}); dispatchEvent(drawer.nativeElement, event); fixture.detectChanges(); flush(); expect(testComponent.closeCount).withContext('Expected still no close events.').toBe(0); expect(testComponent.closeStartCount) .withContext('Expected still no close start events.') .toBe(0); expect(event.defaultPrevented).toBe(false); })); it('should fire the open event when open on init', fakeAsync(() => { const fixture = TestBed.createComponent(DrawerSetToOpenedTrue); fixture.detectChanges(); tick(); expect(fixture.componentInstance.openCallback).toHaveBeenCalledTimes(1); })); it('should not close by pressing escape when disableClose is set', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); const testComponent = fixture.debugElement.componentInstance; const drawer = fixture.debugElement.query(By.directive(MatDrawer))!; drawer.componentInstance.disableClose = true; fixture.changeDetectorRef.markForCheck(); drawer.componentInstance.open(); fixture.detectChanges(); tick(); dispatchKeyboardEvent(drawer.nativeElement, 'keydown', ESCAPE); fixture.detectChanges(); tick(); expect(testComponent.closeCount).toBe(0); expect(testComponent.closeStartCount).toBe(0); })); it('should not close by clicking on the backdrop when disableClose is set', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); const testComponent = fixture.debugElement.componentInstance; const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; drawer.disableClose = true; drawer.open(); fixture.detectChanges(); tick(); fixture.debugElement.query(By.css('.mat-drawer-backdrop'))!.nativeElement.click(); fixture.detectChanges(); tick(); expect(testComponent.closeCount).toBe(0); expect(testComponent.closeStartCount).toBe(0); })); it('should restore focus on close if backdrop has been clicked', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; const openButton = fixture.componentInstance.openButton.nativeElement; openButton.focus(); drawer.open(); fixture.detectChanges(); flush(); fixture.detectChanges(); const backdrop = fixture.nativeElement.querySelector('.mat-drawer-backdrop'); expect(backdrop).toBeTruthy(); // Ensure the element that has been focused on drawer open is blurred. This simulates // the behavior where clicks on the backdrop blur the active element. if (document.activeElement !== null && document.activeElement instanceof HTMLElement) { document.activeElement.blur(); } backdrop.click(); fixture.detectChanges(); flush(); expect(document.activeElement) .withContext('Expected focus to be restored to the open button on close.') .toBe(openButton); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 11298, "start_byte": 1291, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.spec.ts" }
components/src/material/sidenav/drawer.spec.ts_11304_18693
it('should restore focus on close if focus is on drawer', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; const openButton = fixture.componentInstance.openButton.nativeElement; const drawerButton = fixture.componentInstance.drawerButton.nativeElement; openButton.focus(); drawer.open(); fixture.detectChanges(); flush(); fixture.detectChanges(); drawerButton.focus(); drawer.close(); fixture.detectChanges(); flush(); expect(document.activeElement) .withContext('Expected focus to be restored to the open button on close.') .toBe(openButton); })); it('should restore focus to an SVG element', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; const svg = fixture.componentInstance.svg.nativeElement; const drawerButton = fixture.componentInstance.drawerButton.nativeElement; svg.focus(); drawer.open(); fixture.detectChanges(); flush(); fixture.detectChanges(); drawerButton.focus(); drawer.close(); fixture.detectChanges(); flush(); expect(document.activeElement) .withContext('Expected focus to be restored to the SVG element on close.') .toBe(svg); })); it('should not restore focus on close if focus is outside drawer', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); const drawer: MatDrawer = fixture.debugElement.query( By.directive(MatDrawer), )!.componentInstance; fixture.detectChanges(); const openButton = fixture.componentInstance.openButton.nativeElement; const closeButton = fixture.componentInstance.closeButton.nativeElement; openButton.focus(); drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); closeButton.focus(); drawer.close(); fixture.detectChanges(); tick(); expect(document.activeElement) .withContext('Expected focus not to be restored to the open button on close.') .toBe(closeButton); })); it('should pick up drawers that are not direct descendants', fakeAsync(() => { const fixture = TestBed.createComponent(IndirectDescendantDrawer); fixture.detectChanges(); expect(fixture.componentInstance.drawer.opened).toBe(false); fixture.componentInstance.container.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(fixture.componentInstance.drawer.opened).toBe(true); })); it('should not pick up drawers from nested containers', fakeAsync(() => { const fixture = TestBed.createComponent(NestedDrawerContainers); const instance = fixture.componentInstance; fixture.detectChanges(); expect(instance.outerDrawer.opened).toBe(false); expect(instance.innerDrawer.opened).toBe(false); instance.outerContainer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(instance.outerDrawer.opened).toBe(true); expect(instance.innerDrawer.opened).toBe(false); instance.innerContainer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(instance.outerDrawer.opened).toBe(true); expect(instance.innerDrawer.opened).toBe(true); })); }); describe('attributes', () => { it('should correctly parse opened="false"', () => { const fixture = TestBed.createComponent(DrawerSetToOpenedFalse); fixture.detectChanges(); const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; expect((drawer as MatDrawer).opened).toBe(false); }); it('should correctly parse opened="true"', () => { const fixture = TestBed.createComponent(DrawerSetToOpenedTrue); fixture.detectChanges(); const drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; expect((drawer as MatDrawer).opened).toBe(true); }); it('should remove align attr from DOM', () => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const drawerEl = fixture.debugElement.query(By.css('mat-drawer'))!.nativeElement; expect(drawerEl.hasAttribute('align')) .withContext('Expected drawer not to have a native align attribute.') .toBe(false); }); it('should throw when multiple drawers have the same position', fakeAsync(() => { const errorHandler = jasmine.createSpyObj(['handleError']); TestBed.configureTestingModule({ imports: [DrawerDynamicPosition], providers: [ { provide: ErrorHandler, useValue: errorHandler, }, ], }); const fixture = TestBed.createComponent(DrawerDynamicPosition); fixture.detectChanges(); tick(); const testComponent: DrawerDynamicPosition = fixture.debugElement.componentInstance; testComponent.drawer1Position = 'end'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); expect(errorHandler.handleError).toHaveBeenCalled(); })); it('should not throw when drawers swap positions', () => { const fixture = TestBed.createComponent(DrawerDynamicPosition); fixture.detectChanges(); const testComponent: DrawerDynamicPosition = fixture.debugElement.componentInstance; testComponent.drawer1Position = 'end'; testComponent.drawer2Position = 'start'; fixture.changeDetectorRef.markForCheck(); expect(() => fixture.detectChanges()).not.toThrow(); }); it('should bind 2-way bind on opened property', fakeAsync(() => { const fixture = TestBed.createComponent(DrawerOpenBinding); fixture.detectChanges(); const drawer: MatDrawer = fixture.debugElement.query( By.directive(MatDrawer), )!.componentInstance; drawer.open(); fixture.detectChanges(); tick(); expect(fixture.componentInstance.isOpen).toBe(true); })); it('should not throw when a two-way binding is toggled quickly while animating', fakeAsync(() => { TestBed.resetTestingModule().configureTestingModule({ imports: [MatSidenavModule, BrowserAnimationsModule, DrawerOpenBinding], }); const fixture = TestBed.createComponent(DrawerOpenBinding); fixture.detectChanges(); // Note that we need actual timeouts and the `BrowserAnimationsModule` // in order to test it correctly. setTimeout(() => { fixture.componentInstance.isOpen = !fixture.componentInstance.isOpen; fixture.changeDetectorRef.markForCheck(); expect(() => fixture.detectChanges()).not.toThrow(); setTimeout(() => { fixture.componentInstance.isOpen = !fixture.componentInstance.isOpen; fixture.changeDetectorRef.markForCheck(); expect(() => fixture.detectChanges()).not.toThrow(); }, 1); tick(1); }, 1); tick(1); })); });
{ "commit_id": "ea0d1ba7b", "end_byte": 18693, "start_byte": 11304, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.spec.ts" }
components/src/material/sidenav/drawer.spec.ts_18697_25294
describe('focus trapping behavior', () => { let fixture: ComponentFixture<DrawerWithFocusableElements>; let testComponent: DrawerWithFocusableElements; let drawer: MatDrawer; let firstFocusableElement: HTMLElement; let lastFocusableElement: HTMLElement; beforeEach(() => { fixture = TestBed.createComponent(DrawerWithFocusableElements); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; drawer = fixture.debugElement.query(By.directive(MatDrawer))!.componentInstance; firstFocusableElement = fixture.debugElement.query(By.css('.input1'))!.nativeElement; lastFocusableElement = fixture.debugElement.query(By.css('.input2'))!.nativeElement; lastFocusableElement.focus(); }); it('should trap focus when opened in "over" mode', fakeAsync(() => { testComponent.mode = 'over'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); lastFocusableElement.focus(); drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(document.activeElement).toBe(firstFocusableElement); })); it('should trap focus when opened in "push" mode', fakeAsync(() => { testComponent.mode = 'push'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); lastFocusableElement.focus(); drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(document.activeElement).toBe(firstFocusableElement); })); it('should trap focus when opened in "side" mode if backdrop is explicitly enabled', fakeAsync(() => { testComponent.mode = 'push'; testComponent.hasBackdrop = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); lastFocusableElement.focus(); drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(document.activeElement).toBe(firstFocusableElement); })); it('should not auto-focus by default when opened in "side" mode', fakeAsync(() => { testComponent.mode = 'side'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); lastFocusableElement.focus(); drawer.open(); fixture.detectChanges(); tick(); expect(document.activeElement).toBe(lastFocusableElement); })); it( 'should auto-focus to first tabbable element when opened in "side" mode' + 'when enabled explicitly', fakeAsync(() => { drawer.autoFocus = 'first-tabbable'; testComponent.mode = 'side'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); lastFocusableElement.focus(); drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(document.activeElement).toBe(firstFocusableElement); }), ); it( 'should auto-focus to first tabbable element when opened in "push" mode' + 'when backdrop is enabled explicitly', fakeAsync(() => { testComponent.mode = 'push'; testComponent.hasBackdrop = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); lastFocusableElement.focus(); drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(document.activeElement).toBe(firstFocusableElement); }), ); it('should focus the drawer if there are no focusable elements', fakeAsync(() => { fixture.destroy(); const nonFocusableFixture = TestBed.createComponent(DrawerWithoutFocusableElements); const drawerEl = nonFocusableFixture.debugElement.query(By.directive(MatDrawer))!; nonFocusableFixture.detectChanges(); drawerEl.componentInstance.open(); nonFocusableFixture.detectChanges(); tick(); nonFocusableFixture.detectChanges(); expect(document.activeElement).toBe(drawerEl.nativeElement); })); it('should be able to disable auto focus', fakeAsync(() => { drawer.autoFocus = 'dialog'; testComponent.mode = 'push'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); lastFocusableElement.focus(); drawer.open(); fixture.detectChanges(); tick(); expect(document.activeElement).not.toBe(firstFocusableElement); })); it('should update the focus trap enable state if the mode changes while open', fakeAsync(() => { testComponent.mode = 'side'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); drawer.open(); fixture.detectChanges(); tick(); const anchors = Array.from<HTMLElement>( fixture.nativeElement.querySelectorAll('.cdk-focus-trap-anchor'), ); expect(anchors.every(anchor => !anchor.hasAttribute('tabindex'))) .withContext('Expected focus trap anchors to be disabled in side mode.') .toBe(true); testComponent.mode = 'over'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(anchors.every(anchor => anchor.getAttribute('tabindex') === '0')) .withContext('Expected focus trap anchors to be enabled in over mode.') .toBe(true); })); it('should disable the focus trap while closed', fakeAsync(() => { testComponent.mode = 'over'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); flush(); const anchors = Array.from<HTMLElement>( fixture.nativeElement.querySelectorAll('.cdk-focus-trap-anchor'), ); expect(anchors.map(anchor => anchor.getAttribute('tabindex'))).toEqual([null, null]); drawer.open(); fixture.detectChanges(); flush(); expect(anchors.map(anchor => anchor.getAttribute('tabindex'))).toEqual(['0', '0']); drawer.close(); fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); flush(); expect(anchors.map(anchor => anchor.getAttribute('tabindex'))).toEqual([null, null]); })); }); it('should mark the drawer content as scrollable', () => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); const content = fixture.debugElement.query(By.css('.mat-drawer-inner-container')); const scrollable = content.injector.get(CdkScrollable); expect(scrollable).toBeTruthy(); expect(scrollable.getElementRef().nativeElement).toBe(content.nativeElement); });
{ "commit_id": "ea0d1ba7b", "end_byte": 25294, "start_byte": 18697, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.spec.ts" }
components/src/material/sidenav/drawer.spec.ts_25298_31073
describe('DOM position', () => { it('should project start drawer before the content', () => { const fixture = TestBed.createComponent(BasicTestApp); fixture.componentInstance.position = 'start'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const allNodes = getDrawerNodesArray(fixture); const drawerIndex = allNodes.indexOf(fixture.nativeElement.querySelector('.mat-drawer')); const contentIndex = allNodes.indexOf( fixture.nativeElement.querySelector('.mat-drawer-content'), ); expect(drawerIndex) .withContext('Expected drawer to be inside the container') .toBeGreaterThan(-1); expect(contentIndex) .withContext('Expected content to be inside the container') .toBeGreaterThan(-1); expect(drawerIndex) .withContext('Expected drawer to be before the content') .toBeLessThan(contentIndex); }); it('should project end drawer after the content', () => { const fixture = TestBed.createComponent(BasicTestApp); fixture.componentInstance.position = 'end'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const allNodes = getDrawerNodesArray(fixture); const drawerIndex = allNodes.indexOf(fixture.nativeElement.querySelector('.mat-drawer')); const contentIndex = allNodes.indexOf( fixture.nativeElement.querySelector('.mat-drawer-content'), ); expect(drawerIndex) .withContext('Expected drawer to be inside the container') .toBeGreaterThan(-1); expect(contentIndex) .withContext('Expected content to be inside the container') .toBeGreaterThan(-1); expect(drawerIndex) .withContext('Expected drawer to be after the content') .toBeGreaterThan(contentIndex); }); it( 'should move the drawer before/after the content when its position changes after being ' + 'initialized at `start`', () => { const fixture = TestBed.createComponent(BasicTestApp); fixture.componentInstance.position = 'start'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const drawer = fixture.nativeElement.querySelector('.mat-drawer'); const content = fixture.nativeElement.querySelector('.mat-drawer-content'); let allNodes = getDrawerNodesArray(fixture); const startDrawerIndex = allNodes.indexOf(drawer); const startContentIndex = allNodes.indexOf(content); expect(startDrawerIndex) .withContext('Expected drawer to be inside the container') .toBeGreaterThan(-1); expect(startContentIndex) .withContext('Expected content to be inside the container') .toBeGreaterThan(-1); expect(startDrawerIndex) .withContext('Expected drawer to be before the content on init') .toBeLessThan(startContentIndex); fixture.componentInstance.position = 'end'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); allNodes = getDrawerNodesArray(fixture); expect(allNodes.indexOf(drawer)) .withContext('Expected drawer to be after content when position changes to `end`') .toBeGreaterThan(allNodes.indexOf(content)); fixture.componentInstance.position = 'start'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); allNodes = getDrawerNodesArray(fixture); expect(allNodes.indexOf(drawer)) .withContext('Expected drawer to be before content when position changes back to `start`') .toBeLessThan(allNodes.indexOf(content)); }, ); it( 'should move the drawer before/after the content when its position changes after being ' + 'initialized at `end`', () => { const fixture = TestBed.createComponent(BasicTestApp); fixture.componentInstance.position = 'end'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const drawer = fixture.nativeElement.querySelector('.mat-drawer'); const content = fixture.nativeElement.querySelector('.mat-drawer-content'); let allNodes = getDrawerNodesArray(fixture); const startDrawerIndex = allNodes.indexOf(drawer); const startContentIndex = allNodes.indexOf(content); expect(startDrawerIndex).toBeGreaterThan(-1, 'Expected drawer to be inside the container'); expect(startContentIndex).toBeGreaterThan( -1, 'Expected content to be inside the container', ); expect(startDrawerIndex).toBeGreaterThan( startContentIndex, 'Expected drawer to be after the content on init', ); fixture.componentInstance.position = 'start'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); allNodes = getDrawerNodesArray(fixture); expect(allNodes.indexOf(drawer)).toBeLessThan( allNodes.indexOf(content), 'Expected drawer to be before content when position changes to `start`', ); fixture.componentInstance.position = 'end'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); allNodes = getDrawerNodesArray(fixture); expect(allNodes.indexOf(drawer)).toBeGreaterThan( allNodes.indexOf(content), 'Expected drawer to be after content when position changes back to `end`', ); }, ); function getDrawerNodesArray(fixture: ComponentFixture<any>): HTMLElement[] { return Array.from(fixture.nativeElement.querySelector('.mat-drawer-container').childNodes); } }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 31073, "start_byte": 25298, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.spec.ts" }
components/src/material/sidenav/drawer.spec.ts_31075_41740
describe('MatDrawerContainer', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MatSidenavModule, A11yModule, NoopAnimationsModule, DrawerContainerTwoDrawerTestApp, DrawerDelayed, DrawerSetToOpenedTrue, DrawerContainerStateChangesTestApp, AutosizeDrawer, BasicTestApp, DrawerContainerWithContent, ], }); })); it('should be able to open and close all drawers', fakeAsync(() => { const fixture = TestBed.createComponent(DrawerContainerTwoDrawerTestApp); fixture.detectChanges(); const testComponent: DrawerContainerTwoDrawerTestApp = fixture.debugElement.componentInstance; const drawers = fixture.debugElement.queryAll(By.directive(MatDrawer)); expect(drawers.every(drawer => drawer.componentInstance.opened)).toBe(false); testComponent.drawerContainer.open(); fixture.detectChanges(); tick(); expect(drawers.every(drawer => drawer.componentInstance.opened)).toBe(true); testComponent.drawerContainer.close(); fixture.detectChanges(); flush(); expect(drawers.every(drawer => drawer.componentInstance.opened)).toBe(false); })); it('should animate the content when a drawer is added at a later point', fakeAsync(() => { const fixture = TestBed.createComponent(DrawerDelayed); fixture.detectChanges(); const contentElement = fixture.debugElement.nativeElement.querySelector('.mat-drawer-content'); expect(parseInt(contentElement.style.marginLeft)).toBeFalsy(); fixture.componentInstance.showDrawer = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(parseInt(contentElement.style.marginLeft)).toBeGreaterThan(0); })); it('should recalculate the margin if a drawer is destroyed', fakeAsync(() => { const fixture = TestBed.createComponent(DrawerContainerStateChangesTestApp); fixture.detectChanges(); fixture.componentInstance.drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); const contentElement = fixture.debugElement.nativeElement.querySelector('.mat-drawer-content'); const initialMargin = parseInt(contentElement.style.marginLeft); expect(initialMargin).toBeGreaterThan(0); fixture.componentInstance.renderDrawer = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); expect(contentElement.style.marginLeft).toBe(''); })); it('should recalculate the margin if the drawer mode is changed', fakeAsync(() => { const fixture = TestBed.createComponent(DrawerContainerStateChangesTestApp); fixture.detectChanges(); fixture.componentInstance.drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); const contentElement = fixture.debugElement.nativeElement.querySelector('.mat-drawer-content'); const initialMargin = parseInt(contentElement.style.marginLeft); expect(initialMargin).toBeGreaterThan(0); fixture.componentInstance.mode = 'over'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(contentElement.style.marginLeft).toBe(''); })); it('should recalculate the margin if the direction has changed', fakeAsync(() => { const fixture = TestBed.createComponent(DrawerContainerStateChangesTestApp); fixture.detectChanges(); fixture.componentInstance.drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); const contentElement = fixture.debugElement.nativeElement.querySelector('.mat-drawer-content'); const margin = parseInt(contentElement.style.marginLeft); expect(margin).toBeGreaterThan(0); fixture.componentInstance.direction = 'rtl'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(contentElement.style.marginLeft).toBe(''); expect(parseInt(contentElement.style.marginRight)).toBe(margin); })); it('should not animate when the sidenav is open on load', fakeAsync(() => { TestBed.resetTestingModule().configureTestingModule({ imports: [MatSidenavModule, BrowserAnimationsModule, DrawerSetToOpenedTrue], }); const fixture = TestBed.createComponent(DrawerSetToOpenedTrue); fixture.detectChanges(); tick(); const container = fixture.debugElement.nativeElement.querySelector('.mat-drawer-container'); expect(container.classList).not.toContain('mat-drawer-transition'); })); it('should recalculate the margin if a drawer changes size while open in autosize mode', fakeAsync(() => { const fixture = TestBed.createComponent(AutosizeDrawer); fixture.detectChanges(); // In M3 the drawer has a fixed default width. fixture.nativeElement.querySelector('.mat-drawer').style.width = 'auto'; fixture.componentInstance.drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); const contentEl = fixture.debugElement.nativeElement.querySelector('.mat-drawer-content'); const initialMargin = parseInt(contentEl.style.marginLeft); expect(initialMargin).toBeGreaterThan(0); fixture.componentInstance.fillerWidth = 200; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(10); fixture.detectChanges(); expect(parseInt(contentEl.style.marginLeft)).toBeGreaterThan(initialMargin); discardPeriodicTasks(); })); it('should not set a style property if it would be zero', fakeAsync(() => { const fixture = TestBed.createComponent(AutosizeDrawer); fixture.detectChanges(); const content = fixture.debugElement.nativeElement.querySelector('.mat-drawer-content'); expect(content.style.marginLeft) .withContext('Margin should be omitted when drawer is closed') .toBe(''); // Open the drawer and resolve the open animation. fixture.componentInstance.drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(content.style.marginLeft).not.toBe('', 'Margin should be present when drawer is open'); // Close the drawer and resolve the close animation. fixture.componentInstance.drawer.close(); fixture.detectChanges(); flush(); fixture.detectChanges(); expect(content.style.marginLeft) .withContext('Margin should be removed after drawer close.') .toBe(''); discardPeriodicTasks(); })); it('should be able to toggle whether the container has a backdrop', () => { const fixture = TestBed.createComponent(BasicTestApp); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('.mat-drawer-backdrop')).toBeTruthy(); fixture.componentInstance.hasBackdrop = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('.mat-drawer-backdrop')).toBeFalsy(); }); it('should be able to explicitly enable the backdrop in `side` mode', fakeAsync(() => { const fixture = TestBed.createComponent(BasicTestApp); const root = fixture.nativeElement; fixture.detectChanges(); fixture.componentInstance.drawer.mode = 'side'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); fixture.componentInstance.drawer.open(); fixture.detectChanges(); tick(); fixture.detectChanges(); let backdrop = root.querySelector('.mat-drawer-backdrop.mat-drawer-shown'); expect(backdrop).toBeFalsy(); fixture.componentInstance.hasBackdrop = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); backdrop = root.querySelector('.mat-drawer-backdrop.mat-drawer-shown'); expect(backdrop).toBeTruthy(); expect(fixture.componentInstance.drawer.opened).toBe(true); backdrop.click(); fixture.detectChanges(); tick(); expect(fixture.componentInstance.drawer.opened).toBe(false); })); it('should expose a scrollable when the consumer has not specified drawer content', () => { const fixture = TestBed.createComponent(DrawerContainerTwoDrawerTestApp); fixture.detectChanges(); expect(fixture.componentInstance.drawerContainer.scrollable instanceof CdkScrollable).toBe( true, ); }); it('should expose a scrollable when the consumer has specified drawer content', () => { const fixture = TestBed.createComponent(DrawerContainerWithContent); fixture.detectChanges(); expect(fixture.componentInstance.drawerContainer.scrollable instanceof CdkScrollable).toBe( true, ); }); it('should clean up the drawers stream on destroy', () => { const fixture = TestBed.createComponent(DrawerContainerTwoDrawerTestApp); fixture.detectChanges(); const spy = jasmine.createSpy('complete spy'); const subscription = fixture.componentInstance.drawerContainer._drawers.changes.subscribe({ complete: spy, }); fixture.destroy(); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); it('should position the drawers before/after the content in the DOM based on their position', () => { const fixture = TestBed.createComponent(DrawerContainerTwoDrawerTestApp); fixture.detectChanges(); const drawerDebugElements = fixture.debugElement.queryAll(By.directive(MatDrawer)); const [start, end] = drawerDebugElements.map(el => el.componentInstance); const [startNode, endNode] = drawerDebugElements.map(el => el.nativeElement); const contentNode = fixture.nativeElement.querySelector('.mat-drawer-content'); const allNodes: HTMLElement[] = Array.from( fixture.nativeElement.querySelector('.mat-drawer-container').childNodes, ); const startIndex = allNodes.indexOf(startNode); const endIndex = allNodes.indexOf(endNode); const contentIndex = allNodes.indexOf(contentNode); expect(start.position).toBe('start'); expect(end.position).toBe('end'); expect(contentIndex) .withContext('Expected content to be inside the container') .toBeGreaterThan(-1); expect(startIndex) .withContext('Expected start drawer to be inside the container') .toBeGreaterThan(-1); expect(endIndex) .withContext('Expected end drawer to be inside the container') .toBeGreaterThan(-1); expect(startIndex) .withContext('Expected start drawer to be before content') .toBeLessThan(contentIndex); expect(endIndex) .withContext('Expected end drawer to be after content') .toBeGreaterThan(contentIndex); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 41740, "start_byte": 31075, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.spec.ts" }
components/src/material/sidenav/drawer.spec.ts_41742_49158
/** Test component that contains an MatDrawerContainer but no MatDrawer. */ @Component({ template: `<mat-drawer-container></mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerContainerNoDrawerTestApp {} /** Test component that contains an MatDrawerContainer and 2 MatDrawer in the same position. */ @Component({ template: ` <mat-drawer-container> <mat-drawer position="start"></mat-drawer> <mat-drawer position="end"></mat-drawer> </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerContainerTwoDrawerTestApp { @ViewChild(MatDrawerContainer) drawerContainer: MatDrawerContainer; } /** Test component that contains an MatDrawerContainer and one MatDrawer. */ @Component({ template: ` <mat-drawer-container (backdropClick)="backdropClicked()" [hasBackdrop]="hasBackdrop"> <mat-drawer #drawer="matDrawer" [position]="position" (opened)="open()" (openedStart)="openStart()" (closed)="close()" (closedStart)="closeStart()"> <button #drawerButton>Content</button> </mat-drawer> <button (click)="drawer.open()" class="open" #openButton></button> <button (click)="drawer.close()" class="close" #closeButton></button> <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" tabindex="0" focusable="true" #svg> <circle cx="50" cy="50" r="50"/> </svg> </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class BasicTestApp { openCount = 0; openStartCount = 0; closeCount = 0; closeStartCount = 0; backdropClickedCount = 0; hasBackdrop: boolean | null = null; position = 'start'; @ViewChild('drawer') drawer: MatDrawer; @ViewChild('drawerButton') drawerButton: ElementRef<HTMLButtonElement>; @ViewChild('openButton') openButton: ElementRef<HTMLButtonElement>; @ViewChild('svg') svg: ElementRef<SVGElement>; @ViewChild('closeButton') closeButton: ElementRef<HTMLButtonElement>; open() { this.openCount++; } openStart() { this.openStartCount++; } close() { this.closeCount++; } closeStart() { this.closeStartCount++; } backdropClicked() { this.backdropClickedCount++; } } @Component({ template: ` <mat-drawer-container> <mat-drawer #drawer mode="side" opened="false"> Closed Drawer. </mat-drawer> </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerSetToOpenedFalse {} @Component({ template: ` <mat-drawer-container> <mat-drawer #drawer mode="side" opened="true" (opened)="openCallback()"> Closed Drawer. </mat-drawer> </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerSetToOpenedTrue { openCallback = jasmine.createSpy('open callback'); } @Component({ template: ` <mat-drawer-container> <mat-drawer #drawer mode="side" [(opened)]="isOpen"> Closed Drawer. </mat-drawer> </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerOpenBinding { isOpen = false; } @Component({ template: ` <mat-drawer-container> <mat-drawer #drawer1 [position]="drawer1Position"></mat-drawer> <mat-drawer #drawer2 [position]="drawer2Position"></mat-drawer> </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerDynamicPosition { drawer1Position = 'start'; drawer2Position = 'end'; } @Component({ // Note: we use inputs here, because they're guaranteed // to be focusable across all platforms. template: ` <mat-drawer-container [hasBackdrop]="hasBackdrop"> <mat-drawer position="start" [mode]="mode"> <input type="text" class="input1"/> </mat-drawer> <input type="text" class="input2"/> </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerWithFocusableElements { mode: string = 'over'; hasBackdrop: boolean | null = null; } @Component({ template: ` <mat-drawer-container> <mat-drawer position="start" mode="over"> <button disabled>Not focusable</button> </mat-drawer> </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerWithoutFocusableElements {} @Component({ template: ` <mat-drawer-container> @if (showDrawer) { <mat-drawer #drawer mode="side">Drawer</mat-drawer> } </mat-drawer-container> `, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerDelayed { @ViewChild(MatDrawer) drawer: MatDrawer; showDrawer = false; } @Component({ template: ` <mat-drawer-container [dir]="direction"> @if (renderDrawer) { <mat-drawer [mode]="mode" style="width:100px"></mat-drawer> } </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerContainerStateChangesTestApp { @ViewChild(MatDrawer) drawer: MatDrawer; @ViewChild(MatDrawerContainer) drawerContainer: MatDrawerContainer; direction: Direction = 'ltr'; mode = 'side'; renderDrawer = true; } @Component({ template: ` <mat-drawer-container autosize style="min-height: 200px;"> <mat-drawer mode="push" [position]="drawer1Position"> Text <div [style.width.px]="fillerWidth" style="height: 200px; background: red;"></div> </mat-drawer> </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class AutosizeDrawer { @ViewChild(MatDrawer) drawer: MatDrawer; @ViewChild(MatDrawerContainer) drawerContainer: MatDrawerContainer; fillerWidth = 0; } @Component({ template: ` <mat-drawer-container> <mat-drawer>Drawer</mat-drawer> <mat-drawer-content>Content</mat-drawer-content> </mat-drawer-container> `, standalone: true, imports: [MatSidenavModule, A11yModule], }) class DrawerContainerWithContent { @ViewChild(MatDrawerContainer) drawerContainer: MatDrawerContainer; } @Component({ // Note that we need the `@if` so that there's an embedded // view between the container and the drawer. template: ` <mat-drawer-container #container> @if (true) { <mat-drawer #drawer>Drawer</mat-drawer> } </mat-drawer-container>`, standalone: true, imports: [MatSidenavModule, A11yModule], }) class IndirectDescendantDrawer { @ViewChild('container') container: MatDrawerContainer; @ViewChild('drawer') drawer: MatDrawer; } @Component({ template: ` <mat-drawer-container #outerContainer> <mat-drawer #outerDrawer>Drawer</mat-drawer> <mat-drawer-content> <mat-drawer-container #innerContainer> <mat-drawer #innerDrawer>Drawer</mat-drawer> </mat-drawer-container> </mat-drawer-content> </mat-drawer-container> `, standalone: true, imports: [MatSidenavModule, A11yModule], }) class NestedDrawerContainers { @ViewChild('outerContainer') outerContainer: MatDrawerContainer; @ViewChild('outerDrawer') outerDrawer: MatDrawer; @ViewChild('innerContainer') innerContainer: MatDrawerContainer; @ViewChild('innerDrawer') innerDrawer: MatDrawer; }
{ "commit_id": "ea0d1ba7b", "end_byte": 49158, "start_byte": 41742, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.spec.ts" }
components/src/material/sidenav/sidenav.md_0_8353
Angular Material provides two sets of components designed to add collapsible side content (often navigation, though it can be any content) alongside some primary content. These are the sidenav and drawer components. The sidenav components are designed to add side content to a fullscreen app. To set up a sidenav we use three components: `<mat-sidenav-container>` which acts as a structural container for our content and sidenav, `<mat-sidenav-content>` which represents the main content, and `<mat-sidenav>` which represents the added side content. <!-- example(sidenav-overview) --> The drawer component is designed to add side content to a small section of your app. This is accomplished using the `<mat-drawer-container>`, `<mat-drawer-content>`, and `<mat-drawer>` components, which are analogous to their sidenav equivalents. Rather than adding side content to the app as a whole, these are designed to add side content to a small section of your app. They support almost all of the same features, but do not support fixed positioning. <!-- example(sidenav-drawer-overview) --> ### Specifying the main and side content Both the main and side content should be placed inside of the `<mat-sidenav-container>`, content that you don't want to be affected by the sidenav, such as a header or footer, can be placed outside of the container. The side content should be wrapped in a `<mat-sidenav>` element. The `position` property can be used to specify which end of the main content to place the side content on. `position` can be either `start` or `end` which places the side content on the left or right respectively in left-to-right languages. If the `position` is not set, the default value of `start` will be assumed. A `<mat-sidenav-container>` can have up to two `<mat-sidenav>` elements total, but only one for any given side. The `<mat-sidenav>` must be placed as an immediate child of the `<mat-sidenav-container>`. The main content should be wrapped in a `<mat-sidenav-content>`. If no `<mat-sidenav-content>` is specified for a `<mat-sidenav-container>`, one will be created implicitly and all of the content inside the `<mat-sidenav-container>` other than the `<mat-sidenav>` elements will be placed inside of it. <!-- example(sidenav-position) --> The following are examples of valid sidenav layouts: ```html <!-- Creates a layout with a left-positioned sidenav and explicit content. --> <mat-sidenav-container> <mat-sidenav>Start</mat-sidenav> <mat-sidenav-content>Main</mat-sidenav-content> </mat-sidenav-container> ``` ```html <!-- Creates a layout with a left and right sidenav and implicit content. --> <mat-sidenav-container> <mat-sidenav>Start</mat-sidenav> <mat-sidenav position="end">End</mat-sidenav> <section>Main</section> </mat-sidenav-container> ``` ```html <!-- Creates an empty sidenav container with no sidenavs and implicit empty content. --> <mat-sidenav-container></mat-sidenav-container> ``` And these are examples of invalid sidenav layouts: ```html <!-- Invalid because there are two `start` position sidenavs. --> <mat-sidenav-container> <mat-sidenav>Start</mat-sidenav> <mat-sidenav position="start">Start 2</mat-sidenav> </mat-sidenav-container> ``` ```html <!-- Invalid because there are multiple `<mat-sidenav-content>` elements. --> <mat-sidenav-container> <mat-sidenav-content>Main</mat-sidenav-content> <mat-sidenav-content>Main 2</mat-sidenav-content> </mat-sidenav-container> ``` ```html <!-- Invalid because the `<mat-sidenav>` is outside of the `<mat-sidenav-container>`. --> <mat-sidenav-container></mat-sidenav-container> <mat-sidenav></mat-sidenav> ``` These same rules all apply to the drawer components as well. ### Opening and closing a sidenav A `<mat-sidenav>` can be opened or closed using the `open()`, `close()` and `toggle()` methods. Each of these methods returns a `Promise<boolean>` that will be resolved with `true` when the sidenav finishes opening or `false` when it finishes closing. The opened state can also be set via a property binding in the template using the `opened` property. The property supports 2-way binding. `<mat-sidenav>` also supports output properties for just open and just close events, The `(opened)` and `(closed)` properties respectively. <!-- example(sidenav-open-close) --> All of these properties and methods work on `<mat-drawer>` as well. ### Changing the sidenav's behavior The `<mat-sidenav>` can render in one of three different ways based on the `mode` property. | Mode | Description | |--------|-----------------------------------------------------------------------------------------| | `over` | Sidenav floats over the primary content, which is covered by a backdrop | | `push` | Sidenav pushes the primary content out of its way, also covering it with a backdrop | | `side` | Sidenav appears side-by-side with the main content, shrinking the main content's width to make space for the sidenav. | If no `mode` is specified, `over` is used by default. <!-- example(sidenav-mode) --> The `over` and `push` sidenav modes show a backdrop by default, while the `side` mode does not. This can be customized by setting the `hasBackdrop` property on `mat-sidenav-container`. Explicitly setting `hasBackdrop` to `true` or `false` will override the default backdrop visibility setting for all sidenavs regardless of mode. Leaving the property unset or setting it to `null` will use the default backdrop visibility for each mode. <!-- example(sidenav-backdrop) --> `<mat-drawer>` also supports all of these same modes and options. ### Disabling automatic close Clicking on the backdrop or pressing the <kbd>Esc</kbd> key will normally close an open sidenav. However, this automatic closing behavior can be disabled by setting the `disableClose` property on the `<mat-sidenav>` or `<mat-drawer>` that you want to disable the behavior for. Custom handling for <kbd>Esc</kbd> can be done by adding a keydown listener to the `<mat-sidenav>`. Custom handling for backdrop clicks can be done via the `(backdropClick)` output property on `<mat-sidenav-container>`. <!-- example(sidenav-disable-close) --> ### Resizing an open sidenav By default, Material will only measure and resize the drawer container in a few key moments (on open, on window resize, on mode change) in order to avoid layout thrashing, however there are cases where this can be problematic. If your app requires for a drawer to change its width while it is open, you can use the `autosize` option to tell Material to continue measuring it. Note that you should use this option **at your own risk**, because it could cause performance issues. <!-- example(sidenav-autosize) --> ### Setting the sidenav's size The `<mat-sidenav>` and `<mat-drawer>` will, by default, fit the size of its content. The width can be explicitly set via CSS: ```css mat-sidenav { width: 200px; } ``` Try to avoid percent based width as `resize` events are not (yet) supported. ### Fixed position sidenavs For `<mat-sidenav>` only (not `<mat-drawer>`) fixed positioning is supported. It can be enabled by setting the `fixedInViewport` property. Additionally, top and bottom space can be set via the `fixedTopGap` and `fixedBottomGap`. These properties accept a pixel value amount of space to add at the top or bottom. <!-- example(sidenav-fixed) --> ### Creating a responsive layout for mobile & desktop A sidenav often needs to behave differently on a mobile vs a desktop display. On a desktop, it may make sense to have just the content section scroll. However, on mobile you often want the body to be the element that scrolls; this allows the address bar to auto-hide. The sidenav can be styled with CSS to adjust to either type of device. <!-- example(sidenav-responsive) --> ### Reacting to scroll events inside the sidenav container To react to scrolling inside the `<mat-sidenav-container>`, you can get a hold of the underlying `CdkScrollable` instance through the `MatSidenavContainer`. ```ts class YourComponent implements AfterViewInit { @ViewChild(MatSidenavContainer) sidenavContainer: MatSidenavContainer; ngAfterViewInit() { this.sidenavContainer.scrollable.elementScrolled().subscribe(() => /* react to scrolling */); } } ```
{ "commit_id": "ea0d1ba7b", "end_byte": 8353, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/sidenav.md" }
components/src/material/sidenav/sidenav.md_8353_9797
### Accessibility The `<mat-sidenav>` and `<mat-sidenav-content>` should each be given an appropriate `role` attribute depending on the context in which they are used. For example, a `<mat-sidenav>` that contains links to other pages might be marked `role="navigation"`, whereas one that contains a table of contents about might be marked as `role="directory"`. If there is no more specific role that describes your sidenav, `role="region"` is recommended. Similarly, the `<mat-sidenav-content>` should be given a role based on what it contains. If it represents the primary content of the page, it may make sense to mark it `role="main"`. If no more specific role makes sense, `role="region"` is again a good fallback. #### Focus management The sidenav has the ability to capture focus. This behavior is turned on for the `push` and `over` modes and it is off for `side` mode. You can change its default behavior by the `autoFocus` input. By default the first tabbable element will receive focus upon open. If you want a different element to be focused, you can set the `cdkFocusInitial` attribute on it. ### Troubleshooting #### Error: A drawer was already declared for 'position="..."' This error is thrown if you have more than one sidenav or drawer in a given container with the same `position`. The `position` property defaults to `start`, so the issue may just be that you forgot to mark the `end` sidenav with `position="end"`.
{ "commit_id": "ea0d1ba7b", "end_byte": 9797, "start_byte": 8353, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/sidenav.md" }
components/src/material/sidenav/BUILD.bazel_0_1788
load( "//tools:defaults.bzl", "extract_tokens", "markdown_to_html", "ng_module", "ng_test_library", "ng_web_test_suite", "sass_binary", "sass_library", ) package(default_visibility = ["//visibility:public"]) ng_module( name = "sidenav", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [":drawer.css"] + glob(["**/*.html"]), deps = [ "//src:dev_mode_types", "//src/cdk/a11y", "//src/cdk/bidi", "//src/cdk/coercion", "//src/cdk/keycodes", "//src/cdk/scrolling", "//src/material/core", "@npm//@angular/animations", "@npm//@angular/core", "@npm//@angular/platform-browser", "@npm//rxjs", ], ) sass_library( name = "sidenav_scss_lib", srcs = glob(["**/_*.scss"]), deps = ["//src/material/core:core_scss_lib"], ) sass_binary( name = "drawer_scss", src = "drawer.scss", deps = [ "//src/cdk:sass_lib", "//src/material/core:core_scss_lib", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], ), deps = [ ":sidenav", "//src/cdk/a11y", "//src/cdk/bidi", "//src/cdk/keycodes", "//src/cdk/platform", "//src/cdk/scrolling", "//src/cdk/testing", "//src/cdk/testing/private", "@npm//@angular/common", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_test_sources"], ) markdown_to_html( name = "overview", srcs = [":sidenav.md"], ) extract_tokens( name = "tokens", srcs = [":sidenav_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "commit_id": "ea0d1ba7b", "end_byte": 1788, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/BUILD.bazel" }
components/src/material/sidenav/index.ts_0_234
/** * @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 */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/index.ts" }
components/src/material/sidenav/drawer.ts_0_4545
/** * @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 {AnimationEvent} from '@angular/animations'; import { FocusMonitor, FocusOrigin, FocusTrap, FocusTrapFactory, InteractivityChecker, } from '@angular/cdk/a11y'; import {Directionality} from '@angular/cdk/bidi'; import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion'; import {ESCAPE, hasModifierKey} from '@angular/cdk/keycodes'; import {Platform} from '@angular/cdk/platform'; import {CdkScrollable, ScrollDispatcher, ViewportRuler} from '@angular/cdk/scrolling'; import {DOCUMENT} from '@angular/common'; import { AfterContentChecked, AfterContentInit, afterNextRender, AfterRenderPhase, AfterViewInit, ANIMATION_MODULE_TYPE, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, DoCheck, ElementRef, EventEmitter, inject, InjectionToken, Injector, Input, NgZone, OnDestroy, Output, QueryList, ViewChild, ViewEncapsulation, } from '@angular/core'; import {fromEvent, merge, Observable, Subject} from 'rxjs'; import {debounceTime, filter, map, mapTo, startWith, take, takeUntil} from 'rxjs/operators'; import {matDrawerAnimations} from './drawer-animations'; /** * Throws an exception when two MatDrawer are matching the same position. * @docs-private */ export function throwMatDuplicatedDrawerError(position: string) { throw Error(`A drawer was already declared for 'position="${position}"'`); } /** Options for where to set focus to automatically on dialog open */ export type AutoFocusTarget = 'dialog' | 'first-tabbable' | 'first-heading'; /** Result of the toggle promise that indicates the state of the drawer. */ export type MatDrawerToggleResult = 'open' | 'close'; /** Drawer and SideNav display modes. */ export type MatDrawerMode = 'over' | 'push' | 'side'; /** Configures whether drawers should use auto sizing by default. */ export const MAT_DRAWER_DEFAULT_AUTOSIZE = new InjectionToken<boolean>( 'MAT_DRAWER_DEFAULT_AUTOSIZE', { providedIn: 'root', factory: MAT_DRAWER_DEFAULT_AUTOSIZE_FACTORY, }, ); /** * Used to provide a drawer container to a drawer while avoiding circular references. * @docs-private */ export const MAT_DRAWER_CONTAINER = new InjectionToken('MAT_DRAWER_CONTAINER'); /** @docs-private */ export function MAT_DRAWER_DEFAULT_AUTOSIZE_FACTORY(): boolean { return false; } @Component({ selector: 'mat-drawer-content', template: '<ng-content></ng-content>', host: { 'class': 'mat-drawer-content', '[style.margin-left.px]': '_container._contentMargins.left', '[style.margin-right.px]': '_container._contentMargins.right', }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, providers: [ { provide: CdkScrollable, useExisting: MatDrawerContent, }, ], }) export class MatDrawerContent extends CdkScrollable implements AfterContentInit { private _changeDetectorRef = inject(ChangeDetectorRef); _container = inject(MatDrawerContainer); constructor(...args: unknown[]); constructor() { const elementRef = inject<ElementRef<HTMLElement>>(ElementRef); const scrollDispatcher = inject(ScrollDispatcher); const ngZone = inject(NgZone); super(elementRef, scrollDispatcher, ngZone); } ngAfterContentInit() { this._container._contentMarginChanges.subscribe(() => { this._changeDetectorRef.markForCheck(); }); } } /** * This component corresponds to a drawer that can be opened on the drawer container. */ @Component({ selector: 'mat-drawer', exportAs: 'matDrawer', templateUrl: 'drawer.html', animations: [matDrawerAnimations.transformDrawer], host: { 'class': 'mat-drawer', // must prevent the browser from aligning text based on value '[attr.align]': 'null', '[class.mat-drawer-end]': 'position === "end"', '[class.mat-drawer-over]': 'mode === "over"', '[class.mat-drawer-push]': 'mode === "push"', '[class.mat-drawer-side]': 'mode === "side"', '[class.mat-drawer-opened]': 'opened', 'tabIndex': '-1', '[@transform]': '_animationState', '(@transform.start)': '_animationStarted.next($event)', '(@transform.done)': '_animationEnd.next($event)', }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, imports: [CdkScrollable], }) export
{ "commit_id": "ea0d1ba7b", "end_byte": 4545, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.ts" }
components/src/material/sidenav/drawer.ts_4546_12994
class MatDrawer implements AfterViewInit, AfterContentChecked, OnDestroy { private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef); private _focusTrapFactory = inject(FocusTrapFactory); private _focusMonitor = inject(FocusMonitor); private _platform = inject(Platform); private _ngZone = inject(NgZone); private readonly _interactivityChecker = inject(InteractivityChecker); private _doc = inject(DOCUMENT, {optional: true})!; _container? = inject<MatDrawerContainer>(MAT_DRAWER_CONTAINER, {optional: true}); private _focusTrap: FocusTrap | null = null; private _elementFocusedBeforeDrawerWasOpened: HTMLElement | null = null; /** Whether the drawer is initialized. Used for disabling the initial animation. */ private _enableAnimations = false; /** Whether the view of the component has been attached. */ private _isAttached: boolean; /** Anchor node used to restore the drawer to its initial position. */ private _anchor: Comment | null; /** The side that the drawer is attached to. */ @Input() get position(): 'start' | 'end' { return this._position; } set position(value: 'start' | 'end') { // Make sure we have a valid value. value = value === 'end' ? 'end' : 'start'; if (value !== this._position) { // Static inputs in Ivy are set before the element is in the DOM. if (this._isAttached) { this._updatePositionInParent(value); } this._position = value; this.onPositionChanged.emit(); } } private _position: 'start' | 'end' = 'start'; /** Mode of the drawer; one of 'over', 'push' or 'side'. */ @Input() get mode(): MatDrawerMode { return this._mode; } set mode(value: MatDrawerMode) { this._mode = value; this._updateFocusTrapState(); this._modeChanged.next(); } private _mode: MatDrawerMode = 'over'; /** Whether the drawer can be closed with the escape key or by clicking on the backdrop. */ @Input() get disableClose(): boolean { return this._disableClose; } set disableClose(value: BooleanInput) { this._disableClose = coerceBooleanProperty(value); } private _disableClose: boolean = false; /** * Whether the drawer should focus the first focusable element automatically when opened. * Defaults to false in when `mode` is set to `side`, otherwise defaults to `true`. If explicitly * enabled, focus will be moved into the sidenav in `side` mode as well. * @breaking-change 14.0.0 Remove boolean option from autoFocus. Use string or AutoFocusTarget * instead. */ @Input() get autoFocus(): AutoFocusTarget | string | boolean { const value = this._autoFocus; // Note that usually we don't allow autoFocus to be set to `first-tabbable` in `side` mode, // because we don't know how the sidenav is being used, but in some cases it still makes // sense to do it. The consumer can explicitly set `autoFocus`. if (value == null) { if (this.mode === 'side') { return 'dialog'; } else { return 'first-tabbable'; } } return value; } set autoFocus(value: AutoFocusTarget | string | BooleanInput) { if (value === 'true' || value === 'false' || value == null) { value = coerceBooleanProperty(value); } this._autoFocus = value; } private _autoFocus: AutoFocusTarget | string | boolean | undefined; /** * Whether the drawer is opened. We overload this because we trigger an event when it * starts or end. */ @Input() get opened(): boolean { return this._opened; } set opened(value: BooleanInput) { this.toggle(coerceBooleanProperty(value)); } private _opened: boolean = false; /** How the sidenav was opened (keypress, mouse click etc.) */ private _openedVia: FocusOrigin | null; /** Emits whenever the drawer has started animating. */ readonly _animationStarted = new Subject<AnimationEvent>(); /** Emits whenever the drawer is done animating. */ readonly _animationEnd = new Subject<AnimationEvent>(); /** Current state of the sidenav animation. */ _animationState: 'open-instant' | 'open' | 'void' = 'void'; /** Event emitted when the drawer open state is changed. */ @Output() readonly openedChange: EventEmitter<boolean> = // Note this has to be async in order to avoid some issues with two-bindings (see #8872). new EventEmitter<boolean>(/* isAsync */ true); /** Event emitted when the drawer has been opened. */ @Output('opened') readonly _openedStream = this.openedChange.pipe( filter(o => o), map(() => {}), ); /** Event emitted when the drawer has started opening. */ @Output() readonly openedStart: Observable<void> = this._animationStarted.pipe( filter(e => e.fromState !== e.toState && e.toState.indexOf('open') === 0), mapTo(undefined), ); /** Event emitted when the drawer has been closed. */ @Output('closed') readonly _closedStream = this.openedChange.pipe( filter(o => !o), map(() => {}), ); /** Event emitted when the drawer has started closing. */ @Output() readonly closedStart: Observable<void> = this._animationStarted.pipe( filter(e => e.fromState !== e.toState && e.toState === 'void'), mapTo(undefined), ); /** Emits when the component is destroyed. */ private readonly _destroyed = new Subject<void>(); /** Event emitted when the drawer's position changes. */ // tslint:disable-next-line:no-output-on-prefix @Output('positionChanged') readonly onPositionChanged = new EventEmitter<void>(); /** Reference to the inner element that contains all the content. */ @ViewChild('content') _content: ElementRef<HTMLElement>; /** * An observable that emits when the drawer mode changes. This is used by the drawer container to * to know when to when the mode changes so it can adapt the margins on the content. */ readonly _modeChanged = new Subject<void>(); private _injector = inject(Injector); private _changeDetectorRef = inject(ChangeDetectorRef); constructor(...args: unknown[]); constructor() { this.openedChange.pipe(takeUntil(this._destroyed)).subscribe((opened: boolean) => { if (opened) { if (this._doc) { this._elementFocusedBeforeDrawerWasOpened = this._doc.activeElement as HTMLElement; } this._takeFocus(); } else if (this._isFocusWithinDrawer()) { this._restoreFocus(this._openedVia || 'program'); } }); /** * Listen to `keydown` events outside the zone so that change detection is not run every * time a key is pressed. Instead we re-enter the zone only if the `ESC` key is pressed * and we don't have close disabled. */ this._ngZone.runOutsideAngular(() => { (fromEvent(this._elementRef.nativeElement, 'keydown') as Observable<KeyboardEvent>) .pipe( filter(event => { return event.keyCode === ESCAPE && !this.disableClose && !hasModifierKey(event); }), takeUntil(this._destroyed), ) .subscribe(event => this._ngZone.run(() => { this.close(); event.stopPropagation(); event.preventDefault(); }), ); }); this._animationEnd.subscribe((event: AnimationEvent) => { const {fromState, toState} = event; if ( (toState.indexOf('open') === 0 && fromState === 'void') || (toState === 'void' && fromState.indexOf('open') === 0) ) { this.openedChange.emit(this._opened); } }); } /** * Focuses the provided element. If the element is not focusable, it will add a tabIndex * attribute to forcefully focus it. The attribute is removed after focus is moved. * @param element The element to focus. */ private _forceFocus(element: HTMLElement, options?: FocusOptions) { if (!this._interactivityChecker.isFocusable(element)) { element.tabIndex = -1; // The tabindex attribute should be removed to avoid navigating to that element again this._ngZone.runOutsideAngular(() => { const callback = () => { element.removeEventListener('blur', callback); element.removeEventListener('mousedown', callback); element.removeAttribute('tabindex'); }; element.addEventListener('blur', callback); element.addEventListener('mousedown', callback); }); } element.focus(options); }
{ "commit_id": "ea0d1ba7b", "end_byte": 12994, "start_byte": 4546, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.ts" }
components/src/material/sidenav/drawer.ts_12998_20956
/** * Focuses the first element that matches the given selector within the focus trap. * @param selector The CSS selector for the element to set focus to. */ private _focusByCssSelector(selector: string, options?: FocusOptions) { let elementToFocus = this._elementRef.nativeElement.querySelector( selector, ) as HTMLElement | null; if (elementToFocus) { this._forceFocus(elementToFocus, options); } } /** * Moves focus into the drawer. Note that this works even if * the focus trap is disabled in `side` mode. */ private _takeFocus() { if (!this._focusTrap) { return; } const element = this._elementRef.nativeElement; // When autoFocus is not on the sidenav, if the element cannot be focused or does // not exist, focus the sidenav itself so the keyboard navigation still works. // We need to check that `focus` is a function due to Universal. switch (this.autoFocus) { case false: case 'dialog': return; case true: case 'first-tabbable': afterNextRender( () => { const hasMovedFocus = this._focusTrap!.focusInitialElement(); if (!hasMovedFocus && typeof element.focus === 'function') { element.focus(); } }, {injector: this._injector}, ); break; case 'first-heading': this._focusByCssSelector('h1, h2, h3, h4, h5, h6, [role="heading"]'); break; default: this._focusByCssSelector(this.autoFocus!); break; } } /** * Restores focus to the element that was originally focused when the drawer opened. * If no element was focused at that time, the focus will be restored to the drawer. */ private _restoreFocus(focusOrigin: Exclude<FocusOrigin, null>) { if (this.autoFocus === 'dialog') { return; } if (this._elementFocusedBeforeDrawerWasOpened) { this._focusMonitor.focusVia(this._elementFocusedBeforeDrawerWasOpened, focusOrigin); } else { this._elementRef.nativeElement.blur(); } this._elementFocusedBeforeDrawerWasOpened = null; } /** Whether focus is currently within the drawer. */ private _isFocusWithinDrawer(): boolean { const activeEl = this._doc.activeElement; return !!activeEl && this._elementRef.nativeElement.contains(activeEl); } ngAfterViewInit() { this._isAttached = true; // Only update the DOM position when the sidenav is positioned at // the end since we project the sidenav before the content by default. if (this._position === 'end') { this._updatePositionInParent('end'); } // Needs to happen after the position is updated // so the focus trap anchors are in the right place. if (this._platform.isBrowser) { this._focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement); this._updateFocusTrapState(); } } ngAfterContentChecked() { // Enable the animations after the lifecycle hooks have run, in order to avoid animating // drawers that are open by default. When we're on the server, we shouldn't enable the // animations, because we don't want the drawer to animate the first time the user sees // the page. if (this._platform.isBrowser) { this._enableAnimations = true; } } ngOnDestroy() { this._focusTrap?.destroy(); this._anchor?.remove(); this._anchor = null; this._animationStarted.complete(); this._animationEnd.complete(); this._modeChanged.complete(); this._destroyed.next(); this._destroyed.complete(); } /** * Open the drawer. * @param openedVia Whether the drawer was opened by a key press, mouse click or programmatically. * Used for focus management after the sidenav is closed. */ open(openedVia?: FocusOrigin): Promise<MatDrawerToggleResult> { return this.toggle(true, openedVia); } /** Close the drawer. */ close(): Promise<MatDrawerToggleResult> { return this.toggle(false); } /** Closes the drawer with context that the backdrop was clicked. */ _closeViaBackdropClick(): Promise<MatDrawerToggleResult> { // If the drawer is closed upon a backdrop click, we always want to restore focus. We // don't need to check whether focus is currently in the drawer, as clicking on the // backdrop causes blurs the active element. return this._setOpen(/* isOpen */ false, /* restoreFocus */ true, 'mouse'); } /** * Toggle this drawer. * @param isOpen Whether the drawer should be open. * @param openedVia Whether the drawer was opened by a key press, mouse click or programmatically. * Used for focus management after the sidenav is closed. */ toggle(isOpen: boolean = !this.opened, openedVia?: FocusOrigin): Promise<MatDrawerToggleResult> { // If the focus is currently inside the drawer content and we are closing the drawer, // restore the focus to the initially focused element (when the drawer opened). if (isOpen && openedVia) { this._openedVia = openedVia; } const result = this._setOpen( isOpen, /* restoreFocus */ !isOpen && this._isFocusWithinDrawer(), this._openedVia || 'program', ); if (!isOpen) { this._openedVia = null; } return result; } /** * Toggles the opened state of the drawer. * @param isOpen Whether the drawer should open or close. * @param restoreFocus Whether focus should be restored on close. * @param focusOrigin Origin to use when restoring focus. */ private _setOpen( isOpen: boolean, restoreFocus: boolean, focusOrigin: Exclude<FocusOrigin, null>, ): Promise<MatDrawerToggleResult> { this._opened = isOpen; if (isOpen) { this._animationState = this._enableAnimations ? 'open' : 'open-instant'; } else { this._animationState = 'void'; if (restoreFocus) { this._restoreFocus(focusOrigin); } } // Needed to ensure that the closing sequence fires off correctly. this._changeDetectorRef.markForCheck(); this._updateFocusTrapState(); return new Promise<MatDrawerToggleResult>(resolve => { this.openedChange.pipe(take(1)).subscribe(open => resolve(open ? 'open' : 'close')); }); } _getWidth(): number { return this._elementRef.nativeElement ? this._elementRef.nativeElement.offsetWidth || 0 : 0; } /** Updates the enabled state of the focus trap. */ private _updateFocusTrapState() { if (this._focusTrap) { // Trap focus only if the backdrop is enabled. Otherwise, allow end user to interact with the // sidenav content. this._focusTrap.enabled = !!this._container?.hasBackdrop && this.opened; } } /** * Updates the position of the drawer in the DOM. We need to move the element around ourselves * when it's in the `end` position so that it comes after the content and the visual order * matches the tab order. We also need to be able to move it back to `start` if the sidenav * started off as `end` and was changed to `start`. */ private _updatePositionInParent(newPosition: 'start' | 'end'): void { // Don't move the DOM node around on the server, because it can throw off hydration. if (!this._platform.isBrowser) { return; } const element = this._elementRef.nativeElement; const parent = element.parentNode!; if (newPosition === 'end') { if (!this._anchor) { this._anchor = this._doc.createComment('mat-drawer-anchor')!; parent.insertBefore(this._anchor!, element); } parent.appendChild(element); } else if (this._anchor) { this._anchor.parentNode!.insertBefore(element, this._anchor); } } } /** * `<mat-drawer-container>` component. * * This is the parent component to one or two `<mat-drawer>`s that validates the state internally * and coordinates the backdrop and content styling. */
{ "commit_id": "ea0d1ba7b", "end_byte": 20956, "start_byte": 12998, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.ts" }
components/src/material/sidenav/drawer.ts_20957_21474
@Component({ selector: 'mat-drawer-container', exportAs: 'matDrawerContainer', templateUrl: 'drawer-container.html', styleUrl: 'drawer.css', host: { 'class': 'mat-drawer-container', '[class.mat-drawer-container-explicit-backdrop]': '_backdropOverride', }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, providers: [ { provide: MAT_DRAWER_CONTAINER, useExisting: MatDrawerContainer, }, ], imports: [MatDrawerContent], }) export
{ "commit_id": "ea0d1ba7b", "end_byte": 21474, "start_byte": 20957, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.ts" }
components/src/material/sidenav/drawer.ts_21475_29607
class MatDrawerContainer implements AfterContentInit, DoCheck, OnDestroy { private _dir = inject(Directionality, {optional: true}); private _element = inject<ElementRef<HTMLElement>>(ElementRef); private _ngZone = inject(NgZone); private _changeDetectorRef = inject(ChangeDetectorRef); private _animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true}); /** All drawers in the container. Includes drawers from inside nested containers. */ @ContentChildren(MatDrawer, { // We need to use `descendants: true`, because Ivy will no longer match // indirect descendants if it's left as false. descendants: true, }) _allDrawers: QueryList<MatDrawer>; /** Drawers that belong to this container. */ _drawers = new QueryList<MatDrawer>(); @ContentChild(MatDrawerContent) _content: MatDrawerContent; @ViewChild(MatDrawerContent) _userContent: MatDrawerContent; /** The drawer child with the `start` position. */ get start(): MatDrawer | null { return this._start; } /** The drawer child with the `end` position. */ get end(): MatDrawer | null { return this._end; } /** * Whether to automatically resize the container whenever * the size of any of its drawers changes. * * **Use at your own risk!** Enabling this option can cause layout thrashing by measuring * the drawers on every change detection cycle. Can be configured globally via the * `MAT_DRAWER_DEFAULT_AUTOSIZE` token. */ @Input() get autosize(): boolean { return this._autosize; } set autosize(value: BooleanInput) { this._autosize = coerceBooleanProperty(value); } private _autosize = inject(MAT_DRAWER_DEFAULT_AUTOSIZE); /** * Whether the drawer container should have a backdrop while one of the sidenavs is open. * If explicitly set to `true`, the backdrop will be enabled for drawers in the `side` * mode as well. */ @Input() get hasBackdrop(): boolean { return this._drawerHasBackdrop(this._start) || this._drawerHasBackdrop(this._end); } set hasBackdrop(value: BooleanInput) { this._backdropOverride = value == null ? null : coerceBooleanProperty(value); } _backdropOverride: boolean | null; /** Event emitted when the drawer backdrop is clicked. */ @Output() readonly backdropClick: EventEmitter<void> = new EventEmitter<void>(); /** The drawer at the start/end position, independent of direction. */ private _start: MatDrawer | null; private _end: MatDrawer | null; /** * The drawer at the left/right. When direction changes, these will change as well. * They're used as aliases for the above to set the left/right style properly. * In LTR, _left == _start and _right == _end. * In RTL, _left == _end and _right == _start. */ private _left: MatDrawer | null; private _right: MatDrawer | null; /** Emits when the component is destroyed. */ private readonly _destroyed = new Subject<void>(); /** Emits on every ngDoCheck. Used for debouncing reflows. */ private readonly _doCheckSubject = new Subject<void>(); /** * Margins to be applied to the content. These are used to push / shrink the drawer content when a * drawer is open. We use margin rather than transform even for push mode because transform breaks * fixed position elements inside of the transformed element. */ _contentMargins: {left: number | null; right: number | null} = {left: null, right: null}; readonly _contentMarginChanges = new Subject<{left: number | null; right: number | null}>(); /** Reference to the CdkScrollable instance that wraps the scrollable content. */ get scrollable(): CdkScrollable { return this._userContent || this._content; } private _injector = inject(Injector); constructor(...args: unknown[]); constructor() { const viewportRuler = inject(ViewportRuler); // If a `Dir` directive exists up the tree, listen direction changes // and update the left/right properties to point to the proper start/end. this._dir?.change.pipe(takeUntil(this._destroyed)).subscribe(() => { this._validateDrawers(); this.updateContentMargins(); }); // Since the minimum width of the sidenav depends on the viewport width, // we need to recompute the margins if the viewport changes. viewportRuler .change() .pipe(takeUntil(this._destroyed)) .subscribe(() => this.updateContentMargins()); } ngAfterContentInit() { this._allDrawers.changes .pipe(startWith(this._allDrawers), takeUntil(this._destroyed)) .subscribe((drawer: QueryList<MatDrawer>) => { this._drawers.reset(drawer.filter(item => !item._container || item._container === this)); this._drawers.notifyOnChanges(); }); this._drawers.changes.pipe(startWith(null)).subscribe(() => { this._validateDrawers(); this._drawers.forEach((drawer: MatDrawer) => { this._watchDrawerToggle(drawer); this._watchDrawerPosition(drawer); this._watchDrawerMode(drawer); }); if ( !this._drawers.length || this._isDrawerOpen(this._start) || this._isDrawerOpen(this._end) ) { this.updateContentMargins(); } this._changeDetectorRef.markForCheck(); }); // Avoid hitting the NgZone through the debounce timeout. this._ngZone.runOutsideAngular(() => { this._doCheckSubject .pipe( debounceTime(10), // Arbitrary debounce time, less than a frame at 60fps takeUntil(this._destroyed), ) .subscribe(() => this.updateContentMargins()); }); } ngOnDestroy() { this._contentMarginChanges.complete(); this._doCheckSubject.complete(); this._drawers.destroy(); this._destroyed.next(); this._destroyed.complete(); } /** Calls `open` of both start and end drawers */ open(): void { this._drawers.forEach(drawer => drawer.open()); } /** Calls `close` of both start and end drawers */ close(): void { this._drawers.forEach(drawer => drawer.close()); } /** * Recalculates and updates the inline styles for the content. Note that this should be used * sparingly, because it causes a reflow. */ updateContentMargins() { // 1. For drawers in `over` mode, they don't affect the content. // 2. For drawers in `side` mode they should shrink the content. We do this by adding to the // left margin (for left drawer) or right margin (for right the drawer). // 3. For drawers in `push` mode the should shift the content without resizing it. We do this by // adding to the left or right margin and simultaneously subtracting the same amount of // margin from the other side. let left = 0; let right = 0; if (this._left && this._left.opened) { if (this._left.mode == 'side') { left += this._left._getWidth(); } else if (this._left.mode == 'push') { const width = this._left._getWidth(); left += width; right -= width; } } if (this._right && this._right.opened) { if (this._right.mode == 'side') { right += this._right._getWidth(); } else if (this._right.mode == 'push') { const width = this._right._getWidth(); right += width; left -= width; } } // If either `right` or `left` is zero, don't set a style to the element. This // allows users to specify a custom size via CSS class in SSR scenarios where the // measured widths will always be zero. Note that we reset to `null` here, rather // than below, in order to ensure that the types in the `if` below are consistent. left = left || null!; right = right || null!; if (left !== this._contentMargins.left || right !== this._contentMargins.right) { this._contentMargins = {left, right}; // Pull back into the NgZone since in some cases we could be outside. We need to be careful // to do it only when something changed, otherwise we can end up hitting the zone too often. this._ngZone.run(() => this._contentMarginChanges.next(this._contentMargins)); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 29607, "start_byte": 21475, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.ts" }
components/src/material/sidenav/drawer.ts_29611_34688
ngDoCheck() { // If users opted into autosizing, do a check every change detection cycle. if (this._autosize && this._isPushed()) { // Run outside the NgZone, otherwise the debouncer will throw us into an infinite loop. this._ngZone.runOutsideAngular(() => this._doCheckSubject.next()); } } /** * Subscribes to drawer events in order to set a class on the main container element when the * drawer is open and the backdrop is visible. This ensures any overflow on the container element * is properly hidden. */ private _watchDrawerToggle(drawer: MatDrawer): void { drawer._animationStarted .pipe( filter((event: AnimationEvent) => event.fromState !== event.toState), takeUntil(this._drawers.changes), ) .subscribe((event: AnimationEvent) => { // Set the transition class on the container so that the animations occur. This should not // be set initially because animations should only be triggered via a change in state. if (event.toState !== 'open-instant' && this._animationMode !== 'NoopAnimations') { this._element.nativeElement.classList.add('mat-drawer-transition'); } this.updateContentMargins(); this._changeDetectorRef.markForCheck(); }); if (drawer.mode !== 'side') { drawer.openedChange .pipe(takeUntil(this._drawers.changes)) .subscribe(() => this._setContainerClass(drawer.opened)); } } /** * Subscribes to drawer onPositionChanged event in order to * re-validate drawers when the position changes. */ private _watchDrawerPosition(drawer: MatDrawer): void { if (!drawer) { return; } // NOTE: We need to wait for the microtask queue to be empty before validating, // since both drawers may be swapping positions at the same time. drawer.onPositionChanged.pipe(takeUntil(this._drawers.changes)).subscribe(() => { afterNextRender( () => { this._validateDrawers(); }, {injector: this._injector, phase: AfterRenderPhase.Read}, ); }); } /** Subscribes to changes in drawer mode so we can run change detection. */ private _watchDrawerMode(drawer: MatDrawer): void { if (drawer) { drawer._modeChanged .pipe(takeUntil(merge(this._drawers.changes, this._destroyed))) .subscribe(() => { this.updateContentMargins(); this._changeDetectorRef.markForCheck(); }); } } /** Toggles the 'mat-drawer-opened' class on the main 'mat-drawer-container' element. */ private _setContainerClass(isAdd: boolean): void { const classList = this._element.nativeElement.classList; const className = 'mat-drawer-container-has-open'; if (isAdd) { classList.add(className); } else { classList.remove(className); } } /** Validate the state of the drawer children components. */ private _validateDrawers() { this._start = this._end = null; // Ensure that we have at most one start and one end drawer. this._drawers.forEach(drawer => { if (drawer.position == 'end') { if (this._end != null && (typeof ngDevMode === 'undefined' || ngDevMode)) { throwMatDuplicatedDrawerError('end'); } this._end = drawer; } else { if (this._start != null && (typeof ngDevMode === 'undefined' || ngDevMode)) { throwMatDuplicatedDrawerError('start'); } this._start = drawer; } }); this._right = this._left = null; // Detect if we're LTR or RTL. if (this._dir && this._dir.value === 'rtl') { this._left = this._end; this._right = this._start; } else { this._left = this._start; this._right = this._end; } } /** Whether the container is being pushed to the side by one of the drawers. */ private _isPushed() { return ( (this._isDrawerOpen(this._start) && this._start.mode != 'over') || (this._isDrawerOpen(this._end) && this._end.mode != 'over') ); } _onBackdropClicked() { this.backdropClick.emit(); this._closeModalDrawersViaBackdrop(); } _closeModalDrawersViaBackdrop() { // Close all open drawers where closing is not disabled and the mode is not `side`. [this._start, this._end] .filter(drawer => drawer && !drawer.disableClose && this._drawerHasBackdrop(drawer)) .forEach(drawer => drawer!._closeViaBackdropClick()); } _isShowingBackdrop(): boolean { return ( (this._isDrawerOpen(this._start) && this._drawerHasBackdrop(this._start)) || (this._isDrawerOpen(this._end) && this._drawerHasBackdrop(this._end)) ); } private _isDrawerOpen(drawer: MatDrawer | null): drawer is MatDrawer { return drawer != null && drawer.opened; } // Whether argument drawer should have a backdrop when it opens private _drawerHasBackdrop(drawer: MatDrawer | null) { if (this._backdropOverride == null) { return !!drawer && drawer.mode !== 'side'; } return this._backdropOverride; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 34688, "start_byte": 29611, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.ts" }
components/src/material/sidenav/drawer.scss_0_8343
@use '@angular/cdk'; @use '../core/tokens/m2/mat/sidenav' as tokens-mat-sidenav; @use '../core/tokens/token-utils'; @use '../core/style/variables'; @use '../core/style/layout-common'; $drawer-content-z-index: 1; $drawer-side-drawer-z-index: 2; $drawer-backdrop-z-index: 3; $drawer-over-drawer-z-index: 4; // Mixin that creates a new stacking context. // see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context @mixin drawer-stacking-context($z-index: 1) { position: relative; // Use a z-index to create a new stacking context. (We can't use transform because it breaks fixed // positioning inside of the transformed element). z-index: $z-index; } .mat-drawer-container { // We need a stacking context here so that the backdrop and drawers are clipped to the // MatDrawerContainer. This creates a new z-index stack so we use low numbered z-indices. // We create another stacking context in the '.mat-drawer-content' and in each drawer so that // the application content does not get messed up with our own CSS. @include drawer-stacking-context(); @include token-utils.use-tokens( tokens-mat-sidenav.$prefix, tokens-mat-sidenav.get-token-slots()) { @include token-utils.create-token-slot(color, content-text-color); @include token-utils.create-token-slot(background-color, content-background-color); } box-sizing: border-box; -webkit-overflow-scrolling: touch; // Need this to take up space in the layout. display: block; // Hide the drawers when they're closed. overflow: hidden; // TODO(hansl): Update this with a more robust solution. &[fullscreen] { @include layout-common.fill(); &.mat-drawer-container-has-open { overflow: hidden; } } // When the consumer explicitly enabled the backdrop, // we have to pull the side drawers above it. &.mat-drawer-container-explicit-backdrop .mat-drawer-side { z-index: $drawer-backdrop-z-index; } // Note that the `NoopAnimationsModule` is being handled inside of the component code. &.ng-animate-disabled, .ng-animate-disabled & { .mat-drawer-backdrop, .mat-drawer-content { transition: none; } } } .mat-drawer-backdrop { @include layout-common.fill(); display: block; // Because of the new stacking context, the z-index stack is new and we can use our own // numbers. z-index: $drawer-backdrop-z-index; // We use 'visibility: hidden | visible' because 'display: none' will not animate any // transitions, while visibility will interpolate transitions properly. // see https://developer.mozilla.org/en-US/docs/Web/CSS/visibility, the Interpolation // section. visibility: hidden; &.mat-drawer-shown { visibility: visible; @include token-utils.use-tokens( tokens-mat-sidenav.$prefix, tokens-mat-sidenav.get-token-slots()) { @include token-utils.create-token-slot(background-color, scrim-color); } } .mat-drawer-transition & { transition: { duration: variables.$swift-ease-out-duration; timing-function: variables.$swift-ease-out-timing-function; property: background-color, visibility; } } @include cdk.high-contrast { opacity: 0.5; } } .mat-drawer-content { @include drawer-stacking-context($drawer-content-z-index); display: block; height: 100%; overflow: auto; .mat-drawer-transition & { transition: { duration: variables.$swift-ease-out-duration; timing-function: variables.$swift-ease-out-timing-function; property: transform, margin-left, margin-right; } } } .mat-drawer { $high-contrast-border: solid 1px currentColor; @include drawer-stacking-context($drawer-over-drawer-z-index); @include token-utils.use-tokens( tokens-mat-sidenav.$prefix, tokens-mat-sidenav.get-token-slots()) { @include token-utils.create-token-slot(color, container-text-color); @include token-utils.create-token-slot(box-shadow, container-elevation-shadow); @include token-utils.create-token-slot(background-color, container-background-color); @include token-utils.create-token-slot(border-top-right-radius, container-shape); @include token-utils.create-token-slot(border-bottom-right-radius, container-shape); @include token-utils.create-token-slot(width, container-width); } display: block; position: absolute; top: 0; bottom: 0; z-index: 3; outline: 0; box-sizing: border-box; overflow-y: auto; // TODO(kara): revisit scrolling behavior for drawers transform: translate3d(-100%, 0, 0); &, [dir='rtl'] &.mat-drawer-end { @include cdk.high-contrast { border-right: $high-contrast-border; } } [dir='rtl'] &, &.mat-drawer-end { @include cdk.high-contrast { border-left: $high-contrast-border; border-right: none; } } &.mat-drawer-side { z-index: $drawer-side-drawer-z-index; } &.mat-drawer-end { right: 0; transform: translate3d(100%, 0, 0); @include token-utils.use-tokens( tokens-mat-sidenav.$prefix, tokens-mat-sidenav.get-token-slots()) { @include token-utils.create-token-slot(border-top-left-radius, container-shape); @include token-utils.create-token-slot(border-bottom-left-radius, container-shape); border-top-right-radius: 0; border-bottom-right-radius: 0; } } [dir='rtl'] & { @include token-utils.use-tokens( tokens-mat-sidenav.$prefix, tokens-mat-sidenav.get-token-slots()) { @include token-utils.create-token-slot(border-top-left-radius, container-shape); @include token-utils.create-token-slot(border-bottom-left-radius, container-shape); border-top-right-radius: 0; border-bottom-right-radius: 0; transform: translate3d(100%, 0, 0); &.mat-drawer-end { @include token-utils.create-token-slot(border-top-right-radius, container-shape); @include token-utils.create-token-slot(border-bottom-right-radius, container-shape); border-top-left-radius: 0; border-bottom-left-radius: 0; left: 0; right: auto; transform: translate3d(-100%, 0, 0); } } } // Usually the `visibility: hidden` added by the animation is enough to prevent focus from // entering the hidden drawer content, but children with their own `visibility` can override it. // This is a fallback that completely hides the content when the element becomes hidden. // Note that we can't do this in the animation definition, because the style gets recomputed too // late, breaking the animation because Angular didn't have time to figure out the target // transform. This can also be achieved with JS, but it has issues when starting an // animation before the previous one has finished. &[style*='visibility: hidden'] { display: none; } } .mat-drawer-side { box-shadow: none; @include token-utils.use-tokens( tokens-mat-sidenav.$prefix, tokens-mat-sidenav.get-token-slots()) { @include token-utils.create-token-slot(border-right-color, container-divider-color); border-right-width: 1px; border-right-style: solid; &.mat-drawer-end { @include token-utils.create-token-slot(border-left-color, container-divider-color); border-left-width: 1px; border-left-style: solid; border-right: none; } [dir='rtl'] & { @include token-utils.create-token-slot(border-left-color, container-divider-color); border-left-width: 1px; border-left-style: solid; border-right: none; // Clears the default LTR border. &.mat-drawer-end { @include token-utils.create-token-slot(border-right-color, container-divider-color); border-right-width: 1px; border-right-style: solid; border-left: none; } } } } // Note that this div isn't strictly necessary on all browsers, however we need it in // order to avoid a layout issue in Chrome. The issue is that in RTL mode the browser doesn't // account for the sidenav's scrollbar while positioning, which ends up pushing it partially // out of the screen. We work around the issue by having the scrollbar be on this inner container. .mat-drawer-inner-container { width: 100%; height: 100%; overflow: auto; -webkit-overflow-scrolling: touch; } .mat-sidenav-fixed { position: fixed; }
{ "commit_id": "ea0d1ba7b", "end_byte": 8343, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.scss" }
components/src/material/sidenav/drawer.html_0_99
<div class="mat-drawer-inner-container" cdkScrollable #content> <ng-content></ng-content> </div>
{ "commit_id": "ea0d1ba7b", "end_byte": 99, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/drawer.html" }
components/src/material/sidenav/sidenav.ts_0_4295
/** * @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 { ChangeDetectionStrategy, Component, ContentChild, ContentChildren, Input, ViewEncapsulation, QueryList, } from '@angular/core'; import {MatDrawer, MatDrawerContainer, MatDrawerContent, MAT_DRAWER_CONTAINER} from './drawer'; import {matDrawerAnimations} from './drawer-animations'; import { BooleanInput, coerceBooleanProperty, coerceNumberProperty, NumberInput, } from '@angular/cdk/coercion'; import {CdkScrollable} from '@angular/cdk/scrolling'; @Component({ selector: 'mat-sidenav-content', template: '<ng-content></ng-content>', host: { 'class': 'mat-drawer-content mat-sidenav-content', '[style.margin-left.px]': '_container._contentMargins.left', '[style.margin-right.px]': '_container._contentMargins.right', }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, providers: [ { provide: CdkScrollable, useExisting: MatSidenavContent, }, ], }) export class MatSidenavContent extends MatDrawerContent {} @Component({ selector: 'mat-sidenav', exportAs: 'matSidenav', templateUrl: 'drawer.html', animations: [matDrawerAnimations.transformDrawer], host: { 'class': 'mat-drawer mat-sidenav', 'tabIndex': '-1', // must prevent the browser from aligning text based on value '[attr.align]': 'null', '[class.mat-drawer-end]': 'position === "end"', '[class.mat-drawer-over]': 'mode === "over"', '[class.mat-drawer-push]': 'mode === "push"', '[class.mat-drawer-side]': 'mode === "side"', '[class.mat-drawer-opened]': 'opened', '[class.mat-sidenav-fixed]': 'fixedInViewport', '[style.top.px]': 'fixedInViewport ? fixedTopGap : null', '[style.bottom.px]': 'fixedInViewport ? fixedBottomGap : null', }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, imports: [CdkScrollable], providers: [{provide: MatDrawer, useExisting: MatSidenav}], }) export class MatSidenav extends MatDrawer { /** Whether the sidenav is fixed in the viewport. */ @Input() get fixedInViewport(): boolean { return this._fixedInViewport; } set fixedInViewport(value: BooleanInput) { this._fixedInViewport = coerceBooleanProperty(value); } private _fixedInViewport = false; /** * The gap between the top of the sidenav and the top of the viewport when the sidenav is in fixed * mode. */ @Input() get fixedTopGap(): number { return this._fixedTopGap; } set fixedTopGap(value: NumberInput) { this._fixedTopGap = coerceNumberProperty(value); } private _fixedTopGap = 0; /** * The gap between the bottom of the sidenav and the bottom of the viewport when the sidenav is in * fixed mode. */ @Input() get fixedBottomGap(): number { return this._fixedBottomGap; } set fixedBottomGap(value: NumberInput) { this._fixedBottomGap = coerceNumberProperty(value); } private _fixedBottomGap = 0; } @Component({ selector: 'mat-sidenav-container', exportAs: 'matSidenavContainer', templateUrl: 'sidenav-container.html', styleUrl: 'drawer.css', host: { 'class': 'mat-drawer-container mat-sidenav-container', '[class.mat-drawer-container-explicit-backdrop]': '_backdropOverride', }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, providers: [ { provide: MAT_DRAWER_CONTAINER, useExisting: MatSidenavContainer, }, { provide: MatDrawerContainer, useExisting: MatSidenavContainer, }, ], imports: [MatSidenavContent], }) export class MatSidenavContainer extends MatDrawerContainer { @ContentChildren(MatSidenav, { // We need to use `descendants: true`, because Ivy will no longer match // indirect descendants if it's left as false. descendants: true, }) // We need an initializer here to avoid a TS error. override _allDrawers: QueryList<MatSidenav> = undefined!; // We need an initializer here to avoid a TS error. @ContentChild(MatSidenavContent) override _content: MatSidenavContent = undefined!; }
{ "commit_id": "ea0d1ba7b", "end_byte": 4295, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/sidenav.ts" }
components/src/material/sidenav/testing/sidenav-harness.spec.ts_0_7533
import {Component, signal} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {HarnessLoader, parallel} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {MatSidenavModule} from '@angular/material/sidenav'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import {MatDrawerContainerHarness} from './drawer-container-harness'; import {MatDrawerContentHarness} from './drawer-content-harness'; import {MatDrawerHarness} from './drawer-harness'; import {MatSidenavContainerHarness} from './sidenav-container-harness'; import {MatSidenavContentHarness} from './sidenav-content-harness'; import {MatSidenavHarness} from './sidenav-harness'; describe('MatSidenavHarness', () => { describe('drawer', () => { let fixture: ComponentFixture<DrawerHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatSidenavModule, NoopAnimationsModule, DrawerHarnessTest], }); fixture = TestBed.createComponent(DrawerHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should load all drawer harnesses', async () => { const drawers = await loader.getAllHarnesses(MatDrawerHarness); expect(drawers.length).toBe(3); }); it('should load drawer harness based on position', async () => { const drawers = await loader.getAllHarnesses(MatDrawerHarness.with({position: 'end'})); expect(drawers.length).toBe(1); expect(await (await drawers[0].host()).text()).toBe('Two'); }); it('should be able to get whether the drawer is open', async () => { const drawers = await loader.getAllHarnesses(MatDrawerHarness); expect(await drawers[0].isOpen()).toBe(false); expect(await drawers[1].isOpen()).toBe(false); expect(await drawers[2].isOpen()).toBe(true); fixture.componentInstance.threeOpened.set(false); fixture.detectChanges(); expect(await drawers[0].isOpen()).toBe(false); expect(await drawers[1].isOpen()).toBe(false); expect(await drawers[2].isOpen()).toBe(false); }); it('should be able to get the position of a drawer', async () => { const drawers = await loader.getAllHarnesses(MatDrawerHarness); expect(await drawers[0].getPosition()).toBe('start'); expect(await drawers[1].getPosition()).toBe('end'); expect(await drawers[2].getPosition()).toBe('start'); }); it('should be able to get the mode of a drawer', async () => { const drawers = await loader.getAllHarnesses(MatDrawerHarness); expect(await drawers[0].getMode()).toBe('over'); expect(await drawers[1].getMode()).toBe('side'); expect(await drawers[2].getMode()).toBe('push'); }); it('should load all drawer container harnesses', async () => { const containers = await loader.getAllHarnesses(MatDrawerContainerHarness); expect(containers.length).toBe(2); }); it('should get the drawers within a container', async () => { const containers = await loader.getAllHarnesses(MatDrawerContainerHarness); const [firstContainerDrawers, secondContainerDrawers] = await parallel(() => { return containers.map(container => container.getDrawers()); }); expect( await parallel(() => { return firstContainerDrawers.map(async container => (await container.host()).text()); }), ).toEqual(['One', 'Two']); expect( await parallel(() => { return secondContainerDrawers.map(async container => (await container.host()).text()); }), ).toEqual(['Three']); }); it('should get the content of a container', async () => { const container = await loader.getHarness(MatDrawerContainerHarness); const content = await container.getContent(); expect(await (await content.host()).text()).toBe('Content'); }); it('should load all drawer content harnesses', async () => { const contentElements = await loader.getAllHarnesses(MatDrawerContentHarness); expect(contentElements.length).toBe(2); }); }); describe('sidenav', () => { let fixture: ComponentFixture<SidenavHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatSidenavModule, NoopAnimationsModule, SidenavHarnessTest], }); fixture = TestBed.createComponent(SidenavHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should be able to get whether a sidenav is fixed in the viewport', async () => { const sidenavs = await loader.getAllHarnesses(MatSidenavHarness); expect(await sidenavs[0].isFixedInViewport()).toBe(false); expect(await sidenavs[1].isFixedInViewport()).toBe(false); expect(await sidenavs[2].isFixedInViewport()).toBe(true); }); it('should load all sidenav container harnesses', async () => { const containers = await loader.getAllHarnesses(MatSidenavContainerHarness); expect(containers.length).toBe(2); }); it('should get the sidenavs within a container', async () => { const containers = await loader.getAllHarnesses(MatSidenavContainerHarness); const [firstContainerSidenavs, secondContainerSidenavs] = await parallel(() => { return containers.map(container => container.getSidenavs()); }); expect( await parallel(() => { return firstContainerSidenavs.map(async container => (await container.host()).text()); }), ).toEqual(['One', 'Two']); expect( await parallel(() => { return secondContainerSidenavs.map(async container => (await container.host()).text()); }), ).toEqual(['Three']); }); it('should get the content of a container', async () => { const container = await loader.getHarness(MatSidenavContainerHarness); const content = await container.getContent(); expect(await (await content.host()).text()).toBe('Content'); }); it('should load all sidenav content harnesses', async () => { const contentElements = await loader.getAllHarnesses(MatSidenavContentHarness); expect(contentElements.length).toBe(2); }); }); }); @Component({ template: ` <mat-drawer-container> <mat-drawer id="one" position="start">One</mat-drawer> <mat-drawer id="two" mode="side" position="end">Two</mat-drawer> <mat-drawer-content>Content</mat-drawer-content> </mat-drawer-container> <mat-drawer-container> <mat-drawer id="three" mode="push" [opened]="threeOpened()">Three</mat-drawer> <mat-drawer-content>Content</mat-drawer-content> </mat-drawer-container> `, standalone: true, imports: [MatSidenavModule], }) class DrawerHarnessTest { threeOpened = signal(true); } @Component({ template: ` <mat-sidenav-container> <mat-sidenav id="one" position="start">One</mat-sidenav> <mat-sidenav id="two" position="end">Two</mat-sidenav> <mat-sidenav-content>Content</mat-sidenav-content> </mat-sidenav-container> <mat-sidenav-container> <mat-sidenav id="three" fixedInViewport>Three</mat-sidenav> <mat-sidenav-content>Content</mat-sidenav-content> </mat-sidenav-container> `, standalone: true, imports: [MatSidenavModule], }) class SidenavHarnessTest {}
{ "commit_id": "ea0d1ba7b", "end_byte": 7533, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/sidenav-harness.spec.ts" }
components/src/material/sidenav/testing/drawer-harness.ts_0_2022
/** * @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 {ContentContainerComponentHarness, HarnessPredicate} from '@angular/cdk/testing'; import {DrawerHarnessFilters} from './drawer-harness-filters'; /** * Base class for the drawer harness functionality. * @docs-private */ export class MatDrawerHarnessBase extends ContentContainerComponentHarness<string> { /** Whether the drawer is open. */ async isOpen(): Promise<boolean> { return (await this.host()).hasClass('mat-drawer-opened'); } /** Gets the position of the drawer inside its container. */ async getPosition(): Promise<'start' | 'end'> { const host = await this.host(); return (await host.hasClass('mat-drawer-end')) ? 'end' : 'start'; } /** Gets the mode that the drawer is in. */ async getMode(): Promise<'over' | 'push' | 'side'> { const host = await this.host(); if (await host.hasClass('mat-drawer-push')) { return 'push'; } if (await host.hasClass('mat-drawer-side')) { return 'side'; } return 'over'; } } /** Harness for interacting with a standard mat-drawer in tests. */ export class MatDrawerHarness extends MatDrawerHarnessBase { /** The selector for the host element of a `MatDrawer` instance. */ static hostSelector = '.mat-drawer'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatDrawerHarness` that meets * certain criteria. * @param options Options for filtering which drawer instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with(options: DrawerHarnessFilters = {}): HarnessPredicate<MatDrawerHarness> { return new HarnessPredicate(MatDrawerHarness, options).addOption( 'position', options.position, async (harness, position) => (await harness.getPosition()) === position, ); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2022, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/drawer-harness.ts" }
components/src/material/sidenav/testing/public-api.ts_0_506
/** * @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 */ export {MatDrawerHarness} from './drawer-harness'; export * from './drawer-container-harness'; export * from './drawer-content-harness'; export * from './drawer-harness-filters'; export * from './sidenav-container-harness'; export * from './sidenav-content-harness'; export * from './sidenav-harness';
{ "commit_id": "ea0d1ba7b", "end_byte": 506, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/public-api.ts" }
components/src/material/sidenav/testing/sidenav-harness.ts_0_1374
/** * @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 {HarnessPredicate} from '@angular/cdk/testing'; import {MatDrawerHarnessBase} from './drawer-harness'; import {DrawerHarnessFilters} from './drawer-harness-filters'; /** Harness for interacting with a standard mat-sidenav in tests. */ export class MatSidenavHarness extends MatDrawerHarnessBase { /** The selector for the host element of a `MatSidenav` instance. */ static hostSelector = '.mat-sidenav'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatSidenavHarness` that meets * certain criteria. * @param options Options for filtering which sidenav instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with(options: DrawerHarnessFilters = {}): HarnessPredicate<MatSidenavHarness> { return new HarnessPredicate(MatSidenavHarness, options).addOption( 'position', options.position, async (harness, position) => (await harness.getPosition()) === position, ); } /** Whether the sidenav is fixed in the viewport. */ async isFixedInViewport(): Promise<boolean> { return (await this.host()).hasClass('mat-sidenav-fixed'); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1374, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/sidenav-harness.ts" }
components/src/material/sidenav/testing/sidenav-content-harness.ts_0_1147
/** * @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 {ContentContainerComponentHarness, HarnessPredicate} from '@angular/cdk/testing'; import {DrawerContentHarnessFilters} from './drawer-harness-filters'; /** Harness for interacting with a standard mat-sidenav-content in tests. */ export class MatSidenavContentHarness extends ContentContainerComponentHarness<string> { /** The selector for the host element of a `MatSidenavContent` instance. */ static hostSelector = '.mat-sidenav-content'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatSidenavContentHarness` that * meets certain criteria. * @param options Options for filtering which sidenav content instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with( options: DrawerContentHarnessFilters = {}, ): HarnessPredicate<MatSidenavContentHarness> { return new HarnessPredicate(MatSidenavContentHarness, options); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1147, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/sidenav-content-harness.ts" }
components/src/material/sidenav/testing/drawer-content-harness.ts_0_1139
/** * @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 {ContentContainerComponentHarness, HarnessPredicate} from '@angular/cdk/testing'; import {DrawerContentHarnessFilters} from './drawer-harness-filters'; /** Harness for interacting with a standard mat-drawer-content in tests. */ export class MatDrawerContentHarness extends ContentContainerComponentHarness<string> { /** The selector for the host element of a `MatDrawerContent` instance. */ static hostSelector = '.mat-drawer-content'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatDrawerContentHarness` that * meets certain criteria. * @param options Options for filtering which drawer content instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with( options: DrawerContentHarnessFilters = {}, ): HarnessPredicate<MatDrawerContentHarness> { return new HarnessPredicate(MatDrawerContentHarness, options); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1139, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/drawer-content-harness.ts" }
components/src/material/sidenav/testing/drawer-container-harness.ts_0_1769
/** * @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 {ContentContainerComponentHarness, HarnessPredicate} from '@angular/cdk/testing'; import {DrawerContainerHarnessFilters, DrawerHarnessFilters} from './drawer-harness-filters'; import {MatDrawerContentHarness} from './drawer-content-harness'; import {MatDrawerHarness} from './drawer-harness'; /** Harness for interacting with a standard mat-drawer-container in tests. */ export class MatDrawerContainerHarness extends ContentContainerComponentHarness<string> { /** The selector for the host element of a `MatDrawerContainer` instance. */ static hostSelector = '.mat-drawer-container'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatDrawerContainerHarness` that * meets certain criteria. * @param options Options for filtering which container instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with( options: DrawerContainerHarnessFilters = {}, ): HarnessPredicate<MatDrawerContainerHarness> { return new HarnessPredicate(MatDrawerContainerHarness, options); } /** * Gets drawers that match particular criteria within the container. * @param filter Optionally filters which chips are included. */ async getDrawers(filter: DrawerHarnessFilters = {}): Promise<MatDrawerHarness[]> { return this.locatorForAll(MatDrawerHarness.with(filter))(); } /** Gets the element that has the container's content. */ async getContent(): Promise<MatDrawerContentHarness> { return this.locatorFor(MatDrawerContentHarness)(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1769, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/drawer-container-harness.ts" }
components/src/material/sidenav/testing/BUILD.bazel_0_752
load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "testing", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src/cdk/coercion", "//src/cdk/testing", ], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), ) ng_test_library( name = "unit_tests_lib", srcs = glob(["**/*.spec.ts"]), deps = [ ":testing", "//src/cdk/testing", "//src/cdk/testing/testbed", "//src/material/sidenav", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_tests_lib"], )
{ "commit_id": "ea0d1ba7b", "end_byte": 752, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/BUILD.bazel" }
components/src/material/sidenav/testing/index.ts_0_234
/** * @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 */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/index.ts" }
components/src/material/sidenav/testing/drawer-harness-filters.ts_0_867
/** * @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 {BaseHarnessFilters} from '@angular/cdk/testing'; /** A set of criteria that can be used to filter a list of `MatDrawerHarness` instances. */ export interface DrawerHarnessFilters extends BaseHarnessFilters { /** Only find instances whose side is the given value. */ position?: 'start' | 'end'; } /** A set of criteria that can be used to filter a list of `MatDrawerContainerHarness` instances. */ export interface DrawerContainerHarnessFilters extends BaseHarnessFilters {} /** A set of criteria that can be used to filter a list of `MatDrawerContentHarness` instances. */ export interface DrawerContentHarnessFilters extends BaseHarnessFilters {}
{ "commit_id": "ea0d1ba7b", "end_byte": 867, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/drawer-harness-filters.ts" }
components/src/material/sidenav/testing/sidenav-container-harness.ts_0_1786
/** * @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 {ContentContainerComponentHarness, HarnessPredicate} from '@angular/cdk/testing'; import {DrawerContainerHarnessFilters, DrawerHarnessFilters} from './drawer-harness-filters'; import {MatSidenavContentHarness} from './sidenav-content-harness'; import {MatSidenavHarness} from './sidenav-harness'; /** Harness for interacting with a standard mat-sidenav-container in tests. */ export class MatSidenavContainerHarness extends ContentContainerComponentHarness<string> { /** The selector for the host element of a `MatSidenavContainer` instance. */ static hostSelector = '.mat-sidenav-container'; /** * Gets a `HarnessPredicate` that can be used to search for a `MatSidenavContainerHarness` that * meets certain criteria. * @param options Options for filtering which container instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with( options: DrawerContainerHarnessFilters = {}, ): HarnessPredicate<MatSidenavContainerHarness> { return new HarnessPredicate(MatSidenavContainerHarness, options); } /** * Gets sidenavs that match particular criteria within the container. * @param filter Optionally filters which chips are included. */ async getSidenavs(filter: DrawerHarnessFilters = {}): Promise<MatSidenavHarness[]> { return this.locatorForAll(MatSidenavHarness.with(filter))(); } /** Gets the element that has the container's content. */ async getContent(): Promise<MatSidenavContentHarness> { return this.locatorFor(MatSidenavContentHarness)(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 1786, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/sidenav/testing/sidenav-container-harness.ts" }
components/src/material/radio/radio.md_0_2494
`<mat-radio-button>` provides the same functionality as a native `<input type="radio">` enhanced with Material Design styling and animations. <!-- example(radio-overview) --> All radio-buttons with the same `name` comprise a set from which only one may be selected at a time. ### Radio-button label The radio-button label is provided as the content to the `<mat-radio-button>` element. The label can be positioned before or after the radio-button by setting the `labelPosition` property to `'before'` or `'after'`. If you don't want the label to appear next to the radio-button, you can use [`aria-label`](https://www.w3.org/TR/wai-aria/states_and_properties#aria-label) or [`aria-labelledby`](https://www.w3.org/TR/wai-aria/states_and_properties#aria-labelledby) to specify an appropriate label. ### Radio groups Radio-buttons should typically be placed inside of an `<mat-radio-group>` unless the DOM structure would make that impossible (e.g., radio-buttons inside of table cells). The radio-group has a `value` property that reflects the currently selected radio-button inside of the group. Individual radio-buttons inside of a radio-group will inherit the `name` of the group. ### Use with `@angular/forms` `<mat-radio-group>` is compatible with `@angular/forms` and supports both `FormsModule` and `ReactiveFormsModule`. ### Accessibility `MatRadioButton` uses an internal `<input type="radio">` to provide an accessible experience. This internal radio button receives focus and is automatically labelled by the text content of the `<mat-radio-button>` element. Avoid adding other interactive controls into the content of `<mat-radio-button>`, as this degrades the experience for users of assistive technology. Always provide an accessible label via `aria-label` or `aria-labelledby` for radio buttons without descriptive text content. For dynamic labels and descriptions, `MatRadioButton` provides input properties for binding `aria-label`, `aria-labelledby`, and `aria-describedby`. This means that you should not use the `attr.` prefix when binding these properties, as demonstrated below. ```html <mat-radio-button [aria-label]="getMultipleChoiceAnswer()"> </mat-radio-button> ``` Prefer placing all radio buttons inside of a `<mat-radio-group>` rather than creating standalone radio buttons because groups are easier to use exclusively with a keyboard. You should provide an accessible label for all `<mat-radio-group>` elements via `aria-label` or `aria-labelledby`.
{ "commit_id": "ea0d1ba7b", "end_byte": 2494, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.md" }
components/src/material/radio/_radio-common.scss_0_7902
@use '../core/tokens/m2/mdc/radio' as tokens-mdc-radio; @use '../core/tokens/token-utils'; $_icon-size: 20px; @function _enter-transition($name) { @return $name 90ms cubic-bezier(0, 0, 0.2, 1); } @function _exit-transition($name) { @return $name 90ms cubic-bezier(0.4, 0, 0.6, 1); } // Structural styles for a radio button. Shared with the selection list. @mixin radio-structure($is-interactive) { $tokens: tokens-mdc-radio.$prefix, tokens-mdc-radio.get-token-slots(); .mdc-radio { display: inline-block; position: relative; flex: 0 0 auto; box-sizing: content-box; width: $_icon-size; height: $_icon-size; cursor: pointer; // This is something we inherited from MDC, but it shouldn't be necessary. // Removing it will likely lead to screenshot diffs. will-change: opacity, transform, border-color, color; @include token-utils.use-tokens($tokens...) { $size-token: token-utils.get-token-variable(state-layer-size); padding: calc((#{$size-token} - #{$_icon-size}) / 2); } @if ($is-interactive) { // MDC's hover indication comes from their ripple which we don't use. &:hover .mdc-radio__native-control:not([disabled]):not(:focus) { & ~ .mdc-radio__background::before { opacity: 0.04; transform: scale(1); } } &:hover .mdc-radio__native-control:not([disabled]) ~ .mdc-radio__background { .mdc-radio__outer-circle { @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(border-color, unselected-hover-icon-color); } } } &:hover .mdc-radio__native-control:enabled:checked + .mdc-radio__background { .mdc-radio__outer-circle, .mdc-radio__inner-circle { @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(border-color, selected-hover-icon-color); } } } &:active .mdc-radio__native-control:enabled:not(:checked) + .mdc-radio__background { .mdc-radio__outer-circle { @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(border-color, unselected-pressed-icon-color); } } } &:active .mdc-radio__native-control:enabled:checked + .mdc-radio__background { .mdc-radio__outer-circle, .mdc-radio__inner-circle { @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(border-color, selected-pressed-icon-color); } } } } } .mdc-radio__background { display: inline-block; position: relative; box-sizing: border-box; width: $_icon-size; height: $_icon-size; &::before { position: absolute; transform: scale(0, 0); border-radius: 50%; opacity: 0; pointer-events: none; content: ''; transition: _exit-transition(opacity), _exit-transition(transform); @include token-utils.use-tokens($tokens...) { $size: token-utils.get-token-variable(state-layer-size); $offset: calc(-1 * (#{$size} - #{$_icon-size}) / 2); width: $size; height: $size; top: $offset; left: $offset; } } } .mdc-radio__outer-circle { position: absolute; top: 0; left: 0; box-sizing: border-box; width: 100%; height: 100%; border-width: 2px; border-style: solid; border-radius: 50%; transition: _exit-transition(border-color); } .mdc-radio__inner-circle { position: absolute; top: 0; left: 0; box-sizing: border-box; width: 100%; height: 100%; transform: scale(0, 0); border-width: 10px; border-style: solid; border-radius: 50%; transition: _exit-transition(transform), _exit-transition(border-color); } .mdc-radio__native-control { position: absolute; margin: 0; padding: 0; opacity: 0; top: 0; right: 0; left: 0; cursor: inherit; z-index: 1; @include token-utils.use-tokens($tokens...) { @include token-utils.create-token-slot(width, state-layer-size); @include token-utils.create-token-slot(height, state-layer-size); } &:checked, &:disabled { + .mdc-radio__background { transition: _enter-transition(opacity), _enter-transition(transform); .mdc-radio__outer-circle { transition: _enter-transition(border-color); } .mdc-radio__inner-circle { transition: _enter-transition(transform), _enter-transition(border-color); } } } @if ($is-interactive) { &:focus + .mdc-radio__background::before { transform: scale(1); opacity: 0.12; transition: _enter-transition(opacity), _enter-transition(transform); } } &:disabled { @include token-utils.use-tokens($tokens...) { &:not(:checked) + .mdc-radio__background .mdc-radio__outer-circle { @include token-utils.create-token-slot(border-color, disabled-unselected-icon-color); @include token-utils.create-token-slot(opacity, disabled-unselected-icon-opacity); } + .mdc-radio__background { cursor: default; .mdc-radio__inner-circle, .mdc-radio__outer-circle { @include token-utils.create-token-slot(border-color, disabled-selected-icon-color); @include token-utils.create-token-slot(opacity, disabled-selected-icon-opacity); } } } } &:enabled { @include token-utils.use-tokens($tokens...) { &:not(:checked) + .mdc-radio__background .mdc-radio__outer-circle { @include token-utils.create-token-slot(border-color, unselected-icon-color); } &:checked + .mdc-radio__background { .mdc-radio__outer-circle, .mdc-radio__inner-circle { @include token-utils.create-token-slot(border-color, selected-icon-color); } } @if ($is-interactive) { &:focus:checked + .mdc-radio__background { .mdc-radio__inner-circle, .mdc-radio__outer-circle { @include token-utils.create-token-slot(border-color, selected-focus-icon-color); } } } } } &:checked + .mdc-radio__background .mdc-radio__inner-circle { transform: scale(0.5); transition: _enter-transition(transform), _enter-transition(border-color); } } @if ($is-interactive) { &.mat-mdc-radio-disabled-interactive .mdc-radio--disabled { pointer-events: auto; @include token-utils.use-tokens($tokens...) { .mdc-radio__native-control:not(:checked) + .mdc-radio__background .mdc-radio__outer-circle { @include token-utils.create-token-slot(border-color, disabled-unselected-icon-color); @include token-utils.create-token-slot(opacity, disabled-unselected-icon-opacity); } &:hover .mdc-radio__native-control:checked + .mdc-radio__background, .mdc-radio__native-control:checked:focus + .mdc-radio__background, .mdc-radio__native-control + .mdc-radio__background { .mdc-radio__inner-circle, .mdc-radio__outer-circle { @include token-utils.create-token-slot(border-color, disabled-selected-icon-color); @include token-utils.create-token-slot(opacity, disabled-selected-icon-opacity); } } } } } } // Conditionally disables the animations of the radio button. @mixin radio-noop-animations() { &._mat-animation-noopable { .mdc-radio__background::before, .mdc-radio__outer-circle, .mdc-radio__inner-circle { // Needs to be `!important`, because MDC's selectors are really specific. transition: none !important; } } }
{ "commit_id": "ea0d1ba7b", "end_byte": 7902, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/_radio-common.scss" }
components/src/material/radio/module.ts_0_558
/** * @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, MatRippleModule} from '@angular/material/core'; import {MatRadioButton, MatRadioGroup} from './radio'; @NgModule({ imports: [MatCommonModule, MatRippleModule, MatRadioGroup, MatRadioButton], exports: [MatCommonModule, MatRadioGroup, MatRadioButton], }) export class MatRadioModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 558, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/module.ts" }
components/src/material/radio/radio.ts_0_2988
/** * @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 {FocusMonitor, FocusOrigin} from '@angular/cdk/a11y'; import {UniqueSelectionDispatcher} from '@angular/cdk/collections'; import { ANIMATION_MODULE_TYPE, AfterContentInit, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, Directive, DoCheck, ElementRef, EventEmitter, InjectionToken, Injector, Input, NgZone, OnDestroy, OnInit, Output, QueryList, ViewChild, ViewEncapsulation, afterNextRender, booleanAttribute, forwardRef, inject, numberAttribute, HostAttributeToken, } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import { MatRipple, ThemePalette, _MatInternalFormField, _StructuralStylesLoader, } from '@angular/material/core'; import {Subscription} from 'rxjs'; import {_CdkPrivateStyleLoader} from '@angular/cdk/private'; // Increasing integer for generating unique ids for radio components. let nextUniqueId = 0; /** Change event object emitted by radio button and radio group. */ export class MatRadioChange { constructor( /** The radio button that emits the change event. */ public source: MatRadioButton, /** The value of the radio button. */ public value: any, ) {} } /** * Provider Expression that allows mat-radio-group to register as a ControlValueAccessor. This * allows it to support [(ngModel)] and ngControl. * @docs-private */ export const MAT_RADIO_GROUP_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MatRadioGroup), multi: true, }; /** * Injection token that can be used to inject instances of `MatRadioGroup`. It serves as * alternative token to the actual `MatRadioGroup` class which could cause unnecessary * retention of the class and its component metadata. */ export const MAT_RADIO_GROUP = new InjectionToken<MatRadioGroup>('MatRadioGroup'); export interface MatRadioDefaultOptions { /** * Theme color of the radio button. 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. */ color: ThemePalette; /** Whether disabled radio buttons should be interactive. */ disabledInteractive?: boolean; } export const MAT_RADIO_DEFAULT_OPTIONS = new InjectionToken<MatRadioDefaultOptions>( 'mat-radio-default-options', { providedIn: 'root', factory: MAT_RADIO_DEFAULT_OPTIONS_FACTORY, }, ); export function MAT_RADIO_DEFAULT_OPTIONS_FACTORY(): MatRadioDefaultOptions { return { color: 'accent', disabledInteractive: false, }; } /** * A group of radio buttons. May contain one or more `<mat-radio-button>` elements. */
{ "commit_id": "ea0d1ba7b", "end_byte": 2988, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.ts" }
components/src/material/radio/radio.ts_2989_11284
@Directive({ selector: 'mat-radio-group', exportAs: 'matRadioGroup', providers: [ MAT_RADIO_GROUP_CONTROL_VALUE_ACCESSOR, {provide: MAT_RADIO_GROUP, useExisting: MatRadioGroup}, ], host: { 'role': 'radiogroup', 'class': 'mat-mdc-radio-group', }, }) export class MatRadioGroup implements AfterContentInit, OnDestroy, ControlValueAccessor { private _changeDetector = inject(ChangeDetectorRef); /** Selected value for the radio group. */ private _value: any = null; /** The HTML name attribute applied to radio buttons in this group. */ private _name: string = `mat-radio-group-${nextUniqueId++}`; /** The currently selected radio button. Should match value. */ private _selected: MatRadioButton | null = null; /** Whether the `value` has been set to its initial value. */ private _isInitialized: boolean = false; /** Whether the labels should appear after or before the radio-buttons. Defaults to 'after' */ private _labelPosition: 'before' | 'after' = 'after'; /** Whether the radio group is disabled. */ private _disabled: boolean = false; /** Whether the radio group is required. */ private _required: boolean = false; /** Subscription to changes in amount of radio buttons. */ private _buttonChanges: Subscription; /** The method to be called in order to update ngModel */ _controlValueAccessorChangeFn: (value: any) => void = () => {}; /** * onTouch function registered via registerOnTouch (ControlValueAccessor). * @docs-private */ onTouched: () => any = () => {}; /** * Event emitted when the group value changes. * Change events are only emitted when the value changes due to user interaction with * a radio button (the same behavior as `<input type-"radio">`). */ @Output() readonly change: EventEmitter<MatRadioChange> = new EventEmitter<MatRadioChange>(); /** Child radio buttons. */ @ContentChildren(forwardRef(() => MatRadioButton), {descendants: true}) _radios: QueryList<MatRadioButton>; /** * Theme color of the radio buttons in the group. 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: ThemePalette; /** Name of the radio button group. All radio buttons inside this group will use this name. */ @Input() get name(): string { return this._name; } set name(value: string) { this._name = value; this._updateRadioButtonNames(); } /** Whether the labels should appear after or before the radio-buttons. Defaults to 'after' */ @Input() get labelPosition(): 'before' | 'after' { return this._labelPosition; } set labelPosition(v) { this._labelPosition = v === 'before' ? 'before' : 'after'; this._markRadiosForCheck(); } /** * Value for the radio-group. Should equal the value of the selected radio button if there is * a corresponding radio button with a matching value. If there is not such a corresponding * radio button, this value persists to be applied in case a new radio button is added with a * matching value. */ @Input() get value(): any { return this._value; } set value(newValue: any) { if (this._value !== newValue) { // Set this before proceeding to ensure no circular loop occurs with selection. this._value = newValue; this._updateSelectedRadioFromValue(); this._checkSelectedRadioButton(); } } _checkSelectedRadioButton() { if (this._selected && !this._selected.checked) { this._selected.checked = true; } } /** * The currently selected radio button. If set to a new radio button, the radio group value * will be updated to match the new selected button. */ @Input() get selected() { return this._selected; } set selected(selected: MatRadioButton | null) { this._selected = selected; this.value = selected ? selected.value : null; this._checkSelectedRadioButton(); } /** Whether the radio group is disabled */ @Input({transform: booleanAttribute}) get disabled(): boolean { return this._disabled; } set disabled(value: boolean) { this._disabled = value; this._markRadiosForCheck(); } /** Whether the radio group is required */ @Input({transform: booleanAttribute}) get required(): boolean { return this._required; } set required(value: boolean) { this._required = value; this._markRadiosForCheck(); } /** Whether buttons in the group should be interactive while they're disabled. */ @Input({transform: booleanAttribute}) get disabledInteractive(): boolean { return this._disabledInteractive; } set disabledInteractive(value: boolean) { this._disabledInteractive = value; this._markRadiosForCheck(); } private _disabledInteractive = false; constructor(...args: unknown[]); constructor() {} /** * Initialize properties once content children are available. * This allows us to propagate relevant attributes to associated buttons. */ ngAfterContentInit() { // Mark this component as initialized in AfterContentInit because the initial value can // possibly be set by NgModel on MatRadioGroup, and it is possible that the OnInit of the // NgModel occurs *after* the OnInit of the MatRadioGroup. this._isInitialized = true; // Clear the `selected` button when it's destroyed since the tabindex of the rest of the // buttons depends on it. Note that we don't clear the `value`, because the radio button // may be swapped out with a similar one and there are some internal apps that depend on // that behavior. this._buttonChanges = this._radios.changes.subscribe(() => { if (this.selected && !this._radios.find(radio => radio === this.selected)) { this._selected = null; } }); } ngOnDestroy() { this._buttonChanges?.unsubscribe(); } /** * Mark this group as being "touched" (for ngModel). Meant to be called by the contained * radio buttons upon their blur. */ _touch() { if (this.onTouched) { this.onTouched(); } } private _updateRadioButtonNames(): void { if (this._radios) { this._radios.forEach(radio => { radio.name = this.name; radio._markForCheck(); }); } } /** Updates the `selected` radio button from the internal _value state. */ private _updateSelectedRadioFromValue(): void { // If the value already matches the selected radio, do nothing. const isAlreadySelected = this._selected !== null && this._selected.value === this._value; if (this._radios && !isAlreadySelected) { this._selected = null; this._radios.forEach(radio => { radio.checked = this.value === radio.value; if (radio.checked) { this._selected = radio; } }); } } /** Dispatch change event with current selection and group value. */ _emitChangeEvent(): void { if (this._isInitialized) { this.change.emit(new MatRadioChange(this._selected!, this._value)); } } _markRadiosForCheck() { if (this._radios) { this._radios.forEach(radio => radio._markForCheck()); } } /** * Sets the model value. Implemented as part of ControlValueAccessor. * @param value */ writeValue(value: any) { this.value = value; this._changeDetector.markForCheck(); } /** * Registers a callback to be triggered when the model value changes. * Implemented as part of ControlValueAccessor. * @param fn Callback to be registered. */ registerOnChange(fn: (value: any) => void) { this._controlValueAccessorChangeFn = fn; } /** * Registers a callback to be triggered when the control is touched. * Implemented as part of ControlValueAccessor. * @param fn Callback to be registered. */ registerOnTouched(fn: any) { this.onTouched = fn; } /** * Sets the disabled state of the control. Implemented as a part of ControlValueAccessor. * @param isDisabled Whether the control should be disabled. */ setDisabledState(isDisabled: boolean) { this.disabled = isDisabled; this._changeDetector.markForCheck(); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 11284, "start_byte": 2989, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.ts" }
components/src/material/radio/radio.ts_11286_12508
@Component({ selector: 'mat-radio-button', templateUrl: 'radio.html', styleUrl: 'radio.css', host: { 'class': 'mat-mdc-radio-button', '[attr.id]': 'id', '[class.mat-primary]': 'color === "primary"', '[class.mat-accent]': 'color === "accent"', '[class.mat-warn]': 'color === "warn"', '[class.mat-mdc-radio-checked]': 'checked', '[class.mat-mdc-radio-disabled]': 'disabled', '[class.mat-mdc-radio-disabled-interactive]': 'disabledInteractive', '[class._mat-animation-noopable]': '_noopAnimations', // Needs to be removed since it causes some a11y issues (see #21266). '[attr.tabindex]': 'null', '[attr.aria-label]': 'null', '[attr.aria-labelledby]': 'null', '[attr.aria-describedby]': 'null', // Note: under normal conditions focus shouldn't land on this element, however it may be // programmatically set, for example inside of a focus trap, in this case we want to forward // the focus to the native element. '(focus)': '_inputElement.nativeElement.focus()', }, exportAs: 'matRadioButton', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, imports: [MatRipple, _MatInternalFormField], }) export
{ "commit_id": "ea0d1ba7b", "end_byte": 12508, "start_byte": 11286, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.ts" }
components/src/material/radio/radio.ts_12509_20829
class MatRadioButton implements OnInit, AfterViewInit, DoCheck, OnDestroy { protected _elementRef = inject(ElementRef); private _changeDetector = inject(ChangeDetectorRef); private _focusMonitor = inject(FocusMonitor); private _radioDispatcher = inject(UniqueSelectionDispatcher); private _defaultOptions = inject<MatRadioDefaultOptions>(MAT_RADIO_DEFAULT_OPTIONS, { optional: true, }); private _ngZone = inject(NgZone); private _uniqueId: string = `mat-radio-${++nextUniqueId}`; /** The unique ID for the radio button. */ @Input() id: string = this._uniqueId; /** Analog to HTML 'name' attribute used to group radios for unique selection. */ @Input() name: string; /** Used to set the 'aria-label' attribute on the underlying input element. */ @Input('aria-label') ariaLabel: string; /** The 'aria-labelledby' attribute takes precedence as the element's text alternative. */ @Input('aria-labelledby') ariaLabelledby: string; /** The 'aria-describedby' attribute is read after the element's label and field type. */ @Input('aria-describedby') ariaDescribedby: string; /** Whether ripples are disabled inside the radio button */ @Input({transform: booleanAttribute}) disableRipple: boolean = false; /** Tabindex of the radio button. */ @Input({ transform: (value: unknown) => (value == null ? 0 : numberAttribute(value)), }) tabIndex: number = 0; /** Whether this radio button is checked. */ @Input({transform: booleanAttribute}) get checked(): boolean { return this._checked; } set checked(value: boolean) { if (this._checked !== value) { this._checked = value; if (value && this.radioGroup && this.radioGroup.value !== this.value) { this.radioGroup.selected = this; } else if (!value && this.radioGroup && this.radioGroup.value === this.value) { // When unchecking the selected radio button, update the selected radio // property on the group. this.radioGroup.selected = null; } if (value) { // Notify all radio buttons with the same name to un-check. this._radioDispatcher.notify(this.id, this.name); } this._changeDetector.markForCheck(); } } /** The value of this radio button. */ @Input() get value(): any { return this._value; } set value(value: any) { if (this._value !== value) { this._value = value; if (this.radioGroup !== null) { if (!this.checked) { // Update checked when the value changed to match the radio group's value this.checked = this.radioGroup.value === value; } if (this.checked) { this.radioGroup.selected = this; } } } } /** Whether the label should appear after or before the radio button. Defaults to 'after' */ @Input() get labelPosition(): 'before' | 'after' { return this._labelPosition || (this.radioGroup && this.radioGroup.labelPosition) || 'after'; } set labelPosition(value) { this._labelPosition = value; } private _labelPosition: 'before' | 'after'; /** Whether the radio button is disabled. */ @Input({transform: booleanAttribute}) get disabled(): boolean { return this._disabled || (this.radioGroup !== null && this.radioGroup.disabled); } set disabled(value: boolean) { this._setDisabled(value); } /** Whether the radio button is required. */ @Input({transform: booleanAttribute}) get required(): boolean { return this._required || (this.radioGroup && this.radioGroup.required); } set required(value: boolean) { this._required = value; } /** * Theme color of the radio button. 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 { // As per M2 design specifications the selection control radio should use the accent color // palette by default. https://m2.material.io/components/radio-buttons#specs return ( this._color || (this.radioGroup && this.radioGroup.color) || (this._defaultOptions && this._defaultOptions.color) || 'accent' ); } set color(newValue: ThemePalette) { this._color = newValue; } private _color: ThemePalette; /** Whether the radio button should remain interactive when it is disabled. */ @Input({transform: booleanAttribute}) get disabledInteractive(): boolean { return ( this._disabledInteractive || (this.radioGroup !== null && this.radioGroup.disabledInteractive) ); } set disabledInteractive(value: boolean) { this._disabledInteractive = value; } private _disabledInteractive: boolean; /** * Event emitted when the checked state of this radio button changes. * Change events are only emitted when the value changes due to user interaction with * the radio button (the same behavior as `<input type-"radio">`). */ @Output() readonly change: EventEmitter<MatRadioChange> = new EventEmitter<MatRadioChange>(); /** The parent radio group. May or may not be present. */ radioGroup: MatRadioGroup; /** ID of the native input element inside `<mat-radio-button>` */ get inputId(): string { return `${this.id || this._uniqueId}-input`; } /** Whether this radio is checked. */ private _checked: boolean = false; /** Whether this radio is disabled. */ private _disabled: boolean; /** Whether this radio is required. */ private _required: boolean; /** Value assigned to this radio. */ private _value: any = null; /** Unregister function for _radioDispatcher */ private _removeUniqueSelectionListener: () => void = () => {}; /** Previous value of the input's tabindex. */ private _previousTabIndex: number | undefined; /** The native `<input type=radio>` element */ @ViewChild('input') _inputElement: ElementRef<HTMLInputElement>; /** Trigger elements for the ripple events. */ @ViewChild('formField', {read: ElementRef, static: true}) _rippleTrigger: ElementRef<HTMLElement>; /** Whether animations are disabled. */ _noopAnimations: boolean; private _injector = inject(Injector); constructor(...args: unknown[]); constructor() { inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader); const radioGroup = inject<MatRadioGroup>(MAT_RADIO_GROUP, {optional: true})!; const animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true}); const tabIndex = inject(new HostAttributeToken('tabindex'), {optional: true}); // Assertions. Ideally these should be stripped out by the compiler. // TODO(jelbourn): Assert that there's no name binding AND a parent radio group. this.radioGroup = radioGroup; this._noopAnimations = animationMode === 'NoopAnimations'; this._disabledInteractive = this._defaultOptions?.disabledInteractive ?? false; if (tabIndex) { this.tabIndex = numberAttribute(tabIndex, 0); } } /** Focuses the radio button. */ focus(options?: FocusOptions, origin?: FocusOrigin): void { if (origin) { this._focusMonitor.focusVia(this._inputElement, origin, options); } else { this._inputElement.nativeElement.focus(options); } } /** * Marks the radio button as needing checking for change detection. * This method is exposed because the parent radio group will directly * update bound properties of the radio button. */ _markForCheck() { // When group value changes, the button will not be notified. Use `markForCheck` to explicit // update radio button's status this._changeDetector.markForCheck(); } ngOnInit() { if (this.radioGroup) { // If the radio is inside a radio group, determine if it should be checked this.checked = this.radioGroup.value === this._value; if (this.checked) { this.radioGroup.selected = this; } // Copy name from parent radio group this.name = this.radioGroup.name; } this._removeUniqueSelectionListener = this._radioDispatcher.listen((id, name) => { if (id !== this.id && name === this.name) { this.checked = false; } }); } ngDoCheck(): void { this._updateTabIndex(); }
{ "commit_id": "ea0d1ba7b", "end_byte": 20829, "start_byte": 12509, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.ts" }
components/src/material/radio/radio.ts_20833_26283
ngAfterViewInit() { this._updateTabIndex(); this._focusMonitor.monitor(this._elementRef, true).subscribe(focusOrigin => { if (!focusOrigin && this.radioGroup) { this.radioGroup._touch(); } }); // We bind this outside of the zone, because: // 1. Its logic is completely DOM-related so we can avoid some change detections. // 2. There appear to be some internal tests that break when this triggers a change detection. this._ngZone.runOutsideAngular(() => { this._inputElement.nativeElement.addEventListener('click', this._onInputClick); }); } ngOnDestroy() { // We need to null check in case the button was destroyed before `ngAfterViewInit`. this._inputElement?.nativeElement.removeEventListener('click', this._onInputClick); this._focusMonitor.stopMonitoring(this._elementRef); this._removeUniqueSelectionListener(); } /** Dispatch change event with current value. */ private _emitChangeEvent(): void { this.change.emit(new MatRadioChange(this, this._value)); } _isRippleDisabled() { return this.disableRipple || this.disabled; } /** Triggered when the radio button receives an interaction from the user. */ _onInputInteraction(event: Event) { // We always have to stop propagation on the change event. // Otherwise the change event, from the input element, will bubble up and // emit its event object to the `change` output. event.stopPropagation(); if (!this.checked && !this.disabled) { const groupValueChanged = this.radioGroup && this.value !== this.radioGroup.value; this.checked = true; this._emitChangeEvent(); if (this.radioGroup) { this.radioGroup._controlValueAccessorChangeFn(this.value); if (groupValueChanged) { this.radioGroup._emitChangeEvent(); } } } } /** Triggered when the user clicks on the touch target. */ _onTouchTargetClick(event: Event) { this._onInputInteraction(event); if (!this.disabled || this.disabledInteractive) { // Normally the input should be focused already, but if the click // comes from the touch target, then we might have to focus it ourselves. this._inputElement?.nativeElement.focus(); } } /** Sets the disabled state and marks for check if a change occurred. */ protected _setDisabled(value: boolean) { if (this._disabled !== value) { this._disabled = value; this._changeDetector.markForCheck(); } } /** Called when the input is clicked. */ private _onInputClick = (event: Event) => { // If the input is disabled while interactive, we need to prevent the // selection from happening in this event handler. Note that even though // this happens on `click` events, the logic applies when the user is // navigating with the keyboard as well. An alternative way of doing // this is by resetting the `checked` state in the `change` callback but // it isn't optimal, because it can allow a pre-checked disabled button // to be un-checked. This approach seems to cover everything. if (this.disabled && this.disabledInteractive) { event.preventDefault(); } }; /** Gets the tabindex for the underlying input element. */ private _updateTabIndex() { const group = this.radioGroup; let value: number; // Implement a roving tabindex if the button is inside a group. For most cases this isn't // necessary, because the browser handles the tab order for inputs inside a group automatically, // but we need an explicitly higher tabindex for the selected button in order for things like // the focus trap to pick it up correctly. if (!group || !group.selected || this.disabled) { value = this.tabIndex; } else { value = group.selected === this ? this.tabIndex : -1; } if (value !== this._previousTabIndex) { // We have to set the tabindex directly on the DOM node, because it depends on // the selected state which is prone to "changed after checked errors". const input: HTMLInputElement | undefined = this._inputElement?.nativeElement; if (input) { input.setAttribute('tabindex', value + ''); this._previousTabIndex = value; // Wait for any pending tabindex changes to be applied afterNextRender( () => { queueMicrotask(() => { // The radio group uses a "selection follows focus" pattern for tab management, so if this // radio button is currently focused and another radio button in the group becomes // selected, we should move focus to the newly selected radio button to maintain // consistency between the focused and selected states. if ( group && group.selected && group.selected !== this && document.activeElement === input ) { group.selected?._inputElement.nativeElement.focus(); // If this radio button still has focus, the selected one must be disabled. In this // case the radio group as a whole should lose focus. if (document.activeElement === input) { this._inputElement.nativeElement.blur(); } } }); }, {injector: this._injector}, ); } } } }
{ "commit_id": "ea0d1ba7b", "end_byte": 26283, "start_byte": 20833, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.ts" }
components/src/material/radio/radio.html_0_1390
<div mat-internal-form-field [labelPosition]="labelPosition" #formField> <div class="mdc-radio" [class.mdc-radio--disabled]="disabled"> <!-- Render this element first so the input is on top. --> <div class="mat-mdc-radio-touch-target" (click)="_onTouchTargetClick($event)"></div> <input #input class="mdc-radio__native-control" type="radio" [id]="inputId" [checked]="checked" [disabled]="disabled && !disabledInteractive" [attr.name]="name" [attr.value]="value" [required]="required" [attr.aria-label]="ariaLabel" [attr.aria-labelledby]="ariaLabelledby" [attr.aria-describedby]="ariaDescribedby" [attr.aria-disabled]="disabled && disabledInteractive ? 'true' : null" (change)="_onInputInteraction($event)"> <div class="mdc-radio__background"> <div class="mdc-radio__outer-circle"></div> <div class="mdc-radio__inner-circle"></div> </div> <div mat-ripple class="mat-radio-ripple mat-focus-indicator" [matRippleTrigger]="_rippleTrigger.nativeElement" [matRippleDisabled]="_isRippleDisabled()" [matRippleCentered]="true"> <div class="mat-ripple-element mat-radio-persistent-ripple"></div> </div> </div> <label class="mdc-label" [for]="inputId"> <ng-content></ng-content> </label> </div>
{ "commit_id": "ea0d1ba7b", "end_byte": 1390, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.html" }
components/src/material/radio/public-api.ts_0_255
/** * @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 */ export * from './radio'; export * from './module';
{ "commit_id": "ea0d1ba7b", "end_byte": 255, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/public-api.ts" }
components/src/material/radio/radio.scss_0_3352
@use '../core/tokens/m2/mat/radio' as tokens-mat-radio; @use '../core/tokens/m2/mdc/radio' as tokens-mdc-radio; @use '../core/tokens/token-utils'; @use '../core/style/layout-common'; @use './radio-common'; .mat-mdc-radio-button { -webkit-tap-highlight-color: transparent; @include radio-common.radio-structure(true); @include radio-common.radio-noop-animations(); @include token-utils.use-tokens(tokens-mat-radio.$prefix, tokens-mat-radio.get-token-slots()) { .mdc-radio__background::before { @include token-utils.create-token-slot(background-color, ripple-color); } &.mat-mdc-radio-checked { .mat-ripple-element, .mdc-radio__background::before { @include token-utils.create-token-slot(background-color, checked-ripple-color); } } &.mat-mdc-radio-disabled-interactive .mdc-radio--disabled { .mat-ripple-element, .mdc-radio__background::before { @include token-utils.create-token-slot(background-color, ripple-color); } } .mat-internal-form-field { @include token-utils.create-token-slot(color, label-text-color); @include token-utils.create-token-slot(font-family, label-text-font); @include token-utils.create-token-slot(line-height, label-text-line-height); @include token-utils.create-token-slot(font-size, label-text-size); @include token-utils.create-token-slot(letter-spacing, label-text-tracking); @include token-utils.create-token-slot(font-weight, label-text-weight); } .mdc-radio--disabled + label { @include token-utils.create-token-slot(color, disabled-label-color); } } // This is necessary because we do not depend on MDC's ripple, but have our own that should be // positioned correctly. This can be removed once we start using MDC's ripple implementation. .mat-radio-ripple { @include layout-common.fill; pointer-events: none; border-radius: 50%; .mat-ripple-element { opacity: 0.14; } &::before { border-radius: 50%; } } // We don't inherit the border focus style from MDC since we don't use their ripple. // Instead we need to replicate it here. @include token-utils.use-tokens(tokens-mdc-radio.$prefix, tokens-mdc-radio.get-token-slots()) { .mdc-radio .mdc-radio__native-control:focus:enabled:not(:checked) { & ~ .mdc-radio__background .mdc-radio__outer-circle { @include token-utils.create-token-slot(border-color, unselected-focus-icon-color); } } } // For radios render the focus indicator when we know // the hidden input is focused (slightly different for each control). &.cdk-focused .mat-focus-indicator::before { content: ''; } } .mat-mdc-radio-disabled { cursor: default; pointer-events: none; &.mat-mdc-radio-disabled-interactive { pointer-events: auto; } } // Element used to provide a larger tap target for users on touch devices. .mat-mdc-radio-touch-target { position: absolute; top: 50%; left: 50%; height: 48px; width: 48px; transform: translate(-50%, -50%); @include token-utils.use-tokens(tokens-mat-radio.$prefix, tokens-mat-radio.get-token-slots()) { @include token-utils.create-token-slot(display, touch-target-display); } [dir='rtl'] & { left: auto; right: 50%; transform: translate(50%, -50%); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 3352, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.scss" }
components/src/material/radio/README.md_0_96
Please see the official documentation at https://material.angular.io/components/component/radio
{ "commit_id": "ea0d1ba7b", "end_byte": 96, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/README.md" }
components/src/material/radio/BUILD.bazel_0_1477
load( "//tools:defaults.bzl", "extract_tokens", "markdown_to_html", "ng_module", "ng_test_library", "ng_web_test_suite", "sass_binary", "sass_library", ) package(default_visibility = ["//visibility:public"]) ng_module( name = "radio", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [":radio_scss"] + glob(["**/*.html"]), deps = [ "//src/cdk/a11y", "//src/cdk/collections", "//src/material/core", "@npm//@angular/forms", ], ) sass_library( name = "radio_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "radio_scss", src = "radio.scss", deps = [ ":radio_scss_lib", "//src/material/core:core_scss_lib", ], ) markdown_to_html( name = "overview", srcs = [":radio.md"], ) extract_tokens( name = "tokens", srcs = [":radio_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), ) ########### # Testing ########### ng_test_library( name = "radio_tests_lib", srcs = glob( ["**/*.spec.ts"], ), deps = [ ":radio", "//src/cdk/testing/private", "@npm//@angular/common", "@npm//@angular/forms", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":radio_tests_lib", ], )
{ "commit_id": "ea0d1ba7b", "end_byte": 1477, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/BUILD.bazel" }
components/src/material/radio/_radio-theme.scss_0_6108
@use '../core/style/sass-utils'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/tokens/token-utils'; @use '../core/typography/typography'; @use '../core/tokens/m2/mdc/radio' as tokens-mdc-radio; @use '../core/tokens/m2/mat/radio' as tokens-mat-radio; /// Outputs base theme styles (styles not dependent on the color, typography, or density settings) /// for the mat-radio. /// @param {Map} $theme The theme to generate base styles for. @mixin base($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, base)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-radio.$prefix, tokens-mdc-radio.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mat-radio.$prefix, tokens-mat-radio.get-unthemable-tokens() ); } } } /// Outputs color theme styles for the mat-radio. /// @param {Map} $theme The theme to generate color styles for. /// @param {ArgList} Additional optional arguments (only supported for M3 themes): /// $color-variant: The color variant to use for the radio button: primary, secondary, tertiary, /// or error (If not specified, default primary color will be used). @mixin color($theme, $options...) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, color), $options...); } @else { .mat-mdc-radio-button { &.mat-primary { @include token-utils.create-token-values( tokens-mdc-radio.$prefix, tokens-mdc-radio.get-color-tokens($theme, primary) ); @include token-utils.create-token-values( tokens-mat-radio.$prefix, tokens-mat-radio.get-color-tokens($theme, primary) ); } &.mat-accent { @include token-utils.create-token-values( tokens-mdc-radio.$prefix, tokens-mdc-radio.get-color-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-radio.$prefix, tokens-mat-radio.get-color-tokens($theme) ); } &.mat-warn { @include token-utils.create-token-values( tokens-mdc-radio.$prefix, tokens-mdc-radio.get-color-tokens($theme, warn) ); @include token-utils.create-token-values( tokens-mat-radio.$prefix, tokens-mat-radio.get-color-tokens($theme, warn) ); } } } } /// Outputs typography theme styles for the mat-radio. /// @param {Map} $theme The theme to generate typography styles for. @mixin typography($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, typography)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-radio.$prefix, tokens-mdc-radio.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-radio.$prefix, tokens-mat-radio.get-typography-tokens($theme) ); } } } /// Outputs typography theme styles for the mat-radio. /// @param {Map} $theme The theme to generate density styles for. @mixin density($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, density)); } @else { $density-scale: inspection.get-theme-density($theme); @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-radio.$prefix, tokens-mdc-radio.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-radio.$prefix, tokens-mat-radio.get-density-tokens($theme) ); } } } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mdc-radio.$prefix, tokens: tokens-mdc-radio.get-token-slots(), ), ( namespace: tokens-mat-radio.$prefix, tokens: tokens-mat-radio.get-token-slots(), ), ); } /// Outputs the CSS variable values for the given tokens. /// @param {Map} $tokens The token values to emit. @mixin overrides($tokens: ()) { @include token-utils.batch-create-token-values($tokens, _define-overrides()...); } /// Outputs all (base, color, typography, and density) theme styles for the mat-radio. /// @param {Map} $theme The theme to generate styles for. /// @param {ArgList} Additional optional arguments (only supported for M3 themes): /// $color-variant: The color variant to use for the radio button: primary, secondary, tertiary, /// or error (If not specified, default primary color will be used). @mixin theme($theme, $options...) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-radio') { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...); } @else { @include base($theme); @if inspection.theme-has($theme, color) { @include color($theme); } @if inspection.theme-has($theme, density) { @include density($theme); } @if inspection.theme-has($theme, typography) { @include typography($theme); } } } } @mixin _theme-from-tokens($tokens, $options...) { @include validation.selector-defined( 'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector' ); $mdc-radio-tokens: token-utils.get-tokens-for($tokens, tokens-mdc-radio.$prefix, $options...); $mat-radio-tokens: token-utils.get-tokens-for($tokens, tokens-mat-radio.$prefix, $options...); @include token-utils.create-token-values(tokens-mdc-radio.$prefix, $mdc-radio-tokens); @include token-utils.create-token-values(tokens-mat-radio.$prefix, $mat-radio-tokens); }
{ "commit_id": "ea0d1ba7b", "end_byte": 6108, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/_radio-theme.scss" }
components/src/material/radio/index.ts_0_234
/** * @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 */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/index.ts" }
components/src/material/radio/radio.spec.ts_0_1135
import {dispatchFakeEvent} from '@angular/cdk/testing/private'; import {Component, DebugElement, ViewChild} from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, tick, waitForAsync} from '@angular/core/testing'; import {FormControl, FormsModule, NgModel, ReactiveFormsModule} from '@angular/forms'; import {By} from '@angular/platform-browser'; import { MAT_RADIO_DEFAULT_OPTIONS, MatRadioButton, MatRadioChange, MatRadioGroup, MatRadioModule, } from './index'; describe('MatRadio', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ MatRadioModule, FormsModule, ReactiveFormsModule, DisableableRadioButton, FocusableRadioButton, RadiosInsideRadioGroup, RadioGroupWithNgModel, RadioGroupWithFormControl, StandaloneRadioButtons, InterleavedRadioGroup, TranscludingWrapper, RadioButtonWithPredefinedTabindex, RadioButtonWithPredefinedAriaAttributes, RadiosInsidePreCheckedRadioGroup, PreselectedRadioWithStaticValueAndNgIf, ], }); }));
{ "commit_id": "ea0d1ba7b", "end_byte": 1135, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.spec.ts" }
components/src/material/radio/radio.spec.ts_1139_10623
describe('inside of a group', () => { let fixture: ComponentFixture<RadiosInsideRadioGroup>; let groupDebugElement: DebugElement; let radioDebugElements: DebugElement[]; let radioNativeElements: HTMLElement[]; let radioLabelElements: HTMLLabelElement[]; let radioInputElements: HTMLInputElement[]; let radioFormFieldElements: HTMLInputElement[]; let groupInstance: MatRadioGroup; let radioInstances: MatRadioButton[]; let testComponent: RadiosInsideRadioGroup; beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(RadiosInsideRadioGroup); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; groupDebugElement = fixture.debugElement.query(By.directive(MatRadioGroup))!; groupInstance = groupDebugElement.injector.get<MatRadioGroup>(MatRadioGroup); radioDebugElements = fixture.debugElement.queryAll(By.directive(MatRadioButton)); radioNativeElements = radioDebugElements.map(debugEl => debugEl.nativeElement); radioInstances = radioDebugElements.map(debugEl => debugEl.componentInstance); radioLabelElements = radioDebugElements.map( debugEl => debugEl.query(By.css('label'))!.nativeElement, ); radioInputElements = radioDebugElements.map( debugEl => debugEl.query(By.css('input'))!.nativeElement, ); radioFormFieldElements = radioDebugElements.map( debugEl => debugEl.query(By.css('.mdc-form-field'))!.nativeElement, ); })); it('should set individual radio names based on the group name', () => { expect(groupInstance.name).toBeTruthy(); for (const radio of radioInstances) { expect(radio.name).toBe(groupInstance.name); } }); it('should coerce the disabled binding on the radio group', () => { (testComponent as any).isGroupDisabled = ''; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); radioLabelElements[0].click(); fixture.detectChanges(); expect(radioInstances[0].checked).toBe(false); expect(groupInstance.disabled).toBe(true); }); it('should disable click interaction when the group is disabled', () => { testComponent.isGroupDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); radioLabelElements[0].click(); fixture.detectChanges(); expect(radioInstances[0].checked).toBe(false); }); it('should set label position based on the group labelPosition', () => { testComponent.labelPos = 'before'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); for (const radio of radioInstances) { expect(radio.labelPosition).toBe('before'); } testComponent.labelPos = 'after'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); for (const radio of radioInstances) { expect(radio.labelPosition).toBe('after'); } }); it('should disable each individual radio when the group is disabled', () => { testComponent.isGroupDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); for (const radio of radioInstances) { expect(radio.disabled).toBe(true); } }); it('should make all disabled buttons interactive if the group is marked as disabledInteractive', () => { testComponent.isGroupDisabledInteractive = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioInstances.every(radio => radio.disabledInteractive)).toBe(true); }); it('should prevent the click action when disabledInteractive and disabled', () => { testComponent.isGroupDisabled = true; testComponent.isGroupDisabledInteractive = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); // We can't monitor the `defaultPrevented` state on the // native `click` so we dispatch an extra one. const fakeEvent = dispatchFakeEvent(radioInputElements[0], 'click'); radioInputElements[0].click(); fixture.detectChanges(); expect(fakeEvent.defaultPrevented).toBe(true); expect(radioInstances[0].checked).toBe(false); }); it('should set required to each radio button when the group is required', () => { testComponent.isGroupRequired = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); for (const radio of radioInstances) { expect(radio.required).toBe(true); } }); it('should update the group value when one of the radios changes', () => { expect(groupInstance.value).toBeFalsy(); radioInstances[0].checked = true; fixture.detectChanges(); expect(groupInstance.value).toBe('fire'); expect(groupInstance.selected).toBe(radioInstances[0]); }); it('should update the group and radios when one of the radios is clicked', () => { expect(groupInstance.value).toBeFalsy(); radioLabelElements[0].click(); fixture.detectChanges(); expect(groupInstance.value).toBe('fire'); expect(groupInstance.selected).toBe(radioInstances[0]); expect(radioInstances[0].checked).toBe(true); expect(radioInstances[1].checked).toBe(false); radioLabelElements[1].click(); fixture.detectChanges(); expect(groupInstance.value).toBe('water'); expect(groupInstance.selected).toBe(radioInstances[1]); expect(radioInstances[0].checked).toBe(false); expect(radioInstances[1].checked).toBe(true); }); it('should check a radio upon interaction with the underlying native radio button', () => { radioInputElements[0].click(); fixture.detectChanges(); expect(radioInstances[0].checked).toBe(true); expect(groupInstance.value).toBe('fire'); expect(groupInstance.selected).toBe(radioInstances[0]); }); it('should emit a change event from radio buttons', () => { expect(radioInstances[0].checked).toBe(false); const spies = radioInstances.map((radio, index) => jasmine.createSpy(`onChangeSpy ${index} for ${radio.name}`), ); spies.forEach((spy, index) => radioInstances[index].change.subscribe(spy)); radioLabelElements[0].click(); fixture.detectChanges(); expect(spies[0]).toHaveBeenCalled(); radioLabelElements[1].click(); fixture.detectChanges(); // To match the native radio button behavior, the change event shouldn't // be triggered when the radio got unselected. expect(spies[0]).toHaveBeenCalledTimes(1); expect(spies[1]).toHaveBeenCalledTimes(1); }); it(`should not emit a change event from the radio group when change group value programmatically`, () => { expect(groupInstance.value).toBeFalsy(); const changeSpy = jasmine.createSpy('radio-group change listener'); groupInstance.change.subscribe(changeSpy); radioLabelElements[0].click(); fixture.detectChanges(); expect(changeSpy).toHaveBeenCalledTimes(1); groupInstance.value = 'water'; fixture.detectChanges(); expect(changeSpy).toHaveBeenCalledTimes(1); }); it('should update the group and radios when updating the group value', () => { expect(groupInstance.value).toBeFalsy(); testComponent.groupValue = 'fire'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(groupInstance.value).toBe('fire'); expect(groupInstance.selected).toBe(radioInstances[0]); expect(radioInstances[0].checked).toBe(true); expect(radioInstances[1].checked).toBe(false); testComponent.groupValue = 'water'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(groupInstance.value).toBe('water'); expect(groupInstance.selected).toBe(radioInstances[1]); expect(radioInstances[0].checked).toBe(false); expect(radioInstances[1].checked).toBe(true); }); it('should deselect all of the radios when the group value is cleared', () => { radioInstances[0].checked = true; expect(groupInstance.value).toBeTruthy(); groupInstance.value = null; expect(radioInstances.every(radio => !radio.checked)).toBe(true); }); it('should not show ripples on disabled radio buttons', () => { testComponent.isFirstDisabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); dispatchFakeEvent(radioFormFieldElements[0], 'mousedown'); dispatchFakeEvent(radioFormFieldElements[0], 'mouseup'); let rippleAmount = radioNativeElements[0].querySelectorAll( '.mat-ripple-element:not(.mat-radio-persistent-ripple)', ).length; expect(rippleAmount) .withContext('Expected a disabled radio button to not show ripples') .toBe(0); testComponent.isFirstDisabled = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); dispatchFakeEvent(radioFormFieldElements[0], 'mousedown'); dispatchFakeEvent(radioFormFieldElements[0], 'mouseup'); rippleAmount = radioNativeElements[0].querySelectorAll( '.mat-ripple-element:not(.mat-radio-persistent-ripple)', ).length; expect(rippleAmount).withContext('Expected an enabled radio button to show ripples').toBe(1); });
{ "commit_id": "ea0d1ba7b", "end_byte": 10623, "start_byte": 1139, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.spec.ts" }
components/src/material/radio/radio.spec.ts_10629_18589
it('should not show ripples if matRippleDisabled input is set', () => { testComponent.disableRipple = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); for (const radioFormField of radioFormFieldElements) { dispatchFakeEvent(radioFormField, 'mousedown'); dispatchFakeEvent(radioFormField, 'mouseup'); const rippleAmount = radioNativeElements[0].querySelectorAll( '.mat-ripple-element:not(.mat-radio-persistent-ripple)', ).length; expect(rippleAmount).toBe(0); } testComponent.disableRipple = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); for (const radioFormField of radioFormFieldElements) { dispatchFakeEvent(radioFormField, 'mousedown'); dispatchFakeEvent(radioFormField, 'mouseup'); const rippleAmount = radioNativeElements[0].querySelectorAll( '.mat-ripple-element:not(.mat-radio-persistent-ripple)', ).length; expect(rippleAmount).toBe(1); } }); it(`should update the group's selected radio to null when unchecking that radio programmatically`, () => { const changeSpy = jasmine.createSpy('radio-group change listener'); groupInstance.change.subscribe(changeSpy); radioInstances[0].checked = true; fixture.detectChanges(); expect(changeSpy).not.toHaveBeenCalled(); expect(groupInstance.value).toBeTruthy(); radioInstances[0].checked = false; fixture.detectChanges(); expect(changeSpy).not.toHaveBeenCalled(); expect(groupInstance.value).toBeFalsy(); expect(radioInstances.every(radio => !radio.checked)).toBe(true); expect(groupInstance.selected).toBeNull(); }); it('should not fire a change event from the group when a radio checked state changes', () => { const changeSpy = jasmine.createSpy('radio-group change listener'); groupInstance.change.subscribe(changeSpy); radioInstances[0].checked = true; fixture.detectChanges(); expect(changeSpy).not.toHaveBeenCalled(); expect(groupInstance.value).toBeTruthy(); expect(groupInstance.value).toBe('fire'); radioInstances[1].checked = true; fixture.detectChanges(); expect(groupInstance.value).toBe('water'); expect(changeSpy).not.toHaveBeenCalled(); }); it(`should update checked status if changed value to radio group's value`, () => { const changeSpy = jasmine.createSpy('radio-group change listener'); groupInstance.change.subscribe(changeSpy); groupInstance.value = 'apple'; expect(changeSpy).not.toHaveBeenCalled(); expect(groupInstance.value).toBe('apple'); expect(groupInstance.selected).withContext('expect group selected to be null').toBeFalsy(); expect(radioInstances[0].checked) .withContext('should not select the first button') .toBeFalsy(); expect(radioInstances[1].checked) .withContext('should not select the second button') .toBeFalsy(); expect(radioInstances[2].checked) .withContext('should not select the third button') .toBeFalsy(); radioInstances[0].value = 'apple'; fixture.detectChanges(); expect(groupInstance.selected) .withContext('expect group selected to be first button') .toBe(radioInstances[0]); expect(radioInstances[0].checked) .withContext('expect group select the first button') .toBeTruthy(); expect(radioInstances[1].checked) .withContext('should not select the second button') .toBeFalsy(); expect(radioInstances[2].checked) .withContext('should not select the third button') .toBeFalsy(); }); it('should apply class based on color attribute', () => { expect(radioNativeElements.every(radioEl => radioEl.classList.contains('mat-accent'))) .withContext('Expected every radio element to use the accent color by default.') .toBe(true); testComponent.color = 'primary'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioNativeElements.every(radioEl => radioEl.classList.contains('mat-primary'))) .withContext('Expected every radio element to use the primary color from the binding.') .toBe(true); testComponent.color = 'warn'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioNativeElements.every(radioEl => radioEl.classList.contains('mat-warn'))) .withContext('Expected every radio element to use the primary color from the binding.') .toBe(true); testComponent.color = null; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioNativeElements.every(radioEl => radioEl.classList.contains('mat-accent'))) .withContext('Expected every radio element to fallback to accent color if value is falsy.') .toBe(true); }); it('should be able to inherit the color from the radio group', () => { groupInstance.color = 'warn'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioNativeElements.every(radioEl => radioEl.classList.contains('mat-warn'))) .withContext('Expected every radio element to have the warn color.') .toBe(true); }); it('should have the individual button color take precedence over the group color', () => { radioInstances[1].color = 'primary'; groupInstance.color = 'warn'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioNativeElements[0].classList).toContain('mat-warn'); expect(radioNativeElements[1].classList).toContain('mat-primary'); expect(radioNativeElements[2].classList).toContain('mat-warn'); }); it('should have a focus indicator', () => { const radioRippleNativeElements = radioNativeElements.map( element => element.querySelector('.mat-radio-ripple')!, ); expect( radioRippleNativeElements.every(element => element.classList.contains('mat-focus-indicator'), ), ).toBe(true); }); it('should set the input tabindex based on the selected radio button', () => { const getTabIndexes = () => { return radioInputElements.map(element => parseInt(element.getAttribute('tabindex') || '')); }; expect(getTabIndexes()).toEqual([0, 0, 0]); radioLabelElements[0].click(); fixture.detectChanges(); expect(getTabIndexes()).toEqual([0, -1, -1]); radioLabelElements[1].click(); fixture.detectChanges(); expect(getTabIndexes()).toEqual([-1, 0, -1]); radioLabelElements[2].click(); fixture.detectChanges(); expect(getTabIndexes()).toEqual([-1, -1, 0]); }); it('should set the input tabindex correctly with a pre-checked radio button', () => { const precheckedFixture = TestBed.createComponent(RadiosInsidePreCheckedRadioGroup); precheckedFixture.detectChanges(); const radios: NodeListOf<HTMLElement> = precheckedFixture.nativeElement.querySelectorAll('mat-radio-button input'); expect( Array.from(radios).map(radio => { return radio.getAttribute('tabindex'); }), ).toEqual(['-1', '-1', '0']); }); it('should clear the selected radio button but preserve the value on destroy', () => { radioLabelElements[0].click(); fixture.detectChanges(); expect(groupInstance.selected).toBe(radioInstances[0]); expect(groupInstance.value).toBe('fire'); fixture.componentInstance.isFirstShown = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(groupInstance.selected).toBe(null); expect(groupInstance.value).toBe('fire'); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 18589, "start_byte": 10629, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.spec.ts" }
components/src/material/radio/radio.spec.ts_18593_26986
describe('group with ngModel', () => { let fixture: ComponentFixture<RadioGroupWithNgModel>; let groupDebugElement: DebugElement; let radioDebugElements: DebugElement[]; let innerRadios: DebugElement[]; let radioLabelElements: HTMLLabelElement[]; let groupInstance: MatRadioGroup; let radioInstances: MatRadioButton[]; let testComponent: RadioGroupWithNgModel; let groupNgModel: NgModel; beforeEach(() => { fixture = TestBed.createComponent(RadioGroupWithNgModel); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; groupDebugElement = fixture.debugElement.query(By.directive(MatRadioGroup))!; groupInstance = groupDebugElement.injector.get<MatRadioGroup>(MatRadioGroup); groupNgModel = groupDebugElement.injector.get<NgModel>(NgModel); radioDebugElements = fixture.debugElement.queryAll(By.directive(MatRadioButton)); radioInstances = radioDebugElements.map(debugEl => debugEl.componentInstance); innerRadios = fixture.debugElement.queryAll(By.css('input[type="radio"]')); radioLabelElements = radioDebugElements.map( debugEl => debugEl.query(By.css('label'))!.nativeElement, ); }); it('should set individual radio names based on the group name', () => { expect(groupInstance.name).toBeTruthy(); for (const radio of radioInstances) { expect(radio.name).toBe(groupInstance.name); } groupInstance.name = 'new name'; for (const radio of radioInstances) { expect(radio.name).toBe(groupInstance.name); } }); it('should update the name of radio DOM elements if the name of the group changes', () => { const nodes: HTMLInputElement[] = innerRadios.map(radio => radio.nativeElement); expect(nodes.every(radio => radio.getAttribute('name') === groupInstance.name)) .withContext('Expected all radios to have the initial name.') .toBe(true); fixture.componentInstance.groupName = 'changed-name'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(groupInstance.name).toBe('changed-name'); expect(nodes.every(radio => radio.getAttribute('name') === groupInstance.name)) .withContext('Expected all radios to have the new name.') .toBe(true); }); it('should check the corresponding radio button on group value change', () => { expect(groupInstance.value).toBeFalsy(); for (const radio of radioInstances) { expect(radio.checked).toBeFalsy(); } groupInstance.value = 'vanilla'; for (const radio of radioInstances) { expect(radio.checked).toBe(groupInstance.value === radio.value); } expect(groupInstance.selected!.value).toBe(groupInstance.value); }); it('should have the correct control state initially and after interaction', () => { // The control should start off valid, pristine, and untouched. expect(groupNgModel.valid).toBe(true); expect(groupNgModel.pristine).toBe(true); expect(groupNgModel.touched).toBe(false); // After changing the value programmatically, the control should stay pristine // but remain untouched. radioInstances[1].checked = true; fixture.detectChanges(); expect(groupNgModel.valid).toBe(true); expect(groupNgModel.pristine).toBe(true); expect(groupNgModel.touched).toBe(false); // After a user interaction occurs (such as a click), the control should become dirty and // now also be touched. radioLabelElements[2].click(); fixture.detectChanges(); expect(groupNgModel.valid).toBe(true); expect(groupNgModel.pristine).toBe(false); expect(groupNgModel.touched).toBe(false); // Blur the input element in order to verify that the ng-touched state has been set to true. // The touched state should be only set to true after the form control has been blurred. dispatchFakeEvent(innerRadios[2].nativeElement, 'blur'); expect(groupNgModel.valid).toBe(true); expect(groupNgModel.pristine).toBe(false); expect(groupNgModel.touched).toBe(true); }); it('should write to the radio button based on ngModel', fakeAsync(() => { testComponent.modelValue = 'chocolate'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); tick(); fixture.detectChanges(); expect(innerRadios[1].nativeElement.checked).toBe(true); expect(radioInstances[1].checked).toBe(true); })); it('should update the ngModel value when selecting a radio button', () => { dispatchFakeEvent(innerRadios[1].nativeElement, 'change'); fixture.detectChanges(); expect(testComponent.modelValue).toBe('chocolate'); }); it('should update the model before firing change event', () => { expect(testComponent.modelValue).toBeUndefined(); expect(testComponent.lastEvent).toBeUndefined(); dispatchFakeEvent(innerRadios[1].nativeElement, 'change'); fixture.detectChanges(); expect(testComponent.lastEvent.value).toBe('chocolate'); dispatchFakeEvent(innerRadios[0].nativeElement, 'change'); fixture.detectChanges(); expect(testComponent.lastEvent.value).toBe('vanilla'); }); }); describe('group with FormControl', () => { it('should toggle the disabled state', () => { const fixture = TestBed.createComponent(RadioGroupWithFormControl); fixture.detectChanges(); expect(fixture.componentInstance.group.disabled).toBeFalsy(); fixture.componentInstance.formControl.disable(); fixture.detectChanges(); expect(fixture.componentInstance.group.disabled).toBeTruthy(); fixture.componentInstance.formControl.enable(); fixture.detectChanges(); expect(fixture.componentInstance.group.disabled).toBeFalsy(); }); it('should have a selected button when one matches the initial value', () => { const fixture = TestBed.createComponent(RadioGroupWithFormControl); fixture.componentInstance.formControl.setValue('2'); fixture.detectChanges(); expect(fixture.componentInstance.group.selected?.value).toBe('2'); }); }); describe('disableable', () => { let fixture: ComponentFixture<DisableableRadioButton>; let radioInstance: MatRadioButton; let radioNativeElement: HTMLInputElement; let radioHost: HTMLElement; let testComponent: DisableableRadioButton; beforeEach(() => { fixture = TestBed.createComponent(DisableableRadioButton); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; const radioDebugElement = fixture.debugElement.query(By.directive(MatRadioButton))!; radioHost = radioDebugElement.nativeElement; radioInstance = radioDebugElement.injector.get<MatRadioButton>(MatRadioButton); radioNativeElement = radioHost.querySelector('input')!; }); it('should toggle the disabled state', () => { expect(radioInstance.disabled).toBeFalsy(); expect(radioNativeElement.disabled).toBeFalsy(); testComponent.disabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioInstance.disabled).toBeTruthy(); expect(radioNativeElement.disabled).toBeTruthy(); testComponent.disabled = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioInstance.disabled).toBeFalsy(); expect(radioNativeElement.disabled).toBeFalsy(); }); it('should keep the button interactive if disabledInteractive is enabled', () => { testComponent.disabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioNativeElement.disabled).toBe(true); expect(radioNativeElement.hasAttribute('aria-disabled')).toBe(false); expect(radioHost.classList).not.toContain('mat-mdc-radio-disabled-interactive'); testComponent.disabledInteractive = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioNativeElement.disabled).toBe(false); expect(radioNativeElement.getAttribute('aria-disabled')).toBe('true'); expect(radioHost.classList).toContain('mat-mdc-radio-disabled-interactive'); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 26986, "start_byte": 18593, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.spec.ts" }
components/src/material/radio/radio.spec.ts_26990_34239
describe('as standalone', () => { let fixture: ComponentFixture<StandaloneRadioButtons>; let radioDebugElements: DebugElement[]; let seasonRadioInstances: MatRadioButton[]; let weatherRadioInstances: MatRadioButton[]; let fruitRadioInstances: MatRadioButton[]; let fruitRadioNativeElements: HTMLElement[]; let fruitRadioNativeInputs: HTMLElement[]; let testComponent: StandaloneRadioButtons; beforeEach(() => { fixture = TestBed.createComponent(StandaloneRadioButtons); fixture.detectChanges(); testComponent = fixture.debugElement.componentInstance; radioDebugElements = fixture.debugElement.queryAll(By.directive(MatRadioButton)); seasonRadioInstances = radioDebugElements .filter(debugEl => debugEl.componentInstance.name == 'season') .map(debugEl => debugEl.componentInstance); weatherRadioInstances = radioDebugElements .filter(debugEl => debugEl.componentInstance.name == 'weather') .map(debugEl => debugEl.componentInstance); fruitRadioInstances = radioDebugElements .filter(debugEl => debugEl.componentInstance.name == 'fruit') .map(debugEl => debugEl.componentInstance); fruitRadioNativeElements = radioDebugElements .filter(debugEl => debugEl.componentInstance.name == 'fruit') .map(debugEl => debugEl.nativeElement); fruitRadioNativeInputs = []; for (const element of fruitRadioNativeElements) { fruitRadioNativeInputs.push(<HTMLElement>element.querySelector('input')); } }); it('should uniquely select radios by a name', () => { seasonRadioInstances[0].checked = true; weatherRadioInstances[1].checked = true; fixture.detectChanges(); expect(seasonRadioInstances[0].checked).toBe(true); expect(seasonRadioInstances[1].checked).toBe(false); expect(seasonRadioInstances[2].checked).toBe(false); expect(weatherRadioInstances[0].checked).toBe(false); expect(weatherRadioInstances[1].checked).toBe(true); expect(weatherRadioInstances[2].checked).toBe(false); seasonRadioInstances[1].checked = true; fixture.detectChanges(); expect(seasonRadioInstances[0].checked).toBe(false); expect(seasonRadioInstances[1].checked).toBe(true); expect(seasonRadioInstances[2].checked).toBe(false); expect(weatherRadioInstances[0].checked).toBe(false); expect(weatherRadioInstances[1].checked).toBe(true); expect(weatherRadioInstances[2].checked).toBe(false); weatherRadioInstances[2].checked = true; expect(seasonRadioInstances[0].checked).toBe(false); expect(seasonRadioInstances[1].checked).toBe(true); expect(seasonRadioInstances[2].checked).toBe(false); expect(weatherRadioInstances[0].checked).toBe(false); expect(weatherRadioInstances[1].checked).toBe(false); expect(weatherRadioInstances[2].checked).toBe(true); }); it('should add required attribute to the underlying input element if defined', () => { const radioInstance = seasonRadioInstances[0]; radioInstance.required = true; fixture.detectChanges(); expect(radioInstance.required).toBe(true); }); it('should add value attribute to the underlying input element', () => { expect(fruitRadioNativeInputs[0].getAttribute('value')).toBe('banana'); expect(fruitRadioNativeInputs[1].getAttribute('value')).toBe('raspberry'); }); it('should add aria-label attribute to the underlying input element if defined', () => { expect(fruitRadioNativeInputs[0].getAttribute('aria-label')).toBe('Banana'); }); it('should not add aria-label attribute if not defined', () => { expect(fruitRadioNativeInputs[1].hasAttribute('aria-label')).toBeFalsy(); }); it('should change aria-label attribute if property is changed at runtime', () => { expect(fruitRadioNativeInputs[0].getAttribute('aria-label')).toBe('Banana'); testComponent.ariaLabel = 'Pineapple'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(fruitRadioNativeInputs[0].getAttribute('aria-label')).toBe('Pineapple'); }); it('should add aria-labelledby attribute to the underlying input element if defined', () => { expect(fruitRadioNativeInputs[0].getAttribute('aria-labelledby')).toBe('xyz'); }); it('should not add aria-labelledby attribute if not defined', () => { expect(fruitRadioNativeInputs[1].hasAttribute('aria-labelledby')).toBeFalsy(); }); it('should change aria-labelledby attribute if property is changed at runtime', () => { expect(fruitRadioNativeInputs[0].getAttribute('aria-labelledby')).toBe('xyz'); testComponent.ariaLabelledby = 'uvw'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(fruitRadioNativeInputs[0].getAttribute('aria-labelledby')).toBe('uvw'); }); it('should add aria-describedby attribute to the underlying input element if defined', () => { expect(fruitRadioNativeInputs[0].getAttribute('aria-describedby')).toBe('abc'); }); it('should not add aria-describedby attribute if not defined', () => { expect(fruitRadioNativeInputs[1].hasAttribute('aria-describedby')).toBeFalsy(); }); it('should change aria-describedby attribute if property is changed at runtime', () => { expect(fruitRadioNativeInputs[0].getAttribute('aria-describedby')).toBe('abc'); testComponent.ariaDescribedby = 'uvw'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(fruitRadioNativeInputs[0].getAttribute('aria-describedby')).toBe('uvw'); }); it('should focus on underlying input element when focus() is called', () => { for (let i = 0; i < fruitRadioInstances.length; i++) { expect(document.activeElement).not.toBe(fruitRadioNativeInputs[i]); fruitRadioInstances[i].focus(); fixture.detectChanges(); expect(document.activeElement).toBe(fruitRadioNativeInputs[i]); } }); it('should focus on underlying input element when clicking on the touch target', () => { const input = radioDebugElements[0].nativeElement.querySelector('input'); expect(document.activeElement).not.toBe(input); radioDebugElements[0].nativeElement.querySelector('.mat-mdc-radio-touch-target').click(); fixture.detectChanges(); expect(document.activeElement).toBe(input); }); it('should not change focus origin if origin not specified', () => { fruitRadioInstances[0].focus(undefined, 'mouse'); fruitRadioInstances[1].focus(); expect(fruitRadioNativeElements[1].classList).toContain('cdk-focused'); expect(fruitRadioNativeElements[1].classList).toContain('cdk-mouse-focused'); }); it('should not add the "name" attribute if it is not passed in', () => { const radio = fixture.debugElement.nativeElement.querySelector('#nameless input'); expect(radio.hasAttribute('name')).toBe(false); }); it('should default the radio color to `accent`', () => { expect(seasonRadioInstances.every(radio => radio.color === 'accent')).toBe(true); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 34239, "start_byte": 26990, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.spec.ts" }
components/src/material/radio/radio.spec.ts_34243_42837
describe('with tabindex', () => { let fixture: ComponentFixture<FocusableRadioButton>; beforeEach(() => { fixture = TestBed.createComponent(FocusableRadioButton); fixture.detectChanges(); }); it('should forward focus to native input', () => { let radioButtonEl = fixture.debugElement.query( By.css('.mat-mdc-radio-button'), )!.nativeElement; let inputEl = fixture.debugElement.query(By.css('.mdc-radio__native-control'))!.nativeElement; radioButtonEl.focus(); // Focus events don't always fire in tests, so we need to fake it. dispatchFakeEvent(radioButtonEl, 'focus'); fixture.detectChanges(); expect(document.activeElement).toBe(inputEl); }); it('should allow specifying an explicit tabindex for a single radio-button', () => { const radioButtonInput = fixture.debugElement.query(By.css('.mat-mdc-radio-button input'))! .nativeElement as HTMLInputElement; expect(radioButtonInput.tabIndex) .withContext('Expected the tabindex to be set to "0" by default.') .toBe(0); fixture.componentInstance.tabIndex = 4; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioButtonInput.tabIndex) .withContext('Expected the tabindex to be set to "4".') .toBe(4); }); it('should remove the tabindex from the host element', () => { const predefinedFixture = TestBed.createComponent(RadioButtonWithPredefinedTabindex); predefinedFixture.detectChanges(); const radioButtonEl = predefinedFixture.debugElement.query( By.css('.mat-mdc-radio-button'), )!.nativeElement; expect(radioButtonEl.hasAttribute('tabindex')).toBe(false); }); it('should forward a pre-defined tabindex to the underlying input', () => { const predefinedFixture = TestBed.createComponent(RadioButtonWithPredefinedTabindex); predefinedFixture.detectChanges(); const radioButtonInput = predefinedFixture.debugElement.query( By.css('.mat-mdc-radio-button input'), )!.nativeElement as HTMLInputElement; expect(radioButtonInput.getAttribute('tabindex')).toBe('5'); }); it('should remove the aria attributes from the host element', () => { const predefinedFixture = TestBed.createComponent(RadioButtonWithPredefinedAriaAttributes); predefinedFixture.detectChanges(); const radioButtonEl = predefinedFixture.debugElement.query( By.css('.mat-mdc-radio-button'), )!.nativeElement; expect(radioButtonEl.hasAttribute('aria-label')).toBe(false); expect(radioButtonEl.hasAttribute('aria-describedby')).toBe(false); expect(radioButtonEl.hasAttribute('aria-labelledby')).toBe(false); }); it('should remove the tabindex from the host element when disabled', () => { const radioButton = fixture.debugElement.query(By.css('.mat-mdc-radio-button')).nativeElement; fixture.componentInstance.disabled = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(radioButton.hasAttribute('tabindex')).toBe(false); }); }); describe('group interspersed with other tags', () => { let fixture: ComponentFixture<InterleavedRadioGroup>; let groupDebugElement: DebugElement; let groupInstance: MatRadioGroup; let radioDebugElements: DebugElement[]; let radioInstances: MatRadioButton[]; beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(InterleavedRadioGroup); fixture.detectChanges(); groupDebugElement = fixture.debugElement.query(By.directive(MatRadioGroup))!; groupInstance = groupDebugElement.injector.get<MatRadioGroup>(MatRadioGroup); radioDebugElements = fixture.debugElement.queryAll(By.directive(MatRadioButton)); radioInstances = radioDebugElements.map(debugEl => debugEl.componentInstance); })); it('should initialize selection of radios based on model value', () => { expect(groupInstance.selected).toBe(radioInstances[2]); }); }); it('should preselect a radio button with a static value and an ngIf', () => { const fixture = TestBed.createComponent(PreselectedRadioWithStaticValueAndNgIf); fixture.detectChanges(); expect(fixture.componentInstance.preselectedGroup.value).toBe('b'); expect(fixture.componentInstance.preselectedRadio.checked).toBe(true); }); }); describe('MatRadioDefaultOverrides', () => { describe('when MAT_RADIO_DEFAULT_OPTIONS overridden', () => { beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MatRadioModule, FormsModule, DefaultRadioButton, RadioButtonWithColorBinding], providers: [ { provide: MAT_RADIO_DEFAULT_OPTIONS, useValue: {color: 'primary'}, }, ], }); })); it('should override default color in Component', () => { const fixture: ComponentFixture<DefaultRadioButton> = TestBed.createComponent(DefaultRadioButton); fixture.detectChanges(); const radioDebugElement: DebugElement = fixture.debugElement.query( By.directive(MatRadioButton), )!; expect(radioDebugElement.nativeElement.classList).toContain('mat-primary'); }); it('should not override explicit input bindings', () => { const fixture: ComponentFixture<RadioButtonWithColorBinding> = TestBed.createComponent( RadioButtonWithColorBinding, ); fixture.detectChanges(); const radioDebugElement: DebugElement = fixture.debugElement.query( By.directive(MatRadioButton), )!; expect(radioDebugElement.nativeElement.classList).not.toContain('mat-primary'); expect(radioDebugElement.nativeElement.classList).toContain('mat-warn'); }); }); }); @Component({ template: ` <mat-radio-group [disabled]="isGroupDisabled" [labelPosition]="labelPos" [required]="isGroupRequired" [value]="groupValue" [disabledInteractive]="isGroupDisabledInteractive" name="test-name"> @if (isFirstShown) { <mat-radio-button value="fire" [disableRipple]="disableRipple" [disabled]="isFirstDisabled" [color]="color"> Charmander </mat-radio-button> } <mat-radio-button value="water" [disableRipple]="disableRipple" [color]="color"> Squirtle </mat-radio-button> <mat-radio-button value="leaf" [disableRipple]="disableRipple" [color]="color"> Bulbasaur </mat-radio-button> </mat-radio-group> `, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class RadiosInsideRadioGroup { labelPos: 'before' | 'after'; isFirstDisabled = false; isGroupDisabled = false; isGroupRequired = false; isGroupDisabledInteractive = false; groupValue: string | null = null; disableRipple = false; color: string | null; isFirstShown = true; } @Component({ template: ` <mat-radio-group name="test-name"> <mat-radio-button value="fire">Charmander</mat-radio-button> <mat-radio-button value="water">Squirtle</mat-radio-button> <mat-radio-button value="leaf" checked>Bulbasaur</mat-radio-button> </mat-radio-group> `, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class RadiosInsidePreCheckedRadioGroup {} @Component({ template: ` <mat-radio-button name="season" value="spring">Spring</mat-radio-button> <mat-radio-button name="season" value="summer">Summer</mat-radio-button> <mat-radio-button name="season" value="autum">Autumn</mat-radio-button> <mat-radio-button name="weather" value="warm">Spring</mat-radio-button> <mat-radio-button name="weather" value="hot">Summer</mat-radio-button> <mat-radio-button name="weather" value="cool">Autumn</mat-radio-button> <span id="xyz">Baby Banana</span> <span id="abc">A smaller banana</span> <mat-radio-button name="fruit" value="banana" [aria-label]="ariaLabel" [aria-labelledby]="ariaLabelledby" [aria-describedby]="ariaDescribedby"> </mat-radio-button> <mat-radio-button name="fruit" value="raspberry">Raspberry</mat-radio-button> <mat-radio-button id="nameless" value="no-name">No name</mat-radio-button> `, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class StandaloneRadioButtons { ariaLabel: string = 'Banana'; ariaLabelledby: string = 'xyz'; ariaDescribedby: string = 'abc'; }
{ "commit_id": "ea0d1ba7b", "end_byte": 42837, "start_byte": 34243, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.spec.ts" }
components/src/material/radio/radio.spec.ts_42839_47312
@Component({ template: ` <mat-radio-group [name]="groupName" [(ngModel)]="modelValue" (change)="lastEvent = $event"> @for (option of options; track option) { <mat-radio-button [value]="option.value">{{option.label}}</mat-radio-button> } </mat-radio-group> `, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class RadioGroupWithNgModel { modelValue: string; groupName = 'radio-group'; options = [ {label: 'Vanilla', value: 'vanilla'}, {label: 'Chocolate', value: 'chocolate'}, {label: 'Strawberry', value: 'strawberry'}, ]; lastEvent: MatRadioChange; } @Component({ template: ` <mat-radio-button [disabled]="disabled" [disabledInteractive]="disabledInteractive">One</mat-radio-button>`, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class DisableableRadioButton { disabled = false; disabledInteractive = false; @ViewChild(MatRadioButton) matRadioButton: MatRadioButton; } @Component({ template: ` <mat-radio-group [formControl]="formControl"> <mat-radio-button value="1">One</mat-radio-button> <mat-radio-button value="2">Two</mat-radio-button> </mat-radio-group> `, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class RadioGroupWithFormControl { @ViewChild(MatRadioGroup) group: MatRadioGroup; formControl = new FormControl(''); } @Component({ template: `<mat-radio-button [disabled]="disabled" [tabIndex]="tabIndex"></mat-radio-button>`, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class FocusableRadioButton { tabIndex: number; disabled = false; } @Component({ selector: 'transcluding-wrapper', template: ` <div><ng-content></ng-content></div> `, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class TranscludingWrapper {} @Component({ template: ` <mat-radio-group name="group" [(ngModel)]="modelValue"> @for (option of options; track option) { <transcluding-wrapper> <mat-radio-button [value]="option.value">{{option.label}}</mat-radio-button> </transcluding-wrapper> } </mat-radio-group> `, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule, TranscludingWrapper], }) class InterleavedRadioGroup { modelValue = 'strawberry'; options = [ {label: 'Vanilla', value: 'vanilla'}, {label: 'Chocolate', value: 'chocolate'}, {label: 'Strawberry', value: 'strawberry'}, ]; } @Component({ template: `<mat-radio-button tabindex="5"></mat-radio-button>`, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class RadioButtonWithPredefinedTabindex {} @Component({ template: `<mat-radio-button></mat-radio-button>`, standalone: true, imports: [MatRadioModule, FormsModule], }) class DefaultRadioButton {} @Component({ template: `<mat-radio-button color="warn"></mat-radio-button>`, standalone: true, imports: [MatRadioModule, FormsModule], }) class RadioButtonWithColorBinding {} @Component({ template: ` <mat-radio-button aria-label="Radio button" aria-describedby="something" aria-labelledby="something-else"></mat-radio-button>`, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class RadioButtonWithPredefinedAriaAttributes {} @Component({ // Note that this is somewhat of a contrived template, but it is required to // reproduce the issue. It was taken for a specific user report at #25831. template: ` @if (true) { <mat-radio-group [formControl]="controls.predecessor"> <mat-radio-button value="predecessor"></mat-radio-button> </mat-radio-group> } <mat-radio-group [formControl]="controls.target" #preselectedGroup> <mat-radio-button value="a"></mat-radio-button> @if (true) { <mat-radio-button value="b" #preselectedRadio></mat-radio-button> } </mat-radio-group> `, standalone: true, imports: [MatRadioModule, FormsModule, ReactiveFormsModule], }) class PreselectedRadioWithStaticValueAndNgIf { @ViewChild('preselectedGroup', {read: MatRadioGroup}) preselectedGroup: MatRadioGroup; @ViewChild('preselectedRadio', {read: MatRadioButton}) preselectedRadio: MatRadioButton; controls = { predecessor: new FormControl('predecessor'), target: new FormControl('b'), }; }
{ "commit_id": "ea0d1ba7b", "end_byte": 47312, "start_byte": 42839, "url": "https://github.com/angular/components/blob/main/src/material/radio/radio.spec.ts" }
components/src/material/radio/testing/radio-harness-filters.ts_0_950
/** * @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 {BaseHarnessFilters} from '@angular/cdk/testing'; /** A set of criteria that can be used to filter a list of `MatRadioGroupHarness` instances. */ export interface RadioGroupHarnessFilters extends BaseHarnessFilters { /** Only find instances whose name attribute is the given value. */ name?: string; } /** A set of criteria that can be used to filter a list of `MatRadioButtonHarness` instances. */ export interface RadioButtonHarnessFilters extends BaseHarnessFilters { /** Only find instances whose label matches the given value. */ label?: string | RegExp; /** Only find instances whose name attribute is the given value. */ name?: string; /** Only find instances with the given checked value. */ checked?: boolean; }
{ "commit_id": "ea0d1ba7b", "end_byte": 950, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/testing/radio-harness-filters.ts" }
components/src/material/radio/testing/public-api.ts_0_278
/** * @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 */ export * from './radio-harness'; export * from './radio-harness-filters';
{ "commit_id": "ea0d1ba7b", "end_byte": 278, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/testing/public-api.ts" }
components/src/material/radio/testing/radio-harness.ts_0_6159
/** * @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 {coerceBooleanProperty} from '@angular/cdk/coercion'; import { ComponentHarness, ComponentHarnessConstructor, HarnessPredicate, } from '@angular/cdk/testing'; import {RadioButtonHarnessFilters, RadioGroupHarnessFilters} from './radio-harness-filters'; /** Harness for interacting with a mat-radio-group in tests. */ export class MatRadioGroupHarness extends ComponentHarness { /** The selector for the host element of a `MatRadioGroup` instance. */ static hostSelector = '.mat-mdc-radio-group'; private _buttonClass = MatRadioButtonHarness; /** * Gets a `HarnessPredicate` that can be used to search for a radio group with specific * attributes. * @param options Options for filtering which radio group instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatRadioGroupHarness>( this: ComponentHarnessConstructor<T>, options: RadioGroupHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options).addOption( 'name', options.name, MatRadioGroupHarness._checkRadioGroupName, ); } /** Gets the name of the radio-group. */ async getName(): Promise<string | null> { const hostName = await this._getGroupNameFromHost(); // It's not possible to always determine the "name" of a radio-group by reading // the attribute. This is because the radio-group does not set the "name" as an // element attribute if the "name" value is set through a binding. if (hostName !== null) { return hostName; } // In case we couldn't determine the "name" of a radio-group by reading the // "name" attribute, we try to determine the "name" of the group by going // through all radio buttons. const radioNames = await this._getNamesFromRadioButtons(); if (!radioNames.length) { return null; } if (!this._checkRadioNamesInGroupEqual(radioNames)) { throw Error('Radio buttons in radio-group have mismatching names.'); } return radioNames[0]!; } /** Gets the id of the radio-group. */ async getId(): Promise<string | null> { return (await this.host()).getProperty<string | null>('id'); } /** Gets the checked radio-button in a radio-group. */ async getCheckedRadioButton(): Promise<MatRadioButtonHarness | null> { for (let radioButton of await this.getRadioButtons()) { if (await radioButton.isChecked()) { return radioButton; } } return null; } /** Gets the checked value of the radio-group. */ async getCheckedValue(): Promise<string | null> { const checkedRadio = await this.getCheckedRadioButton(); if (!checkedRadio) { return null; } return checkedRadio.getValue(); } /** * Gets a list of radio buttons which are part of the radio-group. * @param filter Optionally filters which radio buttons are included. */ async getRadioButtons(filter?: RadioButtonHarnessFilters): Promise<MatRadioButtonHarness[]> { return this.locatorForAll(this._buttonClass.with(filter))(); } /** * Checks a radio button in this group. * @param filter An optional filter to apply to the child radio buttons. The first tab matching * the filter will be selected. */ async checkRadioButton(filter?: RadioButtonHarnessFilters): Promise<void> { const radioButtons = await this.getRadioButtons(filter); if (!radioButtons.length) { throw Error(`Could not find radio button matching ${JSON.stringify(filter)}`); } return radioButtons[0].check(); } /** Gets the name attribute of the host element. */ private async _getGroupNameFromHost() { return (await this.host()).getAttribute('name'); } /** Gets a list of the name attributes of all child radio buttons. */ private async _getNamesFromRadioButtons(): Promise<string[]> { const groupNames: string[] = []; for (let radio of await this.getRadioButtons()) { const radioName = await radio.getName(); if (radioName !== null) { groupNames.push(radioName); } } return groupNames; } /** Checks if the specified radio names are all equal. */ private _checkRadioNamesInGroupEqual(radioNames: string[]): boolean { let groupName: string | null = null; for (let radioName of radioNames) { if (groupName === null) { groupName = radioName; } else if (groupName !== radioName) { return false; } } return true; } /** * Checks if a radio-group harness has the given name. Throws if a radio-group with * matching name could be found but has mismatching radio-button names. */ protected static async _checkRadioGroupName(harness: MatRadioGroupHarness, name: string) { // Check if there is a radio-group which has the "name" attribute set // to the expected group name. It's not possible to always determine // the "name" of a radio-group by reading the attribute. This is because // the radio-group does not set the "name" as an element attribute if the // "name" value is set through a binding. if ((await harness._getGroupNameFromHost()) === name) { return true; } // Check if there is a group with radio-buttons that all have the same // expected name. This implies that the group has the given name. It's // not possible to always determine the name of a radio-group through // the attribute because there is const radioNames = await harness._getNamesFromRadioButtons(); if (radioNames.indexOf(name) === -1) { return false; } if (!harness._checkRadioNamesInGroupEqual(radioNames)) { throw Error( `The locator found a radio-group with name "${name}", but some ` + `radio-button's within the group have mismatching names, which is invalid.`, ); } return true; } } /** Harness for interacting with a mat-radio-button in tests. */
{ "commit_id": "ea0d1ba7b", "end_byte": 6159, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/testing/radio-harness.ts" }
components/src/material/radio/testing/radio-harness.ts_6160_9545
export class MatRadioButtonHarness extends ComponentHarness { /** The selector for the host element of a `MatRadioButton` instance. */ static hostSelector = '.mat-mdc-radio-button'; /** * Gets a `HarnessPredicate` that can be used to search for a radio button with specific * attributes. * @param options Options for filtering which radio button instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatRadioButtonHarness>( this: ComponentHarnessConstructor<T>, options: RadioButtonHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options) .addOption('label', options.label, (harness, label) => HarnessPredicate.stringMatches(harness.getLabelText(), label), ) .addOption('name', options.name, async (harness, name) => (await harness.getName()) === name) .addOption( 'checked', options.checked, async (harness, checked) => (await harness.isChecked()) == checked, ); } protected _textLabel = this.locatorFor('label'); protected _clickLabel = this._textLabel; private _input = this.locatorFor('input'); /** Whether the radio-button is checked. */ async isChecked(): Promise<boolean> { const checked = (await this._input()).getProperty<boolean>('checked'); return coerceBooleanProperty(await checked); } /** Whether the radio-button is disabled. */ async isDisabled(): Promise<boolean> { const input = await this._input(); const disabled = await input.getAttribute('disabled'); if (disabled !== null) { return coerceBooleanProperty(disabled); } return (await input.getAttribute('aria-disabled')) === 'true'; } /** Whether the radio-button is required. */ async isRequired(): Promise<boolean> { const required = (await this._input()).getAttribute('required'); return coerceBooleanProperty(await required); } /** Gets the radio-button's name. */ async getName(): Promise<string | null> { return (await this._input()).getAttribute('name'); } /** Gets the radio-button's id. */ async getId(): Promise<string | null> { return (await this.host()).getProperty<string>('id'); } /** * Gets the value of the radio-button. The radio-button value will be converted to a string. * * Note: This means that for radio-button's with an object as a value `[object Object]` is * intentionally returned. */ async getValue(): Promise<string | null> { return (await this._input()).getProperty('value'); } /** Gets the radio-button's label text. */ async getLabelText(): Promise<string> { return (await this._textLabel()).text(); } /** Focuses the radio-button. */ async focus(): Promise<void> { return (await this._input()).focus(); } /** Blurs the radio-button. */ async blur(): Promise<void> { return (await this._input()).blur(); } /** Whether the radio-button is focused. */ async isFocused(): Promise<boolean> { return (await this._input()).isFocused(); } /** * Puts the radio-button in a checked state by clicking it if it is currently unchecked, * or doing nothing if it is already checked. */ async check(): Promise<void> { if (!(await this.isChecked())) { return (await this._clickLabel()).click(); } } }
{ "commit_id": "ea0d1ba7b", "end_byte": 9545, "start_byte": 6160, "url": "https://github.com/angular/components/blob/main/src/material/radio/testing/radio-harness.ts" }
components/src/material/radio/testing/radio-harness.spec.ts_0_5978
import {HarnessLoader} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {Component} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {ReactiveFormsModule} from '@angular/forms'; import {MatRadioModule} from '@angular/material/radio'; import {MatRadioButtonHarness, MatRadioGroupHarness} from './radio-harness'; describe('radio harness', () => { let fixture: ComponentFixture<MultipleRadioButtonsHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatRadioModule, ReactiveFormsModule, MultipleRadioButtonsHarnessTest], }); fixture = TestBed.createComponent(MultipleRadioButtonsHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); describe('MatRadioGroupHarness', () => { it('should load all radio-group harnesses', async () => { const groups = await loader.getAllHarnesses(MatRadioGroupHarness); expect(groups.length).toBe(3); }); it('should load radio-group with exact id', async () => { const groups = await loader.getAllHarnesses( MatRadioGroupHarness.with({selector: '#my-group-2'}), ); expect(groups.length).toBe(1); }); it('should load radio-group by name', async () => { let groups = await loader.getAllHarnesses( MatRadioGroupHarness.with({name: 'my-group-2-name'}), ); expect(groups.length).toBe(1); expect(await groups[0].getId()).toBe('my-group-2'); groups = await loader.getAllHarnesses(MatRadioGroupHarness.with({name: 'my-group-1-name'})); expect(groups.length).toBe(1); expect(await groups[0].getId()).toBe('my-group-1'); }); it('should throw when finding radio-group with specific name that has mismatched radio-button names', async () => { fixture.componentInstance.thirdGroupButtonName = 'other-name'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await expectAsync( loader.getAllHarnesses(MatRadioGroupHarness.with({name: 'third-group-name'})), ).toBeRejectedWithError( /locator found a radio-group with name "third-group-name".*have mismatching names/, ); }); it('should get name of radio-group', async () => { const groups = await loader.getAllHarnesses(MatRadioGroupHarness); expect(groups.length).toBe(3); expect(await groups[0].getName()).toBe('my-group-1-name'); expect(await groups[1].getName()).toBe('my-group-2-name'); expect(await groups[2].getName()).toBe('third-group-name'); fixture.componentInstance.secondGroupId = 'new-group'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(await groups[1].getName()).toBe('new-group-name'); fixture.componentInstance.thirdGroupButtonName = 'other-button-name'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); await expectAsync(groups[2].getName()).toBeRejectedWithError( /Radio buttons in radio-group have mismatching names./, ); }); it('should get id of radio-group', async () => { const groups = await loader.getAllHarnesses(MatRadioGroupHarness); expect(groups.length).toBe(3); expect(await groups[0].getId()).toBe('my-group-1'); expect(await groups[1].getId()).toBe('my-group-2'); expect(await groups[2].getId()).toBe(''); fixture.componentInstance.secondGroupId = 'new-group-name'; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(await groups[1].getId()).toBe('new-group-name'); }); it('should get checked value of radio-group', async () => { const [firstGroup, secondGroup] = await loader.getAllHarnesses(MatRadioGroupHarness); expect(await firstGroup.getCheckedValue()).toBe('opt2'); expect(await secondGroup.getCheckedValue()).toBe(null); }); it('should get radio-button harnesses of radio-group', async () => { const groups = await loader.getAllHarnesses(MatRadioGroupHarness); expect(groups.length).toBe(3); expect((await groups[0].getRadioButtons()).length).toBe(3); expect((await groups[1].getRadioButtons()).length).toBe(1); expect((await groups[2].getRadioButtons()).length).toBe(2); }); it('should get radio buttons from group with filter', async () => { const group = await loader.getHarness(MatRadioGroupHarness.with({name: 'my-group-1-name'})); expect((await group.getRadioButtons({label: 'opt2'})).length).toBe(1); }); it('should get checked radio-button harnesses of radio-group', async () => { const groups = await loader.getAllHarnesses(MatRadioGroupHarness); expect(groups.length).toBe(3); const groupOneChecked = await groups[0].getCheckedRadioButton(); const groupTwoChecked = await groups[1].getCheckedRadioButton(); const groupThreeChecked = await groups[2].getCheckedRadioButton(); expect(groupOneChecked).not.toBeNull(); expect(groupTwoChecked).toBeNull(); expect(groupThreeChecked).toBeNull(); expect(await groupOneChecked!.getId()).toBe('opt2-group-one'); }); it('should check radio button in group', async () => { const group = await loader.getHarness(MatRadioGroupHarness.with({name: 'my-group-1-name'})); expect(await group.getCheckedValue()).toBe('opt2'); await group.checkRadioButton({label: 'opt3'}); expect(await group.getCheckedValue()).toBe('opt3'); }); it('should throw error when checking invalid radio button', async () => { const group = await loader.getHarness(MatRadioGroupHarness.with({name: 'my-group-1-name'})); await expectAsync(group.checkRadioButton({label: 'opt4'})).toBeRejectedWithError( /Could not find radio button matching {"label":"opt4"}/, ); }); });
{ "commit_id": "ea0d1ba7b", "end_byte": 5978, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/testing/radio-harness.spec.ts" }
components/src/material/radio/testing/radio-harness.spec.ts_5982_12961
describe('MatRadioButtonHarness', () => { it('should load all radio-button harnesses', async () => { const radios = await loader.getAllHarnesses(MatRadioButtonHarness); expect(radios.length).toBe(9); }); it('should load radio-button with exact label', async () => { const radios = await loader.getAllHarnesses(MatRadioButtonHarness.with({label: 'Option #2'})); expect(radios.length).toBe(1); expect(await radios[0].getId()).toBe('opt2'); expect(await radios[0].getLabelText()).toBe('Option #2'); }); it('should load radio-button with regex label match', async () => { const radios = await loader.getAllHarnesses(MatRadioButtonHarness.with({label: /#3$/i})); expect(radios.length).toBe(1); expect(await radios[0].getId()).toBe('opt3'); expect(await radios[0].getLabelText()).toBe('Option #3'); }); it('should load radio-button with id', async () => { const radios = await loader.getAllHarnesses(MatRadioButtonHarness.with({selector: '#opt3'})); expect(radios.length).toBe(1); expect(await radios[0].getId()).toBe('opt3'); expect(await radios[0].getLabelText()).toBe('Option #3'); }); it('should load radio-buttons with same name', async () => { const radios = await loader.getAllHarnesses(MatRadioButtonHarness.with({name: 'group1'})); expect(radios.length).toBe(2); expect(await radios[0].getId()).toBe('opt1'); expect(await radios[1].getId()).toBe('opt2'); }); it('should get checked state', async () => { const [uncheckedRadio, checkedRadio] = await loader.getAllHarnesses(MatRadioButtonHarness); expect(await uncheckedRadio.isChecked()).toBe(false); expect(await checkedRadio.isChecked()).toBe(true); }); it('should get label text', async () => { const [firstRadio, secondRadio, thirdRadio] = await loader.getAllHarnesses(MatRadioButtonHarness); expect(await firstRadio.getLabelText()).toBe('Option #1'); expect(await secondRadio.getLabelText()).toBe('Option #2'); expect(await thirdRadio.getLabelText()).toBe('Option #3'); }); it('should get value', async () => { const [firstRadio, secondRadio, thirdRadio] = await loader.getAllHarnesses(MatRadioButtonHarness); expect(await firstRadio.getValue()).toBe('opt1'); expect(await secondRadio.getValue()).toBe('opt2'); expect(await thirdRadio.getValue()).toBe('opt3'); }); it('should get disabled state', async () => { const [firstRadio] = await loader.getAllHarnesses(MatRadioButtonHarness); expect(await firstRadio.isDisabled()).toBe(false); fixture.componentInstance.disableAll = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(await firstRadio.isDisabled()).toBe(true); }); it('should get the disabled state with disabledInteractive is enabled', async () => { fixture.componentInstance.disabledInteractive = true; fixture.changeDetectorRef.markForCheck(); const [firstRadio] = await loader.getAllHarnesses(MatRadioButtonHarness); expect(await firstRadio.isDisabled()).toBe(false); fixture.componentInstance.disableAll = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(await firstRadio.isDisabled()).toBe(true); }); it('should focus radio-button', async () => { const radioButton = await loader.getHarness(MatRadioButtonHarness.with({selector: '#opt2'})); expect(await radioButton.isFocused()).toBe(false); await radioButton.focus(); expect(await radioButton.isFocused()).toBe(true); }); it('should blur radio-button', async () => { const radioButton = await loader.getHarness(MatRadioButtonHarness.with({selector: '#opt2'})); await radioButton.focus(); expect(await radioButton.isFocused()).toBe(true); await radioButton.blur(); expect(await radioButton.isFocused()).toBe(false); }); it('should check radio-button', async () => { const [uncheckedRadio, checkedRadio] = await loader.getAllHarnesses(MatRadioButtonHarness); await uncheckedRadio.check(); expect(await uncheckedRadio.isChecked()).toBe(true); // Checked radio state should change since the two radio's // have the same name and only one can be checked. expect(await checkedRadio.isChecked()).toBe(false); }); it('should not be able to check disabled radio-button', async () => { fixture.componentInstance.disableAll = true; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); const radioButton = await loader.getHarness(MatRadioButtonHarness.with({selector: '#opt3'})); expect(await radioButton.isChecked()).toBe(false); await radioButton.check(); expect(await radioButton.isChecked()).toBe(false); fixture.componentInstance.disableAll = false; fixture.changeDetectorRef.markForCheck(); fixture.detectChanges(); expect(await radioButton.isChecked()).toBe(false); await radioButton.check(); expect(await radioButton.isChecked()).toBe(true); }); it('should get required state', async () => { const radioButton = await loader.getHarness( MatRadioButtonHarness.with({selector: '#required-radio'}), ); expect(await radioButton.isRequired()).toBe(true); }); }); }); @Component({ template: ` @for (value of values; track value) { <mat-radio-button [name]="value === 'opt3' ? 'group2' : 'group1'" [disabled]="disableAll" [disabledInteractive]="disabledInteractive" [checked]="value === 'opt2'" [id]="value" [required]="value === 'opt2'" [value]="value"> Option #{{$index + 1}} </mat-radio-button> } <mat-radio-group id="my-group-1" name="my-group-1-name"> @for (value of values; track value) { <mat-radio-button [checked]="value === 'opt2'" [value]="value" [id]="value + '-group-one'">{{value}}</mat-radio-button> } </mat-radio-group> <mat-radio-group [id]="secondGroupId" [name]="secondGroupId + '-name'"> <mat-radio-button id="required-radio" required [value]="true"> Accept terms of conditions </mat-radio-button> </mat-radio-group> <mat-radio-group [name]="thirdGroupName"> <mat-radio-button [value]="true">First</mat-radio-button> <mat-radio-button [value]="false" [name]="thirdGroupButtonName"></mat-radio-button> </mat-radio-group> `, standalone: true, imports: [MatRadioModule, ReactiveFormsModule], }) class MultipleRadioButtonsHarnessTest { values = ['opt1', 'opt2', 'opt3']; disableAll = false; disabledInteractive = false; secondGroupId = 'my-group-2'; thirdGroupName: string = 'third-group-name'; thirdGroupButtonName: string | undefined = undefined; }
{ "commit_id": "ea0d1ba7b", "end_byte": 12961, "start_byte": 5982, "url": "https://github.com/angular/components/blob/main/src/material/radio/testing/radio-harness.spec.ts" }
components/src/material/radio/testing/BUILD.bazel_0_834
load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "testing", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src/cdk/coercion", "//src/cdk/testing", ], ) ng_test_library( name = "unit_tests_lib", srcs = glob(["**/*.spec.ts"]), deps = [ ":testing", "//src/cdk/testing", "//src/cdk/testing/private", "//src/cdk/testing/testbed", "//src/material/radio", "@npm//@angular/forms", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [ ":unit_tests_lib", ], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "commit_id": "ea0d1ba7b", "end_byte": 834, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/testing/BUILD.bazel" }
components/src/material/radio/testing/index.ts_0_234
/** * @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 */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/radio/testing/index.ts" }
components/src/material/card/card-title-group.html_0_520
<div> <ng-content select="mat-card-title, mat-card-subtitle, [mat-card-title], [mat-card-subtitle], [matCardTitle], [matCardSubtitle]"></ng-content> </div> <ng-content select="[mat-card-image], [matCardImage], [mat-card-sm-image], [matCardImageSmall], [mat-card-md-image], [matCardImageMedium], [mat-card-lg-image], [matCardImageLarge], [mat-card-xl-image], [matCardImageXLarge]"></ng-content> <ng-content></ng-content>
{ "commit_id": "ea0d1ba7b", "end_byte": 520, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/card-title-group.html" }
components/src/material/card/card.md_0_4780
`<mat-card>` is a content container for text, photos, and actions in the context of a single subject. <!-- example(card-overview) --> ### Basic card sections The most basic card needs only an `<mat-card>` element with some content. However, Angular Material provides a number of preset sections that you can use inside a `<mat-card>`: | Element | Description | |--------------------------|----------------------------------------------------------------| | `<mat-card-header>` | Section anchored to the top of the card (adds padding) | | `<mat-card-content>` | Primary card content (adds padding) | | `<img mat-card-image>` | Card image. Stretches the image to the container width | | `<mat-card-actions>` | Container for buttons at the bottom of the card (adds padding) | | `<mat-card-footer>` | Section anchored to the bottom of the card | These elements primary serve as pre-styled content containers without any additional APIs. However, the `align` property on `<mat-card-actions>` can be used to position the actions at the `'start'` or `'end'` of the container. ### Card padding The `<mat-card>` element itself does not add any padding around its content. This allows developers to customize the padding to their liking by applying padding to the elements they put in the card. In many cases developers may just want the standard padding specified in the Material Design spec. In this case, the `<mat-card-header>`, `<mat-card-content>`, and `<mat-card-footer>` sections can be used. * `<mat-card-content>` adds standard padding along its sides, as well as along the top if it is the first element in the `<mat-card>`, and along the bottom if it is the last element in the `<mat-card>`. * `<mat-card-header>` adds standard padding along its sides and top. * `<mat-card-actions>` adds padding appropriate for the action buttons at the bottom of a card. ### Card headers A `<mat-card-header>` can contain any content, but there are several predefined elements that can be used to create a rich header to a card. These include: | Element | Description | |--------------------------|------------------------------------------------------| | `<mat-card-title>` | A title within the header | | `<mat-card-subtitle>` | A subtitle within the header | | `<img mat-card-avatar>` | An image used as an avatar within the header | In addition to using `<mat-card-title>` and `<mat-card-subtitle>` directly within the `<mat-card-header>`, they can be further nested inside a `<mat-card-title-group>` in order arrange them with a (non-avatar) image. ### Title groups `<mat-card-title-group>` can be used to combine a title, subtitle, and image into a single section. This element can contain: * `<mat-card-title>` * `<mat-card-subtitle>` * One of: * `<img mat-card-sm-image>` * `<img mat-card-md-image>` * `<img mat-card-lg-image>` ### Accessibility Cards serve a wide variety of scenarios and may contain many different types of content. Due to this flexible nature, the appropriate accessibility treatment depends on how you use `<mat-card>`. #### Group, region, and landmarks There are several ARIA roles that communicate that a portion of the UI represents some semantically meaningful whole. Depending on what the content of the card means to your application, you can apply one of [`role="group"`][role-group], [`role="region"`][role-region], or [one of the landmark roles][aria-landmarks] to the `<mat-card>` element. You do not need to apply a role when using a card as a purely decorative container that does not convey a meaningful grouping of related content for a single subject. In these cases, the content of the card should follow standard practices for document content. #### Focus Depending on how cards are used, it may be appropriate to apply a `tabindex` to the `<mat-card>` element. * If cards are a primary mechanism through which user interacts with the application, `tabindex="0"` may be appropriate. * If attention can be sent to the card, but it's not part of the document flow, `tabindex="-1"` may be appropriate. * If the card acts as a purely decorative container, it does not need to be tabbable. In this case, the card content should follow normal best practices for tab order. Always test your application to verify the behavior that works best for your users. [role-group]: https://www.w3.org/TR/wai-aria/#group [role-region]: https://www.w3.org/TR/wai-aria/#region [aria-landmarks]: https://www.w3.org/TR/wai-aria/#landmark
{ "commit_id": "ea0d1ba7b", "end_byte": 4780, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/card.md" }
components/src/material/card/_card-theme.scss_0_5041
@use 'sass:map'; @use '../core/style/sass-utils'; @use '../core/theming/theming'; @use '../core/theming/inspection'; @use '../core/theming/validation'; @use '../core/typography/typography'; @use '../core/tokens/token-utils'; @use '../core/tokens/m2/mat/card' as tokens-mat-card; @use '../core/tokens/m2/mdc/elevated-card' as tokens-mdc-elevated-card; @use '../core/tokens/m2/mdc/outlined-card' as tokens-mdc-outlined-card; @mixin base($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, base)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-elevated-card.$prefix, tokens-mdc-elevated-card.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mdc-outlined-card.$prefix, tokens-mdc-outlined-card.get-unthemable-tokens() ); @include token-utils.create-token-values( tokens-mat-card.$prefix, tokens-mat-card.get-unthemable-tokens() ); } } } @mixin color($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, color)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-elevated-card.$prefix, tokens-mdc-elevated-card.get-color-tokens($theme) ); @include token-utils.create-token-values( tokens-mdc-outlined-card.$prefix, tokens-mdc-outlined-card.get-color-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-card.$prefix, tokens-mat-card.get-color-tokens($theme) ); } } } @mixin typography($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, typography)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-elevated-card.$prefix, tokens-mdc-elevated-card.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mdc-outlined-card.$prefix, tokens-mdc-outlined-card.get-typography-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-card.$prefix, tokens-mat-card.get-typography-tokens($theme) ); } } } @mixin density($theme) { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme, density)); } @else { @include sass-utils.current-selector-or-root() { @include token-utils.create-token-values( tokens-mdc-elevated-card.$prefix, tokens-mdc-elevated-card.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mdc-outlined-card.$prefix, tokens-mdc-outlined-card.get-density-tokens($theme) ); @include token-utils.create-token-values( tokens-mat-card.$prefix, tokens-mat-card.get-density-tokens($theme) ); } } } /// Defines the tokens that will be available in the `overrides` mixin and for docs extraction. @function _define-overrides() { @return ( ( namespace: tokens-mat-card.$prefix, tokens: tokens-mat-card.get-token-slots(), ), ( namespace: tokens-mdc-elevated-card.$prefix, tokens: tokens-mdc-elevated-card.get-token-slots(), prefix: 'elevated-', ), ( namespace: tokens-mdc-outlined-card.$prefix, tokens: tokens-mdc-outlined-card.get-token-slots(), prefix: 'outlined-', ), ); } @mixin overrides($tokens: ()) { @include token-utils.batch-create-token-values($tokens, _define-overrides()...); } @mixin theme($theme) { @include theming.private-check-duplicate-theme-styles($theme, 'mat-card') { @if inspection.get-theme-version($theme) == 1 { @include _theme-from-tokens(inspection.get-theme-tokens($theme)); } @else { @include base($theme); @if inspection.theme-has($theme, color) { @include color($theme); } @if inspection.theme-has($theme, density) { @include density($theme); } @if inspection.theme-has($theme, typography) { @include typography($theme); } } } } @mixin _theme-from-tokens($tokens) { @include validation.selector-defined( 'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector' ); @if ($tokens != ()) { @include token-utils.create-token-values( tokens-mdc-elevated-card.$prefix, map.get($tokens, tokens-mdc-elevated-card.$prefix) ); @include token-utils.create-token-values( tokens-mdc-outlined-card.$prefix, map.get($tokens, tokens-mdc-outlined-card.$prefix) ); @include token-utils.create-token-values( tokens-mat-card.$prefix, map.get($tokens, tokens-mat-card.$prefix) ); } }
{ "commit_id": "ea0d1ba7b", "end_byte": 5041, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/_card-theme.scss" }
components/src/material/card/module.ts_0_983
/** * @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 { MatCard, MatCardActions, MatCardAvatar, MatCardContent, MatCardFooter, MatCardHeader, MatCardImage, MatCardLgImage, MatCardMdImage, MatCardSmImage, MatCardSubtitle, MatCardTitle, MatCardTitleGroup, MatCardXlImage, } from './card'; const CARD_DIRECTIVES = [ MatCard, MatCardActions, MatCardAvatar, MatCardContent, MatCardFooter, MatCardHeader, MatCardImage, MatCardLgImage, MatCardMdImage, MatCardSmImage, MatCardSubtitle, MatCardTitle, MatCardTitleGroup, MatCardXlImage, ]; @NgModule({ imports: [MatCommonModule, ...CARD_DIRECTIVES], exports: [CARD_DIRECTIVES, MatCommonModule], }) export class MatCardModule {}
{ "commit_id": "ea0d1ba7b", "end_byte": 983, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/module.ts" }
components/src/material/card/public-api.ts_0_254
/** * @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 */ export * from './card'; export * from './module';
{ "commit_id": "ea0d1ba7b", "end_byte": 254, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/public-api.ts" }
components/src/material/card/card.scss_0_2869
@use '../core/tokens/token-utils'; @use '../core/tokens/m2/mat/card' as tokens-mat-card; @use '../core/tokens/m2/mdc/elevated-card' as tokens-mdc-elevated-card; @use '../core/tokens/m2/mdc/outlined-card' as tokens-mdc-outlined-card; // Size of the `mat-card-header` region custom to Angular Material. $mat-card-header-size: 40px !default; // Default padding for text content within a card. $mat-card-default-padding: 16px !default; .mat-mdc-card { display: flex; flex-direction: column; box-sizing: border-box; position: relative; border-style: solid; border-width: 0; @include token-utils.use-tokens( tokens-mdc-elevated-card.$prefix, tokens-mdc-elevated-card.get-token-slots() ) { @include token-utils.create-token-slot(background-color, container-color); @include token-utils.create-token-slot(border-color, container-color); @include token-utils.create-token-slot(border-radius, container-shape); @include token-utils.create-token-slot(box-shadow, container-elevation); } // Transparent card border for high-contrast mode. &::after { position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: solid 1px transparent; content: ''; display: block; pointer-events: none; box-sizing: border-box; @include token-utils.use-tokens( tokens-mdc-elevated-card.$prefix, tokens-mdc-elevated-card.get-token-slots() ) { @include token-utils.create-token-slot(border-radius, container-shape); } } } .mat-mdc-card-outlined { @include token-utils.use-tokens( tokens-mdc-outlined-card.$prefix, tokens-mdc-outlined-card.get-token-slots() ) { @include token-utils.create-token-slot(background-color, container-color); @include token-utils.create-token-slot(border-radius, container-shape); @include token-utils.create-token-slot(border-width, outline-width); @include token-utils.create-token-slot(border-color, outline-color); @include token-utils.create-token-slot(box-shadow, container-elevation); } // Outlined card already displays border in high-contrast mode. // Overwriting styles set above to remove a duplicate border. &::after { border: none; } } .mdc-card__media { position: relative; box-sizing: border-box; background-repeat: no-repeat; background-position: center; background-size: cover; &::before { display: block; content: ''; } &:first-child { border-top-left-radius: inherit; border-top-right-radius: inherit; } &:last-child { border-bottom-left-radius: inherit; border-bottom-right-radius: inherit; } } .mat-mdc-card-actions { display: flex; flex-direction: row; align-items: center; box-sizing: border-box; min-height: 52px; padding: 8px; } // Add slots for custom Angular Material card tokens. @include token-utils
{ "commit_id": "ea0d1ba7b", "end_byte": 2869, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/card.scss" }
components/src/material/card/card.scss_2869_9249
.use-tokens(tokens-mat-card.$prefix, tokens-mat-card.get-token-slots()) { .mat-mdc-card-title { @include token-utils.create-token-slot(font-family, title-text-font); @include token-utils.create-token-slot(line-height, title-text-line-height); @include token-utils.create-token-slot(font-size, title-text-size); @include token-utils.create-token-slot(letter-spacing, title-text-tracking); @include token-utils.create-token-slot(font-weight, title-text-weight); } .mat-mdc-card-subtitle { @include token-utils.create-token-slot(color, subtitle-text-color); @include token-utils.create-token-slot(font-family, subtitle-text-font); @include token-utils.create-token-slot(line-height, subtitle-text-line-height); @include token-utils.create-token-slot(font-size, subtitle-text-size); @include token-utils.create-token-slot(letter-spacing, subtitle-text-tracking); @include token-utils.create-token-slot(font-weight, subtitle-text-weight); } } // Title text and subtitles text within a card. MDC doesn't have pre-made title sections for cards. // Maintained here for backwards compatibility with the previous generation MatCard. .mat-mdc-card-title, .mat-mdc-card-subtitle { // Custom elements default to `display: inline`. Reset to 'block'. display: block; // Titles and subtitles can be set on native header elements which come with // their own margin. Clear it since the spacing is done using `padding`. margin: 0; .mat-mdc-card-avatar ~ .mat-mdc-card-header-text & { // Apply default padding for a text content region. Omit any bottom padding because we assume // this region will be followed by another region that includes top padding. padding: $mat-card-default-padding $mat-card-default-padding 0; } } // Header section at the top of a card. MDC does not have a pre-made header section for cards. // Maintained here for backwards compatibility with the previous generation MatCard. .mat-mdc-card-header { // The primary purpose of the card header is to lay out the title, subtitle, and image in the // correct order. The image will come first, followed by a single div that will contain (via // content projection) both the title and the subtitle. display: flex; // Apply default padding for the header region. Omit any bottom padding because we assume // this region will be followed by another region that includes top padding. padding: $mat-card-default-padding $mat-card-default-padding 0; } // Primary card content. MDC does not have a pre-made section for primary content. // Adds the default 16px padding to the content. Maintained here for backwards compatibility // with the previous generation MatCard. .mat-mdc-card-content { // Custom elements default to `display: inline`. Reset to 'block'. display: block; // Apply default horizontal padding for a content region. padding: 0 $mat-card-default-padding; // Only add vertical padding to the main content area if it's not preceeded/followed by another // element within the card. &:first-child { padding-top: $mat-card-default-padding; } &:last-child { padding-bottom: $mat-card-default-padding; } } // Title group within a card. MDC does not have a pre-made section for anything title-related. // Maintained here for backwards compatibility with the previous generation MatCard. .mat-mdc-card-title-group { // This element exists primary to lay out its children (title, subtitle, media). The title // and subtitle go first (projected into a single div), followed by the media. display: flex; justify-content: space-between; width: 100%; } // Avatar image for a card. MDC does not specifically have a card avatar or a "common" avatar. // They *do* have a list avatar, but it uses a different size than we do here, which we preserve // to reduce breaking changes. Ultimately, the avatar styles just consist of a size and a // border-radius. .mat-mdc-card-avatar { height: $mat-card-header-size; width: $mat-card-header-size; border-radius: 50%; flex-shrink: 0; margin-bottom: $mat-card-default-padding; // Makes `<img>` tags behave like `background-size: cover`. Not supported // in IE, but we're using it as a progressive enhancement. object-fit: cover; // When a title and subtitle are used alongside an avatar, // reduce the spacing between them to better align with the avatar. & ~ .mat-mdc-card-header-text { .mat-mdc-card-subtitle, .mat-mdc-card-title { line-height: normal; } } } // Specifically sized small image, specific to Angular Material. .mat-mdc-card-sm-image { width: 80px; height: 80px; } // Specifically sized medium image, specific to Angular Material. .mat-mdc-card-md-image { width: 112px; height: 112px; } // Specifically sized large image, specific to Angular Material. .mat-mdc-card-lg-image { width: 152px; height: 152px; } // Specifically sized extra-large image, specific to Angular Material. .mat-mdc-card-xl-image { width: 240px; height: 240px; } // When both a title and a subtitle are used, eliminate the top padding of whichever comes second // because the first already covers the padding. // // Additionally, reset the padding for title and subtitle when used within `mat-card-header` or // `mat-card-title-group` since the padding is captured by parent container already. .mat-mdc-card-subtitle ~ .mat-mdc-card-title, .mat-mdc-card-title ~ .mat-mdc-card-subtitle, // The `.mat-mdc-card-header-text` here is redundant since the header text // wrapper is always there in the header, but we need the extra specificity. .mat-mdc-card-header .mat-mdc-card-header-text .mat-mdc-card-title, .mat-mdc-card-header .mat-mdc-card-header-text .mat-mdc-card-subtitle, .mat-mdc-card-title-group .mat-mdc-card-title, .mat-mdc-card-title-group .mat-mdc-card-subtitle { padding-top: 0; } // Remove the bottom margin from the last child of the card content. We intended to remove // margin from elements that have it built-in, such as `<p>`. We do this to avoid having too much // space between card content regions, as the space is already captured in the content region // element. .mat-mdc-card-content > :last-child:not(.mat-mdc-card-footer) { margin-bottom: 0; } // Support for actions aligned to the end of the card. .mat-mdc-card-actions-align-end { justify-content: flex-end; }
{ "commit_id": "ea0d1ba7b", "end_byte": 9249, "start_byte": 2869, "url": "https://github.com/angular/components/blob/main/src/material/card/card.scss" }
components/src/material/card/card.html_0_26
<ng-content></ng-content>
{ "commit_id": "ea0d1ba7b", "end_byte": 26, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/card.html" }
components/src/material/card/migration.md_0_124
# Migration notes for MDC-based `MatCard` * Previous `MatCard` always set 16px padding, which the MDC card sets no padding.
{ "commit_id": "ea0d1ba7b", "end_byte": 124, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/migration.md" }
components/src/material/card/card.ts_0_8206
/** * @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 { ChangeDetectionStrategy, Component, Directive, InjectionToken, Input, ViewEncapsulation, inject, } from '@angular/core'; export type MatCardAppearance = 'outlined' | 'raised'; /** Object that can be used to configure the default options for the card module. */ export interface MatCardConfig { /** Default appearance for cards. */ appearance?: MatCardAppearance; } /** Injection token that can be used to provide the default options the card module. */ export const MAT_CARD_CONFIG = new InjectionToken<MatCardConfig>('MAT_CARD_CONFIG'); /** * Material Design card component. Cards contain content and actions about a single subject. * See https://material.io/design/components/cards.html * * MatCard provides no behaviors, instead serving as a purely visual treatment. */ @Component({ selector: 'mat-card', templateUrl: 'card.html', styleUrl: 'card.css', host: { 'class': 'mat-mdc-card mdc-card', '[class.mat-mdc-card-outlined]': 'appearance === "outlined"', '[class.mdc-card--outlined]': 'appearance === "outlined"', }, exportAs: 'matCard', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, }) export class MatCard { @Input() appearance: MatCardAppearance; constructor(...args: unknown[]); constructor() { const config = inject<MatCardConfig>(MAT_CARD_CONFIG, {optional: true}); this.appearance = config?.appearance || 'raised'; } } // TODO(jelbourn): add `MatActionCard`, which is a card that acts like a button (and has a ripple). // Supported in MDC with `.mdc-card__primary-action`. Will require additional a11y docs for users. /** * Title of a card, intended for use within `<mat-card>`. This component is an optional * convenience for one variety of card title; any custom title element may be used in its place. * * MatCardTitle provides no behaviors, instead serving as a purely visual treatment. */ @Directive({ selector: `mat-card-title, [mat-card-title], [matCardTitle]`, host: {'class': 'mat-mdc-card-title'}, }) export class MatCardTitle {} /** * Container intended to be used within the `<mat-card>` component. Can contain exactly one * `<mat-card-title>`, one `<mat-card-subtitle>` and one content image of any size * (e.g. `<img matCardLgImage>`). */ @Component({ selector: 'mat-card-title-group', templateUrl: 'card-title-group.html', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, host: {'class': 'mat-mdc-card-title-group'}, }) export class MatCardTitleGroup {} /** * Content of a card, intended for use within `<mat-card>`. This component is an optional * convenience for use with other convenience elements, such as `<mat-card-title>`; any custom * content block element may be used in its place. * * MatCardContent provides no behaviors, instead serving as a purely visual treatment. */ @Directive({ selector: 'mat-card-content', host: {'class': 'mat-mdc-card-content'}, }) export class MatCardContent {} /** * Sub-title of a card, intended for use within `<mat-card>` beneath a `<mat-card-title>`. This * component is an optional convenience for use with other convenience elements, such as * `<mat-card-title>`. * * MatCardSubtitle provides no behaviors, instead serving as a purely visual treatment. */ @Directive({ selector: `mat-card-subtitle, [mat-card-subtitle], [matCardSubtitle]`, host: {'class': 'mat-mdc-card-subtitle'}, }) export class MatCardSubtitle {} /** * Bottom area of a card that contains action buttons, intended for use within `<mat-card>`. * This component is an optional convenience for use with other convenience elements, such as * `<mat-card-content>`; any custom action block element may be used in its place. * * MatCardActions provides no behaviors, instead serving as a purely visual treatment. */ @Directive({ selector: 'mat-card-actions', exportAs: 'matCardActions', host: { 'class': 'mat-mdc-card-actions mdc-card__actions', '[class.mat-mdc-card-actions-align-end]': 'align === "end"', }, }) export class MatCardActions { // TODO(jelbourn): deprecate `align` in favor of `actionPosition` or `actionAlignment` // as to not conflict with the native `align` attribute. /** Position of the actions inside the card. */ @Input() align: 'start' | 'end' = 'start'; // TODO(jelbourn): support `.mdc-card__actions--full-bleed`. // TODO(jelbourn): support `.mdc-card__action-buttons` and `.mdc-card__action-icons`. // TODO(jelbourn): figure out how to use `.mdc-card__action`, `.mdc-card__action--button`, and // `mdc-card__action--icon`. They're used primarily for positioning, which we might be able to // do implicitly. } /** * Header region of a card, intended for use within `<mat-card>`. This header captures * a card title, subtitle, and avatar. This component is an optional convenience for use with * other convenience elements, such as `<mat-card-footer>`; any custom header block element may be * used in its place. * * MatCardHeader provides no behaviors, instead serving as a purely visual treatment. */ @Component({ selector: 'mat-card-header', templateUrl: 'card-header.html', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, host: {'class': 'mat-mdc-card-header'}, }) export class MatCardHeader {} /** * Footer area a card, intended for use within `<mat-card>`. * This component is an optional convenience for use with other convenience elements, such as * `<mat-card-content>`; any custom footer block element may be used in its place. * * MatCardFooter provides no behaviors, instead serving as a purely visual treatment. */ @Directive({ selector: 'mat-card-footer', host: {'class': 'mat-mdc-card-footer'}, }) export class MatCardFooter {} // TODO(jelbourn): deprecate the "image" selectors to replace with "media". // TODO(jelbourn): support `.mdc-card__media-content`. /** * Primary image content for a card, intended for use within `<mat-card>`. Can be applied to * any media element, such as `<img>` or `<picture>`. * * This component is an optional convenience for use with other convenience elements, such as * `<mat-card-content>`; any custom media element may be used in its place. * * MatCardImage provides no behaviors, instead serving as a purely visual treatment. */ @Directive({ selector: '[mat-card-image], [matCardImage]', host: {'class': 'mat-mdc-card-image mdc-card__media'}, }) export class MatCardImage { // TODO(jelbourn): support `.mdc-card__media--square` and `.mdc-card__media--16-9`. } /** Same as `MatCardImage`, but small. */ @Directive({ selector: '[mat-card-sm-image], [matCardImageSmall]', host: {'class': 'mat-mdc-card-sm-image mdc-card__media'}, }) export class MatCardSmImage {} /** Same as `MatCardImage`, but medium. */ @Directive({ selector: '[mat-card-md-image], [matCardImageMedium]', host: {'class': 'mat-mdc-card-md-image mdc-card__media'}, }) export class MatCardMdImage {} /** Same as `MatCardImage`, but large. */ @Directive({ selector: '[mat-card-lg-image], [matCardImageLarge]', host: {'class': 'mat-mdc-card-lg-image mdc-card__media'}, }) export class MatCardLgImage {} /** Same as `MatCardImage`, but extra-large. */ @Directive({ selector: '[mat-card-xl-image], [matCardImageXLarge]', host: {'class': 'mat-mdc-card-xl-image mdc-card__media'}, }) export class MatCardXlImage {} /** * Avatar image content for a card, intended for use within `<mat-card>`. Can be applied to * any media element, such as `<img>` or `<picture>`. * * This component is an optional convenience for use with other convenience elements, such as * `<mat-card-title>`; any custom media element may be used in its place. * * MatCardAvatar provides no behaviors, instead serving as a purely visual treatment. */ @Directive({ selector: '[mat-card-avatar], [matCardAvatar]', host: {'class': 'mat-mdc-card-avatar'}, }) export class MatCardAvatar {}
{ "commit_id": "ea0d1ba7b", "end_byte": 8206, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/card.ts" }
components/src/material/card/README.md_0_95
Please see the official documentation at https://material.angular.io/components/component/card
{ "commit_id": "ea0d1ba7b", "end_byte": 95, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/README.md" }
components/src/material/card/card-header.html_0_305
<ng-content select="[mat-card-avatar], [matCardAvatar]"></ng-content> <div class="mat-mdc-card-header-text"> <ng-content select="mat-card-title, mat-card-subtitle, [mat-card-title], [mat-card-subtitle], [matCardTitle], [matCardSubtitle]"></ng-content> </div> <ng-content></ng-content>
{ "commit_id": "ea0d1ba7b", "end_byte": 305, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/card-header.html" }
components/src/material/card/BUILD.bazel_0_1160
load( "//tools:defaults.bzl", "extract_tokens", "markdown_to_html", "ng_module", "ng_test_library", "ng_web_test_suite", "sass_binary", "sass_library", ) package(default_visibility = ["//visibility:public"]) ng_module( name = "card", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), assets = [":card_scss"] + glob(["**/*.html"]), deps = [ "//src/material/core", ], ) sass_library( name = "card_scss_lib", srcs = glob(["**/_*.scss"]), deps = [ "//src/material/core:core_scss_lib", ], ) sass_binary( name = "card_scss", src = "card.scss", deps = [ "//src/material/core:core_scss_lib", ], ) ng_test_library( name = "unit_test_sources", srcs = glob( ["**/*.spec.ts"], ), deps = [ ":card", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_test_sources"], ) markdown_to_html( name = "overview", srcs = [":card.md"], ) extract_tokens( name = "tokens", srcs = [":card_scss_lib"], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), )
{ "commit_id": "ea0d1ba7b", "end_byte": 1160, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/BUILD.bazel" }
components/src/material/card/card.spec.ts_0_1993
import {ComponentFixture, TestBed} from '@angular/core/testing'; import {Component, Provider, Type, signal} from '@angular/core'; import {MatCardModule} from './module'; import {MatCard, MAT_CARD_CONFIG, MatCardAppearance} from './card'; describe('MatCard', () => { function createComponent<T>(component: Type<T>, providers: Provider[] = []): ComponentFixture<T> { TestBed.configureTestingModule({ imports: [MatCardModule, component], providers, }); return TestBed.createComponent<T>(component); } it('should default the card to the `raised` appearance', () => { const fixture = createComponent(BasicCard); fixture.detectChanges(); const card = fixture.nativeElement.querySelector('.mat-mdc-card'); expect(card.classList).not.toContain('mdc-card--outlined'); }); it('should be able to change the card appearance', () => { const fixture = createComponent(BasicCard); fixture.detectChanges(); const card = fixture.nativeElement.querySelector('.mat-mdc-card'); expect(card.classList).not.toContain('mdc-card--outlined'); fixture.componentInstance.appearance.set('outlined'); fixture.detectChanges(); expect(card.classList).toContain('mdc-card--outlined'); }); it('should be able to change the default card appearance using DI', () => { const fixture = createComponent(BasicCardNoAppearance, [ { provide: MAT_CARD_CONFIG, useValue: {appearance: 'outlined'}, }, ]); fixture.detectChanges(); const card = fixture.nativeElement.querySelector('.mat-mdc-card'); expect(card.classList).toContain('mdc-card--outlined'); }); }); @Component({ template: '<mat-card [appearance]="appearance()"></mat-card>', standalone: true, imports: [MatCard], }) class BasicCard { appearance = signal<MatCardAppearance | undefined>(undefined); } @Component({ template: '<mat-card></mat-card>', standalone: true, imports: [MatCard], }) class BasicCardNoAppearance {}
{ "commit_id": "ea0d1ba7b", "end_byte": 1993, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/card.spec.ts" }
components/src/material/card/index.ts_0_234
/** * @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 */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/index.ts" }
components/src/material/card/testing/card-harness.spec.ts_0_5414
import {Component} from '@angular/core'; import {ComponentFixture, TestBed} from '@angular/core/testing'; import {ComponentHarness, HarnessLoader, parallel} from '@angular/cdk/testing'; import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed'; import {MatCardModule} from '@angular/material/card'; import {MatCardHarness, MatCardSection} from './card-harness'; describe('MatCardHarness', () => { let fixture: ComponentFixture<CardHarnessTest>; let loader: HarnessLoader; beforeEach(() => { TestBed.configureTestingModule({ imports: [MatCardModule, CardHarnessTest], }); fixture = TestBed.createComponent(CardHarnessTest); fixture.detectChanges(); loader = TestbedHarnessEnvironment.loader(fixture); }); it('should find all cards', async () => { const cards = await loader.getAllHarnesses(MatCardHarness); expect(cards.length).toBe(2); }); it('should find card with text', async () => { const cards = await loader.getAllHarnesses(MatCardHarness.with({text: /spitz breed/})); expect(cards.length).toBe(1); expect(await cards[0].getTitleText()).toBe('Shiba Inu'); }); it('should find card with title', async () => { const cards = await loader.getAllHarnesses(MatCardHarness.with({title: 'Shiba Inu'})); expect(cards.length).toBe(1); expect(await cards[0].getTitleText()).toBe('Shiba Inu'); }); it('should find card with subtitle', async () => { const cards = await loader.getAllHarnesses(MatCardHarness.with({subtitle: 'Dog Breed'})); expect(cards.length).toBe(1); expect(await cards[0].getTitleText()).toBe('Shiba Inu'); }); it('should get card text', async () => { const cards = await loader.getAllHarnesses(MatCardHarness); expect(await parallel(() => cards.map(c => c.getText()))).toEqual([ '', 'Shiba InuDog Breed The Shiba Inu is the smallest of the six original and distinct spitz' + ' breeds of dog from Japan. A small, agile dog that copes very well with mountainous' + ' terrain, the Shiba Inu was originally bred for hunting. LIKESHAREWoof woof!', ]); }); it('should get title text', async () => { const cards = await loader.getAllHarnesses(MatCardHarness); expect(await parallel(() => cards.map(c => c.getTitleText()))).toEqual(['', 'Shiba Inu']); }); it('should get subtitle text', async () => { const cards = await loader.getAllHarnesses(MatCardHarness); expect(await parallel(() => cards.map(c => c.getSubtitleText()))).toEqual(['', 'Dog Breed']); }); it('should get a harness loader for the card header', async () => { const card = await loader.getHarness(MatCardHarness.with({title: 'Shiba Inu'})); const headerLoader = await card.getChildLoader(MatCardSection.HEADER); const headerSubcomponents = (await headerLoader?.getAllHarnesses(DummyHarness)) ?? []; expect(headerSubcomponents.length).toBe(2); }); it('should get a harness loader for the card content', async () => { const card = await loader.getHarness(MatCardHarness.with({title: 'Shiba Inu'})); const contentLoader = await card.getChildLoader(MatCardSection.CONTENT); const contentSubcomponents = (await contentLoader?.getAllHarnesses(DummyHarness)) ?? []; expect(contentSubcomponents.length).toBe(1); }); it('should get a harness loader for the card actions', async () => { const card = await loader.getHarness(MatCardHarness.with({title: 'Shiba Inu'})); const actionLoader = await card.getChildLoader(MatCardSection.ACTIONS); const actionSubcomponents = (await actionLoader?.getAllHarnesses(DummyHarness)) ?? []; expect(actionSubcomponents.length).toBe(2); }); it('should get a harness loader for the card footer', async () => { const card = await loader.getHarness(MatCardHarness.with({title: 'Shiba Inu'})); const footerLoader = await card.getChildLoader(MatCardSection.FOOTER); const footerSubcomponents = (await footerLoader?.getAllHarnesses(DummyHarness)) ?? []; expect(footerSubcomponents.length).toBe(1); }); it('should act as a harness loader for user content', async () => { const card = await loader.getHarness(MatCardHarness.with({title: 'Shiba Inu'})); const footerSubcomponents = (await card.getAllHarnesses(DummyHarness)) ?? []; expect(footerSubcomponents.length).toBe(7); }); }); @Component({ template: ` <mat-card></mat-card> <mat-card> <mat-card-header> <div mat-card-avatar></div> <mat-card-title>Shiba Inu</mat-card-title> <mat-card-subtitle>Dog Breed</mat-card-subtitle> </mat-card-header> <div mat-card-image></div> <mat-card-content> <p> The Shiba Inu is the smallest of the six original and distinct spitz breeds of dog from Japan. A small, agile dog that copes very well with mountainous terrain, the Shiba Inu was originally bred for hunting. </p> </mat-card-content> <mat-card-actions> <button mat-button>LIKE</button> <button mat-button>SHARE</button> </mat-card-actions> <mat-card-footer> <div>Woof woof!</div> </mat-card-footer> </mat-card> `, standalone: true, imports: [MatCardModule], }) class CardHarnessTest {} class DummyHarness extends ComponentHarness { static hostSelector = 'div, p, button'; }
{ "commit_id": "ea0d1ba7b", "end_byte": 5414, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/testing/card-harness.spec.ts" }
components/src/material/card/testing/card-harness-filters.ts_0_702
/** * @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 {BaseHarnessFilters} from '@angular/cdk/testing'; /** A set of criteria that can be used to filter a list of `MatCardHarness` instances. */ export interface CardHarnessFilters extends BaseHarnessFilters { /** Only find instances whose text matches the given value. */ text?: string | RegExp; /** Only find instances whose title matches the given value. */ title?: string | RegExp; /** Only find instances whose subtitle matches the given value. */ subtitle?: string | RegExp; }
{ "commit_id": "ea0d1ba7b", "end_byte": 702, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/testing/card-harness-filters.ts" }
components/src/material/card/testing/public-api.ts_0_276
/** * @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 */ export * from './card-harness'; export * from './card-harness-filters';
{ "commit_id": "ea0d1ba7b", "end_byte": 276, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/testing/public-api.ts" }
components/src/material/card/testing/card-harness.ts_0_2347
/** * @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 { ComponentHarnessConstructor, ContentContainerComponentHarness, HarnessPredicate, } from '@angular/cdk/testing'; import {CardHarnessFilters} from './card-harness-filters'; /** Selectors for different sections of the mat-card that can container user content. */ export enum MatCardSection { HEADER = '.mat-mdc-card-header', CONTENT = '.mat-mdc-card-content', ACTIONS = '.mat-mdc-card-actions', FOOTER = '.mat-mdc-card-footer', } /** Harness for interacting with a mat-card in tests. */ export class MatCardHarness extends ContentContainerComponentHarness<MatCardSection> { /** The selector for the host element of a `MatCard` instance. */ static hostSelector = '.mat-mdc-card'; /** * Gets a `HarnessPredicate` that can be used to search for a card with specific attributes. * @param options Options for filtering which card instances are considered a match. * @return a `HarnessPredicate` configured with the given options. */ static with<T extends MatCardHarness>( this: ComponentHarnessConstructor<T>, options: CardHarnessFilters = {}, ): HarnessPredicate<T> { return new HarnessPredicate(this, options) .addOption('text', options.text, (harness, text) => HarnessPredicate.stringMatches(harness.getText(), text), ) .addOption('title', options.title, (harness, title) => HarnessPredicate.stringMatches(harness.getTitleText(), title), ) .addOption('subtitle', options.subtitle, (harness, subtitle) => HarnessPredicate.stringMatches(harness.getSubtitleText(), subtitle), ); } private _title = this.locatorForOptional('.mat-mdc-card-title'); private _subtitle = this.locatorForOptional('.mat-mdc-card-subtitle'); /** Gets all of the card's content as text. */ async getText(): Promise<string> { return (await this.host()).text(); } /** Gets the cards's title text. */ async getTitleText(): Promise<string> { return (await this._title())?.text() ?? ''; } /** Gets the cards's subtitle text. */ async getSubtitleText(): Promise<string> { return (await this._subtitle())?.text() ?? ''; } }
{ "commit_id": "ea0d1ba7b", "end_byte": 2347, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/testing/card-harness.ts" }
components/src/material/card/testing/BUILD.bazel_0_719
load("//tools:defaults.bzl", "ng_test_library", "ng_web_test_suite", "ts_library") package(default_visibility = ["//visibility:public"]) ts_library( name = "testing", srcs = glob( ["**/*.ts"], exclude = ["**/*.spec.ts"], ), deps = [ "//src/cdk/testing", ], ) filegroup( name = "source-files", srcs = glob(["**/*.ts"]), ) ng_test_library( name = "unit_tests_lib", srcs = glob(["**/*.spec.ts"]), deps = [ ":testing", "//src/cdk/testing", "//src/cdk/testing/testbed", "//src/material/card", "@npm//@angular/platform-browser", ], ) ng_web_test_suite( name = "unit_tests", deps = [":unit_tests_lib"], )
{ "commit_id": "ea0d1ba7b", "end_byte": 719, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/testing/BUILD.bazel" }
components/src/material/card/testing/index.ts_0_234
/** * @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 */ export * from './public-api';
{ "commit_id": "ea0d1ba7b", "end_byte": 234, "start_byte": 0, "url": "https://github.com/angular/components/blob/main/src/material/card/testing/index.ts" }