_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material/form-field/_mdc-text-field-structure-overrides.scss_812_9265 | @mixin private-text-field-structure-overrides() {
// Unset the border set by MDC. We move the border (which serves as the Material Design
// text-field bottom line) into its own element. This is necessary because we want the
// bottom-line to span across the whole form-field (including prefixes and suffixes). Also
// we ensure that font styles are inherited for input elements. We do this because inputs by
// default have explicit font styles from the user agent, and we set the desired font styles
// in the parent `mat-form-field` element (for better custom form-field control support).
// Note: We increase specificity here because the MDC textfield seems to override this,
// depending on the CSS order, with an affix selector joint with the input.
.mat-mdc-form-field-input-control.mat-mdc-form-field-input-control {
@include vendor-prefixes.smooth-font();
font: inherit;
letter-spacing: inherit;
text-decoration: inherit;
text-transform: inherit;
border: none;
}
.mat-mdc-form-field .mat-mdc-floating-label.mdc-floating-label {
@include vendor-prefixes.smooth-font();
// In order to ensure proper alignment of the floating label, we reset its line-height.
// The line-height is not important as the element is absolutely positioned and only has one
// line of text.
line-height: normal;
// This allows users to focus the input by clicking the part of the label above the outline box,
// and makes migration from the legacy form-field easier for tests that were depending on
// clicking the label to focus the input.
pointer-events: all;
@if ($_enable-form-field-will-change-reset) {
will-change: auto;
}
}
.mat-mdc-form-field:not(.mat-form-field-disabled) .mat-mdc-floating-label.mdc-floating-label {
// Style the cursor the same way as the rest of the input
cursor: inherit;
}
// Reset the height that MDC sets on native input elements. We cannot rely on their
// fixed height as we handle vertical spacing differently. MDC sets a fixed height for
// inputs and modifies the baseline so that the textfield matches the spec. This does
// not work for us since we support arbitrary form field controls which don't necessarily
// use an `input` element. We organize the vertical spacing on the infix container.
.mdc-text-field--no-label:not(.mdc-text-field--textarea)
.mat-mdc-form-field-input-control.mdc-text-field__input,
.mat-mdc-text-field-wrapper .mat-mdc-form-field-input-control {
height: auto;
}
// Color inputs are a special case, because setting their height to
// `auto` will collapse them. The height value is an arbitrary number
// which was extracted from the user agent styles of Chrome and Firefox.
.mat-mdc-text-field-wrapper
.mat-mdc-form-field-input-control.mdc-text-field__input[type='color'] {
height: 23px;
}
// Root element of the mdc-text-field. As explained in the height overwrites above, MDC
// sets a default height on the text-field root element. This is not desired since we
// want the element to be able to expand as needed.
.mat-mdc-text-field-wrapper {
height: auto;
flex: auto;
@if ($_enable-form-field-will-change-reset) {
will-change: auto;
}
}
// The icon prefix/suffix is closer to the edge of the form-field than the infix is in a
// form-field with no prefix/suffix. Therefore the standard padding has to be removed when showing
// an icon prefix or suffix. We can't rely on MDC's styles for this because we use a different
// structure for our form-field in order to support arbitrary height input elements.
.mat-mdc-form-field-has-icon-prefix .mat-mdc-text-field-wrapper {
padding-left: 0;
// Signal to the TypeScript label calculation code that the label should be offset 16px less
// due to resetting the padding above.
--mat-mdc-form-field-label-offset-x: -16px;
}
.mat-mdc-form-field-has-icon-suffix .mat-mdc-text-field-wrapper {
padding-right: 0;
}
[dir='rtl'] {
// Undo the above padding removals which only apply in LTR languages.
.mat-mdc-text-field-wrapper {
padding-left: 16px;
padding-right: 16px;
}
// ...and apply the correct padding resets for RTL languages.
.mat-mdc-form-field-has-icon-suffix .mat-mdc-text-field-wrapper {
padding-left: 0;
}
.mat-mdc-form-field-has-icon-prefix .mat-mdc-text-field-wrapper {
padding-right: 0;
}
}
// Before the switch to the tokens MDC was setting a specific placeholder color when the input
// is disabled, but now there's no token for it so we need to implement it ourselves.
.mat-form-field-disabled .mdc-text-field__input {
@include vendor-prefixes.input-placeholder {
@include token-utils.use-tokens(
tokens-mat-form-field.$prefix, tokens-mat-form-field.get-token-slots()) {
@include token-utils.create-token-slot(color, disabled-input-text-placeholder-color);
}
}
}
// The default MDC text-field implementation does not support labels which always float.
// MDC only renders the placeholder if the input is focused. We extend this to show the
// placeholder if the form-field label is set to always float.
// TODO(devversion): consider getting a mixin or variables for this (currently not available).
// Stylelint no-prefixes rule disabled because MDC text-field only uses "::placeholder" too.
// stylelint-disable-next-line material/no-prefixes
.mat-mdc-form-field-label-always-float .mdc-text-field__input::placeholder {
transition-delay: 40ms;
transition-duration: 110ms;
opacity: 1;
}
// Since we moved the horizontal spacing from the input to the form-field flex container
// and the MDC floating label tries to account for the horizontal spacing, we need to reset
// the shifting since there is no padding the label needs to account for. Note that we do not
// want do this for labels in the notched-outline since MDC keeps those labels relative to
// the notched outline container, and already applies a specific horizontal spacing which
// we do not want to overwrite. *Note*: We need to have increased specificity for this
// override because the `right` property will be set with higher specificity in RTL mode.
.mat-mdc-text-field-wrapper .mat-mdc-form-field-infix .mat-mdc-floating-label {
left: auto;
right: auto;
}
// MDC sets the input elements in outline appearance to "display: flex". There seems to
// be no particular reason why this is needed. We set it to "inline-block", as it otherwise
// could shift the baseline.
.mat-mdc-text-field-wrapper.mdc-text-field--outlined .mdc-text-field__input {
display: inline-block;
}
// As mentioned in the override before, MDC aligns the label using percentage. This means that
// MDC tries to offset the label when the parent element changes in the notched-outline. For
// example, the outline stroke width changes on focus. Since we updated the label to use a fixed
// position, we don't need the vertical offsetting (that will shift the label incorrectly now).
// Note: Increased specificity needed here since MDC overwrites the padding on `:focus`.
.mat-mdc-form-field .mat-mdc-text-field-wrapper.mdc-text-field .mdc-notched-outline__notch {
padding-top: 0;
}
// This fixes an issue where the notch appears to be thicker than the rest of the outline when
// zoomed in on Chrome. The border inconsistency seems to be some kind of rendering artifact
// that arises from a combination of the fact that the notch contains text, while the leading
// and trailing outline do not, combined with the fact that the border is semi-transparent.
// Experimentally, I discovered that adding a transparent left border fixes the inconsistency.
// Note: class name is repeated to achieve sufficient specificity over the various MDC states.
// (hover, focus, etc.)
// TODO(mmalerba): port this fix into MDC
.mat-mdc-form-field.mat-mdc-form-field.mat-mdc-form-field.mat-mdc-form-field {
&.mat-mdc-form-field.mat-mdc-form-field .mdc-notched-outline__notch {
border-left: 1px solid transparent;
}
}
[dir='rtl'] .mat-mdc-form-field.mat-mdc-form-field.mat-mdc-form-field.mat-mdc-form-field {
&.mat-mdc-form-field.mat-mdc-form-field .mdc-notched-outline__notch {
border-left: none;
border-right: 1px solid transparent;
}
}
} | {
"end_byte": 9265,
"start_byte": 812,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/_mdc-text-field-structure-overrides.scss"
} |
components/src/material/form-field/_form-field-focus-overlay.scss_0_1461 | @use '../core/tokens/m2/mat/form-field' as tokens-mat-form-field;
@use '../core/tokens/token-utils';
@use '../core/style/layout-common';
// MDC text-field used to use their ripple in order to show a focus and hover effect for
// text-fields. This is unnecessary because the ripples bring in a lot of unnecessary
// styles and runtime code while the actual goal for the text-field is simply showing a
// focus and hover effect. The ripples will unnecessarily provide CSS selectors and JS
// runtime code for launching interaction ripples at pointer location. This is not needed
// for the text-field, so we create our own minimal focus overlay styles. Our focus overlay
// uses the exact same logic to compute the colors as in the default MDC text-field ripples.
@mixin private-form-field-focus-overlay() {
.mat-mdc-form-field-focus-overlay {
@include layout-common.fill;
opacity: 0;
pointer-events: none; // Make sure we don't block click on the prefix/suffix.
@include token-utils.use-tokens(
tokens-mat-form-field.$prefix, tokens-mat-form-field.get-token-slots()) {
@include token-utils.create-token-slot(background-color, state-layer-color);
.mat-mdc-text-field-wrapper:hover & {
@include token-utils.create-token-slot(opacity, hover-state-layer-opacity);
}
.mat-mdc-form-field.mat-focused & {
@include token-utils.create-token-slot(opacity, focus-state-layer-opacity);
}
}
}
}
| {
"end_byte": 1461,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/_form-field-focus-overlay.scss"
} |
components/src/material/form-field/public-api.ts_0_557 | /**
* @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 './directives/label';
export * from './directives/error';
export * from './directives/hint';
export * from './directives/prefix';
export * from './directives/suffix';
export * from './form-field';
export * from './module';
export * from './form-field-control';
export * from './form-field-errors';
export * from './form-field-animations';
| {
"end_byte": 557,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/public-api.ts"
} |
components/src/material/form-field/form-field.md_0_7585 | `<mat-form-field>` is a component used to wrap several Angular Material components and apply common
[Text field](https://material.io/guidelines/components/text-fields.html) styles such as the
underline, floating label, and hint messages.
In this document, "form field" refers to the wrapper component `<mat-form-field>` and
"form field control" refers to the component that the `<mat-form-field>` is wrapping
(e.g. the input, textarea, select, etc.)
The following Angular Material components are designed to work inside a `<mat-form-field>`:
- [`<input matNativeControl>` & `<textarea matNativeControl>`](https://material.angular.io/components/input/overview)
- [`<select matNativeControl>`](https://material.angular.io/components/select/overview)
- [`<mat-select>`](https://material.angular.io/components/select/overview)
- [`<mat-chip-list>`](https://material.angular.io/components/chips/overview)
<!-- example(form-field-overview) -->
### Form field appearance variants
`mat-form-field` supports two different appearance variants which can be set via the `appearance`
input: `fill` and `outline`. The `fill` appearance displays the form field with a filled background
box and an underline, while the `outline` appearance shows the form field with a border all the way
around.
Out of the box, if you do not specify an `appearance` for the `<mat-form-field>` it will default to
`fill`. However, this can be configured using a global provider to choose a different default
appearance for your app.
```ts
@NgModule({
providers: [
{provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: {appearance: 'outline'}}
]
})
```
<!-- example(form-field-appearance) -->
### Floating label
The floating label is a text label displayed on top of the form field control when
the control does not contain any text or when `<select matNativeControl>` does not show any option
text. By default, when text is present the floating label floats above the form field control. The
label for a form field can be specified by adding a `mat-label` element.
If the form field control is marked with a `required` attribute, an asterisk will be appended to the
label to indicate the fact that it is a required field. If unwanted, this can be disabled by
setting the `hideRequiredMarker` property on `<mat-form-field>`
The `floatLabel` property of `<mat-form-field>` can be used to change this default floating
behavior. It can be set to `always` to float the label even when no text is present in the form
field control, or to `auto` to restore the default behavior.
<!-- example(form-field-label) -->
The floating label behavior can be adjusted globally by providing a value for
`MAT_FORM_FIELD_DEFAULT_OPTIONS` in your application's root module. Like the `floatLabel` input,
the option can be either set to `always` or `auto`.
```ts
@NgModule({
providers: [
{provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: {floatLabel: 'always'}}
]
})
```
### Hint labels
Hint labels are additional descriptive text that appears below the form field's underline. A
`<mat-form-field>` can have up to two hint labels; one start-aligned (left in an LTR language, right
in RTL), and one end-aligned.
Hint labels are specified in one of two ways: either by using the `hintLabel` property of
`<mat-form-field>`, or by adding a `<mat-hint>` element inside the form field. When adding a hint
via the `hintLabel` property, it will be treated as the start hint. Hints added via the
`<mat-hint>` hint element can be added to either side by setting the `align` property on
`<mat-hint>` to either `start` or `end`. Attempting to add multiple hints to the same side will
raise an error.
<!-- example(form-field-hint) -->
### Error messages
Error messages can be shown under the form field underline by adding `mat-error` elements inside the
form field. Errors are hidden initially and will be displayed on invalid form fields after the user
has interacted with the element or the parent form has been submitted. Since the errors occupy the
same space as the hints, the hints are hidden when the errors are shown.
If a form field can have more than one error state, it is up to the consumer to toggle which
messages should be displayed. This can be done with CSS, `@if` or `@switch`. Multiple error
messages can be shown at the same time if desired, but the `<mat-form-field>` only reserves enough
space to display one error message at a time. Ensuring that enough space is available to display
multiple errors is up to the user.
<!-- example(form-field-error) -->
### Prefix & suffix
Custom content can be included before and after the input tag, as a prefix or suffix. It will be
included within the visual container that wraps the form control as per the Material specification.
Adding the `matPrefix` directive to an element inside the `<mat-form-field>` will designate it as
the prefix. Similarly, adding `matSuffix` will designate it as the suffix.
If the prefix/suffix content is purely text-based, it is recommended to use the `matTextPrefix` or
`matTextSuffix` directives which ensure that the text is aligned with the form control.
<!-- example(form-field-prefix-suffix) -->
### Custom form field controls
In addition to the form field controls that Angular Material provides, it is possible to create
custom form field controls that work with `<mat-form-field>` in the same way. For additional
information on this see the guide on
[Creating Custom mat-form-field Controls](/guide/creating-a-custom-form-field-control).
### Theming
The color of the form-field can be changed by specifying a `$color-variant` when applying the
`mat.form-field-theme` or `mat.form-field-color` mixins (see the
[theming guide](/guide/theming#using-component-color-variants) to learn more.) By default, the
form-field uses the theme's primary palette. This can be changed to `'secondary'`, `'tertiary'`, or
`'error'`.
### Accessibility
By itself, `MatFormField` does not apply any additional accessibility treatment to a control.
However, several of the form field's optional features interact with the control contained within
the form field.
When you provide a label via `<mat-label>`, `MatFormField` automatically associates this label with
the field's control via a native `<label>` element, using the `for` attribute to reference the
control's ID.
If a floating label is specified, it will be automatically used as the label for the form
field control. If no floating label is specified, the user should label the form field control
themselves using `aria-label`, `aria-labelledby` or `<label for=...>`.
When you provide informational text via `<mat-hint>` or `<mat-error>`, `MatFormField` automatically
adds these elements' IDs to the control's `aria-describedby` attribute. Additionally, `MatError`
applies `aria-live="polite"` by default such that assistive technology will announce errors when
they appear.
### Troubleshooting
#### Error: A hint was already declared for align="..."
This error occurs if you have added multiple hints for the same side. Keep in mind that the
`hintLabel` property adds a hint to the start side.
#### Error: mat-form-field must contain a MatFormFieldControl
This error occurs when you have not added a form field control to your form field. If your form
field contains a native `<input>` or `<textarea>` element, make sure you've added the `matInput`
directive to it and have imported `MatInputModule`. Other components that can act as a form field
control include `<mat-select>`, `<mat-chip-list>`, and any custom form field controls you've
created.
| {
"end_byte": 7585,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field.md"
} |
components/src/material/form-field/_mdc-text-field-structure.scss_0_7267 | @use '@angular/cdk';
@use '../core/style/vendor-prefixes';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mdc/filled-text-field' as tokens-mdc-filled-text-field;
@use '../core/tokens/m2/mdc/outlined-text-field' as tokens-mdc-outlined-text-field;
// Includes the structural styles for the form field inherited from MDC.
@mixin private-text-field-structure {
$filled-slots: (
tokens-mdc-filled-text-field.$prefix,
tokens-mdc-filled-text-field.get-token-slots()
);
$outlined-slots: (
tokens-mdc-outlined-text-field.$prefix,
tokens-mdc-outlined-text-field.get-token-slots()
);
.mdc-text-field {
display: inline-flex;
align-items: baseline;
padding: 0 16px;
position: relative;
box-sizing: border-box;
overflow: hidden;
will-change: opacity, transform, color;
// TODO(crisbeto): The filled form field overrides these while the outlined doesn't.
// The correct thing to do would be to remove them from here and have the one based on the
// token in the outlined appearance. We keep them as is for now to avoid screenshot diffs.
border-top-left-radius: 4px;
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.mdc-text-field__input {
width: 100%;
min-width: 0;
border: none;
border-radius: 0;
background: none;
padding: 0;
-moz-appearance: none;
-webkit-appearance: none;
// TODO(crisbeto): this height gets overwritten eventually, but there are some internal
// tests that depend on this being here in weird ways so we're keeping it around for now.
height: 28px;
// Note that while this style and the `-ms-clear` are identical, we can't combine
// them because if one of them isn't supported, it'll invalidate the whole rule.
&::-webkit-calendar-picker-indicator {
display: none;
}
&::-ms-clear {
display: none;
}
&:focus {
outline: none;
}
&:invalid {
box-shadow: none;
}
@include vendor-prefixes.input-placeholder {
opacity: 0;
}
.mdc-text-field--no-label &,
.mdc-text-field--focused & {
@include vendor-prefixes.input-placeholder {
opacity: 1;
}
}
.mdc-text-field--disabled:not(.mdc-text-field--no-label) &.mat-mdc-input-disabled-interactive {
@include vendor-prefixes.input-placeholder {
opacity: 0;
}
}
.mdc-text-field--outlined &,
.mdc-text-field--filled.mdc-text-field--no-label & {
height: 100%;
}
.mdc-text-field--outlined & {
display: flex;
border: none !important;
background-color: transparent;
}
.mdc-text-field--disabled & {
pointer-events: auto;
}
@include token-utils.use-tokens($filled-slots...) {
@include _input-tokens('.mdc-text-field--filled');
}
@include token-utils.use-tokens($outlined-slots...) {
@include _input-tokens('.mdc-text-field--outlined');
}
@include cdk.high-contrast {
.mdc-text-field--disabled & {
background-color: Window;
}
}
}
.mdc-text-field--filled {
height: 56px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
@include token-utils.use-tokens($filled-slots...) {
@include token-utils.create-token-slot(border-top-left-radius, container-shape);
@include token-utils.create-token-slot(border-top-right-radius, container-shape);
&:not(.mdc-text-field--disabled) {
@include token-utils.create-token-slot(background-color, container-color);
}
&.mdc-text-field--disabled {
@include token-utils.create-token-slot(background-color, disabled-container-color);
}
}
}
.mdc-text-field--outlined {
height: 56px;
overflow: visible;
@include token-utils.use-tokens($outlined-slots...) {
$shape-var: token-utils.get-token-variable(container-shape);
padding-right: max(16px, #{$shape-var});
padding-left: max(16px, calc(#{$shape-var} + 4px));
[dir='rtl'] & {
padding-right: max(16px, calc(#{$shape-var} + 4px));
padding-left: max(16px, #{$shape-var});
}
}
}
.mdc-floating-label {
position: absolute;
left: 0;
transform-origin: left top;
line-height: 1.15rem;
text-align: left;
text-overflow: ellipsis;
white-space: nowrap;
cursor: text;
overflow: hidden;
will-change: transform;
[dir='rtl'] & {
right: 0;
left: auto;
transform-origin: right top;
text-align: right;
}
.mdc-text-field & {
top: 50%;
transform: translateY(-50%);
pointer-events: none;
}
.mdc-notched-outline & {
display: inline-block;
position: relative;
max-width: 100%;
}
.mdc-text-field--outlined & {
left: 4px;
right: auto;
}
[dir='rtl'] .mdc-text-field--outlined & {
left: auto;
right: 4px;
}
.mdc-text-field--filled & {
left: 16px;
right: auto;
}
[dir='rtl'] .mdc-text-field--filled & {
left: auto;
right: 16px;
}
.mdc-text-field--disabled & {
cursor: default;
@include cdk.high-contrast {
z-index: 1;
}
}
.mdc-text-field--filled.mdc-text-field--no-label & {
display: none;
}
@include token-utils.use-tokens($filled-slots...) {
@include _floating-label-tokens('.mdc-text-field--filled');
}
@include token-utils.use-tokens($outlined-slots...) {
@include _floating-label-tokens('.mdc-text-field--outlined');
}
}
.mdc-floating-label--float-above {
cursor: auto;
transform: translateY(-106%) scale(0.75);
.mdc-text-field--filled & {
transform: translateY(-106%) scale(0.75);
}
.mdc-text-field--outlined & {
transform: translateY(-37.25px) scale(1);
font-size: 0.75rem;
}
.mdc-notched-outline & {
text-overflow: clip;
}
.mdc-notched-outline--upgraded & {
max-width: 133.3333333333%;
}
.mdc-text-field--outlined.mdc-notched-outline--upgraded &,
.mdc-text-field--outlined .mdc-notched-outline--upgraded & {
transform: translateY(-34.75px) scale(0.75);
}
.mdc-text-field--outlined.mdc-notched-outline--upgraded &,
.mdc-text-field--outlined .mdc-notched-outline--upgraded & {
font-size: 1rem;
}
}
.mdc-floating-label--required {
&:not(.mdc-floating-label--hide-required-marker)::after {
margin-left: 1px;
margin-right: 0;
content: '*';
[dir='rtl'] & {
margin-left: 0;
margin-right: 1px;
}
}
}
.mdc-notched-outline {
display: flex;
position: absolute;
top: 0;
right: 0;
left: 0;
box-sizing: border-box;
width: 100%;
max-width: 100%;
height: 100%;
text-align: left;
pointer-events: none;
[dir='rtl'] & {
text-align: right;
}
.mdc-text-field--outlined & {
z-index: 1;
}
}
.mat-mdc-notch-piece {
box-sizing: border-box;
height: 100%;
pointer-events: none;
border-top: 1px solid;
border-bottom: 1px solid;
.mdc-text-field--focused & {
border-width: 2px;
}
@include token-utils | {
"end_byte": 7267,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/_mdc-text-field-structure.scss"
} |
components/src/material/form-field/_mdc-text-field-structure.scss_7267_15558 | .use-tokens($outlined-slots...) {
// Moved out into variables because the selectors we inherited were too long.
$enabled-selector: '.mdc-text-field--outlined:not(.mdc-text-field--disabled)';
$hover-selector: ':not(.mdc-text-field--focused):hover';
#{$enabled-selector} & {
@include token-utils.create-token-slot(border-color, outline-color);
@include token-utils.create-token-slot(border-width, outline-width);
}
#{$enabled-selector}#{$hover-selector} & {
@include token-utils.create-token-slot(border-color, hover-outline-color);
}
#{$enabled-selector}.mdc-text-field--focused & {
@include token-utils.create-token-slot(border-color, focus-outline-color);
}
.mdc-text-field--outlined.mdc-text-field--disabled & {
@include token-utils.create-token-slot(border-color, disabled-outline-color);
}
#{$enabled-selector}.mdc-text-field--invalid & {
@include token-utils.create-token-slot(border-color, error-outline-color);
}
#{$enabled-selector}.mdc-text-field--invalid#{$hover-selector} .mdc-notched-outline & {
@include token-utils.create-token-slot(border-color, error-hover-outline-color);
}
#{$enabled-selector}.mdc-text-field--invalid.mdc-text-field--focused & {
@include token-utils.create-token-slot(border-color, error-focus-outline-color);
}
#{$enabled-selector}.mdc-text-field--focused .mdc-notched-outline & {
@include token-utils.create-token-slot(border-width, focus-outline-width);
}
}
}
.mdc-notched-outline__leading {
border-left: 1px solid;
border-right: none;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
@include token-utils.use-tokens($outlined-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);
.mdc-text-field--outlined .mdc-notched-outline & {
$shape-var: token-utils.get-token-variable(container-shape);
width: max(12px, #{$shape-var});
}
}
[dir='rtl'] & {
border-left: none;
border-right: 1px solid;
border-bottom-left-radius: 0;
border-top-left-radius: 0;
@include token-utils.use-tokens($outlined-slots...) {
@include token-utils.create-token-slot(border-top-right-radius, container-shape);
@include token-utils.create-token-slot(border-bottom-right-radius, container-shape);
}
}
}
.mdc-notched-outline__trailing {
flex-grow: 1;
border-left: none;
border-right: 1px solid;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
@include token-utils.use-tokens($outlined-slots...) {
@include token-utils.create-token-slot(border-top-right-radius, container-shape);
@include token-utils.create-token-slot(border-bottom-right-radius, container-shape);
}
[dir='rtl'] & {
border-left: 1px solid;
border-right: none;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
@include token-utils.use-tokens($outlined-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);
}
}
}
.mdc-notched-outline__notch {
flex: 0 0 auto;
width: auto;
@include token-utils.use-tokens($outlined-slots...) {
.mdc-text-field--outlined .mdc-notched-outline & {
$shape-var: token-utils.get-token-variable(container-shape);
max-width: min(
var(--mat-form-field-notch-max-width, 100%),
calc(100% - max(12px, #{$shape-var}) * 2)
);
}
}
.mdc-text-field--outlined .mdc-notched-outline--notched & {
padding-top: 1px;
}
.mdc-text-field--focused.mdc-text-field--outlined .mdc-notched-outline--notched & {
padding-top: 2px;
}
.mdc-notched-outline--notched & {
padding-left: 0;
padding-right: 8px;
border-top: none;
--mat-form-field-notch-max-width: 100%;
}
[dir='rtl'] .mdc-notched-outline--notched & {
padding-left: 8px;
padding-right: 0;
}
.mdc-notched-outline--no-label & {
display: none;
}
}
.mdc-line-ripple {
&::before,
&::after {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
border-bottom-style: solid;
content: '';
}
&::before {
z-index: 1;
@include token-utils.use-tokens($filled-slots...) {
$enabled-field: '.mdc-text-field--filled:not(.mdc-text-field--disabled)';
@include token-utils.create-token-slot(border-bottom-width, active-indicator-height);
#{$enabled-field} & {
@include token-utils.create-token-slot(border-bottom-color, active-indicator-color);
}
#{$enabled-field}:not(.mdc-text-field--focused):hover & {
@include token-utils.create-token-slot(border-bottom-color, hover-active-indicator-color);
}
.mdc-text-field--filled.mdc-text-field--disabled & {
@include token-utils.create-token-slot(
border-bottom-color,
disabled-active-indicator-color
);
}
#{$enabled-field}.mdc-text-field--invalid & {
@include token-utils.create-token-slot(border-bottom-color, error-active-indicator-color);
}
#{$enabled-field}.mdc-text-field--invalid:not(.mdc-text-field--focused):hover & {
@include token-utils.create-token-slot(
border-bottom-color,
error-hover-active-indicator-color
);
}
}
}
&::after {
transform: scaleX(0);
opacity: 0;
z-index: 2;
@include token-utils.use-tokens($filled-slots...) {
.mdc-text-field--filled & {
@include token-utils.create-token-slot(
border-bottom-width,
focus-active-indicator-height
);
}
.mdc-text-field--filled:not(.mdc-text-field--disabled) & {
@include token-utils.create-token-slot(border-bottom-color, focus-active-indicator-color);
}
.mdc-text-field--filled.mdc-text-field--invalid:not(.mdc-text-field--disabled) & {
@include token-utils.create-token-slot(
border-bottom-color,
error-focus-active-indicator-color
);
}
}
}
}
.mdc-line-ripple--active::after {
transform: scaleX(1);
opacity: 1;
}
.mdc-line-ripple--deactivating::after {
opacity: 0;
}
.mdc-text-field--disabled {
pointer-events: none;
}
}
// Includes the tokens for the floating label for a specific form field variant.
@mixin _floating-label-tokens($selector) {
$enabled-field: '#{$selector}:not(.mdc-text-field--disabled)';
#{$enabled-field} & {
@include token-utils.create-token-slot(color, label-text-color);
}
#{$enabled-field}.mdc-text-field--focused & {
@include token-utils.create-token-slot(color, focus-label-text-color);
}
#{$enabled-field}:not(.mdc-text-field--focused):hover & {
@include token-utils.create-token-slot(color, hover-label-text-color);
}
#{$selector}.mdc-text-field--disabled & {
@include token-utils.create-token-slot(color, disabled-label-text-color);
}
#{$enabled-field}.mdc-text-field--invalid & {
@include token-utils.create-token-slot(color, error-label-text-color);
}
#{$enabled-field}.mdc-text-field--invalid.mdc-text-field--focused & {
@include token-utils.create-token-slot(color, error-focus-label-text-color);
}
#{$enabled-field}.mdc-text-field--invalid:not(.mdc-text-field--disabled):hover & {
@include token-utils.create-token-slot(color, error-hover-label-text-color);
}
#{$selector} & {
@include token-utils.create-token-slot(font-family, label-text-font);
@include token-utils.create-token-slot(font-size, label-text-size);
@include token-utils.create-token-slot(font-weight, label-text-weight);
@include token-utils.create-token-slot(letter-spacing, label-text-tracking);
}
}
// Includes the tokens for the input for a specific form field variant. | {
"end_byte": 15558,
"start_byte": 7267,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/_mdc-text-field-structure.scss"
} |
components/src/material/form-field/_mdc-text-field-structure.scss_15559_17139 | @mixin _input-tokens($selector) {
#{$selector}:not(.mdc-text-field--disabled) & {
@include token-utils.create-token-slot(color, input-text-color);
@include token-utils.create-token-slot(caret-color, caret-color);
@include vendor-prefixes.input-placeholder {
@include token-utils.create-token-slot(color, input-text-placeholder-color);
}
}
#{$selector}.mdc-text-field--invalid:not(.mdc-text-field--disabled) & {
@include token-utils.create-token-slot(caret-color, error-caret-color);
}
#{$selector}.mdc-text-field--disabled & {
@include token-utils.create-token-slot(color, disabled-input-text-color);
}
}
// Includes the animation styles for the form field inherited from MDC.
@mixin private-text-field-animations {
$timing-curve: cubic-bezier(0.4, 0, 0.2, 1);
.mdc-floating-label {
transition:
transform 150ms $timing-curve,
color 150ms $timing-curve;
}
.mdc-text-field__input {
transition: opacity 150ms $timing-curve;
@include vendor-prefixes.input-placeholder {
transition: opacity 67ms $timing-curve;
}
}
&.mdc-text-field--no-label,
&.mdc-text-field--focused {
.mdc-text-field__input {
@include vendor-prefixes.input-placeholder {
transition-delay: 40ms;
transition-duration: 110ms;
}
}
}
.mdc-text-field--filled:not(.mdc-ripple-upgraded):focus .mdc-text-field__ripple::before {
transition-duration: 75ms;
}
.mdc-line-ripple::after {
transition:
transform 180ms $timing-curve,
opacity 180ms $timing-curve;
}
} | {
"end_byte": 17139,
"start_byte": 15559,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/_mdc-text-field-structure.scss"
} |
components/src/material/form-field/form-field.html_0_4506 | <ng-template #labelTemplate>
<!--
MDC recommends that the text-field is a `<label>` element. This rather complicates the
setup because it would require every form-field control to explicitly set `aria-labelledby`.
This is because the `<label>` itself contains more than the actual label (e.g. prefix, suffix
or other projected content), and screen readers could potentially read out undesired content.
Excluding elements from being printed out requires them to be marked with `aria-hidden`, or
the form control is set to a scoped element for the label (using `aria-labelledby`). Both of
these options seem to complicate the setup because we know exactly what content is rendered
as part of the label, and we don't want to spend resources on walking through projected content
to set `aria-hidden`. Nor do we want to set `aria-labelledby` on every form control if we could
simply link the label to the control using the label `for` attribute.
-->
@if (_hasFloatingLabel()) {
<label
matFormFieldFloatingLabel
[floating]="_shouldLabelFloat()"
[monitorResize]="_hasOutline()"
[id]="_labelId"
[attr.for]="_control.disableAutomaticLabeling ? null : _control.id"
>
<ng-content select="mat-label"></ng-content>
<!--
We set the required marker as a separate element, in order to make it easier to target if
apps want to override it and to be able to set `aria-hidden` so that screen readers don't
pick it up.
-->
@if (!hideRequiredMarker && _control.required) {
<span
aria-hidden="true"
class="mat-mdc-form-field-required-marker mdc-floating-label--required"
></span>
}
</label>
}
</ng-template>
<div
class="mat-mdc-text-field-wrapper mdc-text-field"
#textField
[class.mdc-text-field--filled]="!_hasOutline()"
[class.mdc-text-field--outlined]="_hasOutline()"
[class.mdc-text-field--no-label]="!_hasFloatingLabel()"
[class.mdc-text-field--disabled]="_control.disabled"
[class.mdc-text-field--invalid]="_control.errorState"
(click)="_control.onContainerClick($event)"
>
@if (!_hasOutline() && !_control.disabled) {
<div class="mat-mdc-form-field-focus-overlay"></div>
}
<div class="mat-mdc-form-field-flex">
@if (_hasOutline()) {
<div matFormFieldNotchedOutline [matFormFieldNotchedOutlineOpen]="_shouldLabelFloat()">
@if (!_forceDisplayInfixLabel()) {
<ng-template [ngTemplateOutlet]="labelTemplate"></ng-template>
}
</div>
}
@if (_hasIconPrefix) {
<div class="mat-mdc-form-field-icon-prefix" #iconPrefixContainer>
<ng-content select="[matPrefix], [matIconPrefix]"></ng-content>
</div>
}
@if (_hasTextPrefix) {
<div class="mat-mdc-form-field-text-prefix" #textPrefixContainer>
<ng-content select="[matTextPrefix]"></ng-content>
</div>
}
<div class="mat-mdc-form-field-infix">
@if (!_hasOutline() || _forceDisplayInfixLabel()) {
<ng-template [ngTemplateOutlet]="labelTemplate"></ng-template>
}
<ng-content></ng-content>
</div>
@if (_hasTextSuffix) {
<div class="mat-mdc-form-field-text-suffix" #textSuffixContainer>
<ng-content select="[matTextSuffix]"></ng-content>
</div>
}
@if (_hasIconSuffix) {
<div class="mat-mdc-form-field-icon-suffix" #iconSuffixContainer>
<ng-content select="[matSuffix], [matIconSuffix]"></ng-content>
</div>
}
</div>
@if (!_hasOutline()) {
<div matFormFieldLineRipple></div>
}
</div>
<div
class="mat-mdc-form-field-subscript-wrapper mat-mdc-form-field-bottom-align"
[class.mat-mdc-form-field-subscript-dynamic-size]="subscriptSizing === 'dynamic'"
>
@switch (_getDisplayedMessages()) {
@case ('error') {
<div
class="mat-mdc-form-field-error-wrapper"
[@transitionMessages]="_subscriptAnimationState"
>
<ng-content select="mat-error, [matError]"></ng-content>
</div>
}
@case ('hint') {
<div class="mat-mdc-form-field-hint-wrapper" [@transitionMessages]="_subscriptAnimationState">
@if (hintLabel) {
<mat-hint [id]="_hintLabelId">{{hintLabel}}</mat-hint>
}
<ng-content select="mat-hint:not([align='end'])"></ng-content>
<div class="mat-mdc-form-field-hint-spacer"></div>
<ng-content select="mat-hint[align='end']"></ng-content>
</div>
}
}
</div>
| {
"end_byte": 4506,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field.html"
} |
components/src/material/form-field/_form-field-theme.scss_0_7957 | @use '../core/tokens/m2/mdc/filled-text-field' as tokens-mdc-filled-text-field;
@use '../core/tokens/m2/mdc/outlined-text-field' as tokens-mdc-outlined-text-field;
@use '../core/tokens/m2/mat/form-field' as tokens-mat-form-field;
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/style/sass-utils';
@use '../core/tokens/token-utils';
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-form-field.
/// @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-filled-text-field.$prefix,
tokens-mdc-filled-text-field.get-unthemable-tokens()
);
@include token-utils.create-token-values(
tokens-mdc-outlined-text-field.$prefix,
tokens-mdc-outlined-text-field.get-unthemable-tokens()
);
@include token-utils.create-token-values(
tokens-mat-form-field.$prefix,
tokens-mat-form-field.get-unthemable-tokens()
);
}
}
}
/// Outputs color theme styles for the mat-form-field.
/// @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 form field: 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 {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mdc-filled-text-field.$prefix,
tokens-mdc-filled-text-field.get-color-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mdc-outlined-text-field.$prefix,
tokens-mdc-outlined-text-field.get-color-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-form-field.$prefix,
tokens-mat-form-field.get-color-tokens($theme)
);
}
.mat-mdc-form-field.mat-accent {
@include token-utils.create-token-values(
tokens-mdc-filled-text-field.$prefix,
tokens-mdc-filled-text-field.private-get-color-palette-color-tokens($theme, accent)
);
@include token-utils.create-token-values(
tokens-mdc-outlined-text-field.$prefix,
tokens-mdc-outlined-text-field.private-get-color-palette-color-tokens($theme, accent)
);
@include token-utils.create-token-values(
tokens-mat-form-field.$prefix,
tokens-mat-form-field.private-get-color-palette-color-tokens($theme, accent)
);
}
.mat-mdc-form-field.mat-warn {
@include token-utils.create-token-values(
tokens-mdc-filled-text-field.$prefix,
tokens-mdc-filled-text-field.private-get-color-palette-color-tokens($theme, warn)
);
@include token-utils.create-token-values(
tokens-mdc-outlined-text-field.$prefix,
tokens-mdc-outlined-text-field.private-get-color-palette-color-tokens($theme, warn)
);
@include token-utils.create-token-values(
tokens-mat-form-field.$prefix,
tokens-mat-form-field.private-get-color-palette-color-tokens($theme, warn)
);
}
}
}
/// Outputs typography theme styles for the mat-form-field.
/// @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-filled-text-field.$prefix,
tokens-mdc-filled-text-field.get-typography-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mdc-outlined-text-field.$prefix,
tokens-mdc-outlined-text-field.get-typography-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-form-field.$prefix,
tokens-mat-form-field.get-typography-tokens($theme)
);
}
}
}
/// Outputs density theme styles for the mat-form-field.
/// @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 {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-form-field.$prefix,
tokens-mat-form-field.get-density-tokens($theme)
);
}
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
$filled-text-field-tokens: tokens-mdc-filled-text-field.get-token-slots();
$outlined-text-field-tokens: tokens-mdc-outlined-text-field.get-token-slots();
$form-field-tokens: tokens-mat-form-field.get-token-slots();
@return (
(
namespace: tokens-mdc-filled-text-field.$prefix,
tokens: $filled-text-field-tokens,
prefix: 'filled-',
),
(
namespace: tokens-mdc-outlined-text-field.$prefix,
tokens: $outlined-text-field-tokens,
prefix: 'outlined-',
),
(
namespace: tokens-mat-form-field.$prefix,
tokens: $form-field-tokens,
)
);
}
/// 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-form-field.
/// @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 form field: 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-form-field') {
@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-filled-text-field-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mdc-filled-text-field.$prefix,
$options...
);
$mdc-outlined-text-field-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mdc-outlined-text-field.$prefix,
$options...
);
$mat-form-field-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mat-form-field.$prefix,
$options...
);
@include token-utils.create-token-values(
tokens-mdc-filled-text-field.$prefix,
$mdc-filled-text-field-tokens
);
@include token-utils.create-token-values(
tokens-mdc-outlined-text-field.$prefix,
$mdc-outlined-text-field-tokens
);
@include token-utils.create-token-values(tokens-mat-form-field.$prefix, $mat-form-field-tokens);
}
| {
"end_byte": 7957,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/_form-field-theme.scss"
} |
components/src/material/form-field/README.md_0_101 | Please see the official documentation at https://material.angular.io/components/component/form-field
| {
"end_byte": 101,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/README.md"
} |
components/src/material/form-field/form-field-animations.ts_0_935 | /**
* @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 MatFormField.
* @docs-private
*/
export const matFormFieldAnimations: {
readonly transitionMessages: AnimationTriggerMetadata;
} = {
/** Animation that transitions the form field's error and hint messages. */
transitionMessages: trigger('transitionMessages', [
// TODO(mmalerba): Use angular animations for label animation as well.
state('enter', style({opacity: 1, transform: 'translateY(0%)'})),
transition('void => enter', [
style({opacity: 0, transform: 'translateY(-5px)'}),
animate('300ms cubic-bezier(0.55, 0, 0.55, 0.2)'),
]),
]),
};
| {
"end_byte": 935,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field-animations.ts"
} |
components/src/material/form-field/_form-field-high-contrast.scss_0_1303 | @use '@angular/cdk';
@mixin private-form-field-high-contrast() {
$focus-indicator-width: 3px;
$focus-indicator-style: dashed;
.mat-form-field-appearance-fill {
// The outline of the `fill` appearance is achieved through a background color
// which won't be visible in high contrast mode. Add an outline to replace it.
.mat-mdc-text-field-wrapper {
@include cdk.high-contrast {
outline: solid 1px;
}
}
// Use GreyText for the disabled outline color which will account for the user's configuration.
&.mat-form-field-disabled .mat-mdc-text-field-wrapper {
@include cdk.high-contrast {
outline-color: GrayText;
}
}
}
// If a form field with fill appearance is focused, update the outline to be
// dashed and thicker to indicate focus.
.mat-form-field-appearance-fill.mat-focused .mat-mdc-text-field-wrapper {
@include cdk.high-contrast {
outline: $focus-indicator-style $focus-indicator-width;
}
}
// For form fields with outline appearance, we show a dashed thick border on top
// of the solid notched-outline border to indicate focus.
.mat-mdc-form-field.mat-focused .mdc-notched-outline {
@include cdk.high-contrast {
border: $focus-indicator-style $focus-indicator-width;
}
}
}
| {
"end_byte": 1303,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/_form-field-high-contrast.scss"
} |
components/src/material/form-field/_mdc-text-field-density-overrides.scss_0_3223 | @use '../core/tokens/m2/mat/form-field' as tokens-mat-form-field;
@use '../core/tokens/token-utils';
// Mixin that includes the density styles for form fields. MDC provides their own density
// styles for MDC text-field which we cannot use. MDC relies on input elements to stretch
// vertically when the height is reduced as per density scale. This doesn't work for our
// form field since we support custom form field controls without a fixed height. Instead, we
// provide spacing that makes arbitrary controls align as specified in the Material Design
// specification. In order to support density, we need to adjust the vertical spacing to be
// based on the density scale.
@mixin private-text-field-density-overrides() {
@include token-utils.use-tokens(
tokens-mat-form-field.$prefix, tokens-mat-form-field.get-token-slots()) {
$height: token-utils.get-token-variable(container-height);
.mat-mdc-form-field-infix {
// We add a minimum height to the infix container to ensure that custom controls have the
// same default vertical space as text-field inputs (with respect to the vertical padding).
min-height: #{$height};
@include token-utils.create-token-slot(padding-top,
filled-with-label-container-padding-top);
@include token-utils.create-token-slot(padding-bottom,
filled-with-label-container-padding-bottom);
.mdc-text-field--outlined &,
.mdc-text-field--no-label & {
@include token-utils.create-token-slot(padding-top, container-vertical-padding);
@include token-utils.create-token-slot(padding-bottom, container-vertical-padding);
}
}
// By default, MDC aligns the label using percentage. This will be overwritten based
// on whether a textarea is used. This is not possible in our implementation of the
// form-field because we do not know what type of form-field control is set up. Hence
// we always use a fixed position for the label. This does not have any implications.
.mat-mdc-text-field-wrapper .mat-mdc-form-field-flex .mat-mdc-floating-label {
top: calc(#{$height} / 2);
}
// We need to conditionally hide the floating label based on the height of the form field.
.mdc-text-field--filled .mat-mdc-floating-label {
display: token-utils.get-token-variable(filled-label-display, $fallback: block);
}
// For the outline appearance, we re-create the active floating label transform. This is
// necessary because the transform for docked floating labels can be updated to account for
// the width of prefix container.
.mat-mdc-text-field-wrapper.mdc-text-field--outlined .mdc-notched-outline--upgraded
.mdc-floating-label--float-above {
// Needs to be in a string form to work around an internal check that incorrectly flags this
// interpolation in `calc` as unnecessary. If we don't have it, Sass won't evaluate it.
$offset: 'calc(6.75px + #{$height} / 2)';
$translate: 'calc(#{$offset} * -1)';
--mat-mdc-form-field-label-transform: translateY(#{$translate})
scale(var(--mat-mdc-form-field-floating-label-scale, 0.75));
transform: var(--mat-mdc-form-field-label-transform);
}
}
}
| {
"end_byte": 3223,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/_mdc-text-field-density-overrides.scss"
} |
components/src/material/form-field/_form-field-native-select.scss_0_3661 | @use 'sass:math';
@use '../core/tokens/m2/mat/form-field' as tokens-mat-form-field;
@use '../core/tokens/token-utils';
// Width of the Material Design form-field select arrow.
$mat-form-field-select-arrow-width: 10px;
// Height of the Material Design form-field select arrow.
$mat-form-field-select-arrow-height: 5px;
// Horizontal padding that needs to be applied to the native select in a form-field so
// that the absolute positioned arrow does not overlap the select content.
$mat-form-field-select-horizontal-end-padding: $mat-form-field-select-arrow-width + 5px;
$_tokens: tokens-mat-form-field.$prefix, tokens-mat-form-field.get-token-slots();
// Mixin that creates styles for native select controls in a form-field.
@mixin private-form-field-native-select() {
// Remove the native select down arrow and ensure that the native appearance
// does not conflict with the form-field. e.g. Focus indication of the native
// select is undesired since we handle focus as part of the form-field.
select.mat-mdc-form-field-input-control {
-moz-appearance: none;
-webkit-appearance: none;
background-color: transparent;
display: inline-flex;
box-sizing: border-box;
// By default the cursor does not change when hovering over a select. We want to
// change this for non-disabled select elements so that it's more obvious that the
// control can be clicked.
&:not(:disabled) {
cursor: pointer;
}
&:not(.mat-mdc-native-select-inline) {
@include token-utils.use-tokens($_tokens...) {
option {
@include token-utils.create-token-slot(color, select-option-text-color);
}
option:disabled {
@include token-utils.create-token-slot(color, select-disabled-option-text-color);
}
}
}
}
// Native select elements with the `matInput` directive should have Material Design
// styling. This means that we add an arrow to the form-field that is based on the
// Material Design specification. We achieve this by adding a pseudo element to the
// form-field infix.
.mat-mdc-form-field-type-mat-native-select {
.mat-mdc-form-field-infix::after {
content: '';
width: 0;
height: 0;
border-left: math.div($mat-form-field-select-arrow-width, 2) solid transparent;
border-right: math.div($mat-form-field-select-arrow-width, 2) solid transparent;
border-top: $mat-form-field-select-arrow-height solid;
position: absolute;
right: 0;
top: 50%;
margin-top: -#{math.div($mat-form-field-select-arrow-height, 2)};
// Make the arrow non-clickable so the user can click on the form control under it.
pointer-events: none;
@include token-utils.use-tokens($_tokens...) {
@include token-utils.create-token-slot(color, enabled-select-arrow-color);
}
[dir='rtl'] & {
right: auto;
left: 0;
}
}
@include token-utils.use-tokens($_tokens...) {
&.mat-focused .mat-mdc-form-field-infix::after {
@include token-utils.create-token-slot(color, focus-select-arrow-color);
}
&.mat-form-field-disabled .mat-mdc-form-field-infix::after {
@include token-utils.create-token-slot(color, disabled-select-arrow-color);
}
}
// Add padding on the end of the native select so that the content does not
// overlap with the Material Design arrow.
.mat-mdc-form-field-input-control {
padding-right: $mat-form-field-select-horizontal-end-padding;
[dir='rtl'] & {
padding-right: 0;
padding-left: $mat-form-field-select-horizontal-end-padding;
}
}
}
}
| {
"end_byte": 3661,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/_form-field-native-select.scss"
} |
components/src/material/form-field/BUILD.bazel_0_1797 | load(
"//tools:defaults.bzl",
"extract_tokens",
"markdown_to_html",
"ng_module",
"sass_binary",
"sass_library",
)
package(default_visibility = ["//visibility:public"])
ng_module(
name = "form-field",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [":form_field_scss"] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/cdk/bidi",
"//src/cdk/observers/private",
"//src/cdk/platform",
"//src/material/core",
"@npm//@angular/forms",
"@npm//rxjs",
],
)
sass_library(
name = "form_field_scss_lib",
srcs = [
"_form-field-theme.scss",
],
deps = [
":form_field_partials",
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "form_field_scss",
src = "form-field.scss",
deps = [
":form_field_partials",
"//src/material:sass_lib",
"//src/material/core:core_scss_lib",
],
)
sass_library(
name = "form_field_partials",
srcs = [
"_form-field-focus-overlay.scss",
"_form-field-high-contrast.scss",
"_form-field-native-select.scss",
"_form-field-subscript.scss",
"_mdc-text-field-density-overrides.scss",
"_mdc-text-field-structure.scss",
"_mdc-text-field-structure-overrides.scss",
"_mdc-text-field-textarea-overrides.scss",
"_user-agent-overrides.scss",
],
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
markdown_to_html(
name = "overview",
srcs = [":form-field.md"],
)
extract_tokens(
name = "tokens",
srcs = [":form_field_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1797,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/BUILD.bazel"
} |
components/src/material/form-field/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';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/index.ts"
} |
components/src/material/form-field/_form-field-subscript.scss_0_2349 | @use '../core/tokens/m2/mat/form-field' as tokens-mat-form-field;
@use '../core/style/vendor-prefixes';
@use '../core/tokens/token-utils';
@mixin private-form-field-subscript() {
// Wrapper for the hints and error messages.
.mat-mdc-form-field-subscript-wrapper {
box-sizing: border-box;
width: 100%;
position: relative;
}
.mat-mdc-form-field-hint-wrapper,
.mat-mdc-form-field-error-wrapper {
position: absolute;
top: 0;
left: 0;
right: 0;
padding: 0 16px;
}
.mat-mdc-form-field-subscript-dynamic-size {
.mat-mdc-form-field-hint-wrapper,
.mat-mdc-form-field-error-wrapper {
position: static;
}
}
.mat-mdc-form-field-bottom-align::before {
content: '';
display: inline-block;
height: 16px;
}
.mat-mdc-form-field-bottom-align.mat-mdc-form-field-subscript-dynamic-size::before {
content: unset;
}
.mat-mdc-form-field-hint-end {
order: 1;
}
// Clears the floats on the hints. This is necessary for the hint animation to work.
.mat-mdc-form-field-hint-wrapper {
display: flex;
}
// Spacer used to make sure start and end hints have enough space between them.
.mat-mdc-form-field-hint-spacer {
flex: 1 0 1em;
}
// Single error message displayed beneath the form field underline.
.mat-mdc-form-field-error {
display: block;
@include token-utils.use-tokens(tokens-mat-form-field.$prefix,
tokens-mat-form-field.get-token-slots()) {
@include token-utils.create-token-slot(color, error-text-color);
}
}
// The subscript wrapper has a minimum height to avoid that the form-field
// jumps when hints or errors are displayed.
.mat-mdc-form-field-subscript-wrapper,
.mat-mdc-form-field-bottom-align::before {
@include token-utils.use-tokens(tokens-mat-form-field.$prefix,
tokens-mat-form-field.get-token-slots()) {
@include vendor-prefixes.smooth-font();
@include token-utils.create-token-slot(font-family, subscript-text-font);
@include token-utils.create-token-slot(line-height, subscript-text-line-height);
@include token-utils.create-token-slot(font-size, subscript-text-size);
@include token-utils.create-token-slot(letter-spacing, subscript-text-tracking);
@include token-utils.create-token-slot(font-weight, subscript-text-weight);
}
}
}
| {
"end_byte": 2349,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/_form-field-subscript.scss"
} |
components/src/material/form-field/form-field-control.ts_0_2634 | /**
* @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 {Observable} from 'rxjs';
import {AbstractControlDirective, NgControl} from '@angular/forms';
import {Directive} from '@angular/core';
/** An interface which allows a control to work inside of a `MatFormField`. */
@Directive()
export abstract class MatFormFieldControl<T> {
/** The value of the control. */
value: T | null;
/**
* Stream that emits whenever the state of the control changes such that the parent `MatFormField`
* needs to run change detection.
*/
readonly stateChanges: Observable<void>;
/** The element ID for this control. */
readonly id: string;
/** The placeholder for this control. */
readonly placeholder: string;
/** Gets the AbstractControlDirective for this control. */
readonly ngControl: NgControl | AbstractControlDirective | null;
/** Whether the control is focused. */
readonly focused: boolean;
/** Whether the control is empty. */
readonly empty: boolean;
/** Whether the `MatFormField` label should try to float. */
readonly shouldLabelFloat: boolean;
/** Whether the control is required. */
readonly required: boolean;
/** Whether the control is disabled. */
readonly disabled: boolean;
/** Whether the control is in an error state. */
readonly errorState: boolean;
/**
* An optional name for the control type that can be used to distinguish `mat-form-field` elements
* based on their control type. The form field will add a class,
* `mat-form-field-type-{{controlType}}` to its root element.
*/
readonly controlType?: string;
/**
* Whether the input is currently in an autofilled state. If property is not present on the
* control it is assumed to be false.
*/
readonly autofilled?: boolean;
/**
* Value of `aria-describedby` that should be merged with the described-by ids
* which are set by the form-field.
*/
readonly userAriaDescribedBy?: string;
/**
* Whether to automatically assign the ID of the form field as the `for` attribute
* on the `<label>` inside the form field. Set this to true to prevent the form
* field from associating the label with non-native elements.
*/
readonly disableAutomaticLabeling?: boolean;
/** Sets the list of element IDs that currently describe this control. */
abstract setDescribedByIds(ids: string[]): void;
/** Handles a click on the control's container. */
abstract onContainerClick(event: MouseEvent): void;
}
| {
"end_byte": 2634,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/form-field-control.ts"
} |
components/src/material/form-field/directives/notched-outline.html_0_242 | <div class="mat-mdc-notch-piece mdc-notched-outline__leading"></div>
<div class="mat-mdc-notch-piece mdc-notched-outline__notch" #notch>
<ng-content></ng-content>
</div>
<div class="mat-mdc-notch-piece mdc-notched-outline__trailing"></div>
| {
"end_byte": 242,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/directives/notched-outline.html"
} |
components/src/material/form-field/directives/suffix.ts_0_906 | /**
* @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 {Directive, InjectionToken, Input} from '@angular/core';
/**
* Injection token that can be used to reference instances of `MatSuffix`. It serves as
* alternative token to the actual `MatSuffix` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_SUFFIX = new InjectionToken<MatSuffix>('MatSuffix');
/** Suffix to be placed at the end of the form field. */
@Directive({
selector: '[matSuffix], [matIconSuffix], [matTextSuffix]',
providers: [{provide: MAT_SUFFIX, useExisting: MatSuffix}],
})
export class MatSuffix {
@Input('matTextSuffix')
set _isTextSelector(value: '') {
this._isText = true;
}
_isText = false;
}
| {
"end_byte": 906,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/directives/suffix.ts"
} |
components/src/material/form-field/directives/hint.ts_0_942 | /**
* @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 {Directive, Input} from '@angular/core';
let nextUniqueId = 0;
/** Hint text to be shown underneath the form field control. */
@Directive({
selector: 'mat-hint',
host: {
'class': 'mat-mdc-form-field-hint mat-mdc-form-field-bottom-align',
'[class.mat-mdc-form-field-hint-end]': 'align === "end"',
'[id]': 'id',
// Remove align attribute to prevent it from interfering with layout.
'[attr.align]': 'null',
},
})
export class MatHint {
/** Whether to align the hint label at the start or end of the line. */
@Input() align: 'start' | 'end' = 'start';
/** Unique ID for the hint. Used for the aria-describedby on the form field control. */
@Input() id: string = `mat-mdc-hint-${nextUniqueId++}`;
}
| {
"end_byte": 942,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/directives/hint.ts"
} |
components/src/material/form-field/directives/notched-outline.ts_0_2495 | /**
* @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 {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ElementRef,
Input,
NgZone,
ViewChild,
ViewEncapsulation,
inject,
} from '@angular/core';
/**
* Internal component that creates an instance of the MDC notched-outline component.
*
* The component sets up the HTML structure and styles for the notched-outline. It provides
* inputs to toggle the notch state and width.
*/
@Component({
selector: 'div[matFormFieldNotchedOutline]',
templateUrl: './notched-outline.html',
host: {
'class': 'mdc-notched-outline',
// Besides updating the notch state through the MDC component, we toggle this class through
// a host binding in order to ensure that the notched-outline renders correctly on the server.
'[class.mdc-notched-outline--notched]': 'open',
},
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class MatFormFieldNotchedOutline implements AfterViewInit {
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _ngZone = inject(NgZone);
/** Whether the notch should be opened. */
@Input('matFormFieldNotchedOutlineOpen') open: boolean = false;
@ViewChild('notch') _notch: ElementRef;
constructor(...args: unknown[]);
constructor() {}
ngAfterViewInit(): void {
const label = this._elementRef.nativeElement.querySelector<HTMLElement>('.mdc-floating-label');
if (label) {
this._elementRef.nativeElement.classList.add('mdc-notched-outline--upgraded');
if (typeof requestAnimationFrame === 'function') {
label.style.transitionDuration = '0s';
this._ngZone.runOutsideAngular(() => {
requestAnimationFrame(() => (label.style.transitionDuration = ''));
});
}
} else {
this._elementRef.nativeElement.classList.add('mdc-notched-outline--no-label');
}
}
_setNotchWidth(labelWidth: number) {
if (!this.open || !labelWidth) {
this._notch.nativeElement.style.width = '';
} else {
const NOTCH_ELEMENT_PADDING = 8;
const NOTCH_ELEMENT_BORDER = 1;
this._notch.nativeElement.style.width = `calc(${labelWidth}px * var(--mat-mdc-form-field-floating-label-scale, 0.75) + ${
NOTCH_ELEMENT_PADDING + NOTCH_ELEMENT_BORDER
}px)`;
}
}
}
| {
"end_byte": 2495,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/directives/notched-outline.ts"
} |
components/src/material/form-field/directives/label.ts_0_362 | /**
* @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 {Directive} from '@angular/core';
/** The floating label for a `mat-form-field`. */
@Directive({
selector: 'mat-label',
})
export class MatLabel {}
| {
"end_byte": 362,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/directives/label.ts"
} |
components/src/material/form-field/directives/floating-label.ts_0_5123 | /**
* @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 {
Directive,
ElementRef,
inject,
Input,
NgZone,
OnDestroy,
InjectionToken,
} from '@angular/core';
import {SharedResizeObserver} from '@angular/cdk/observers/private';
import {Subscription} from 'rxjs';
/** An interface that the parent form-field should implement to receive resize events. */
export interface FloatingLabelParent {
_handleLabelResized(): void;
}
/** An injion token for the parent form-field. */
export const FLOATING_LABEL_PARENT = new InjectionToken<FloatingLabelParent>('FloatingLabelParent');
/**
* Internal directive that maintains a MDC floating label. This directive does not
* use the `MDCFloatingLabelFoundation` class, as it is not worth the size cost of
* including it just to measure the label width and toggle some classes.
*
* The use of a directive allows us to conditionally render a floating label in the
* template without having to manually manage instantiation and destruction of the
* floating label component based on.
*
* The component is responsible for setting up the floating label styles, measuring label
* width for the outline notch, and providing inputs that can be used to toggle the
* label's floating or required state.
*/
@Directive({
selector: 'label[matFormFieldFloatingLabel]',
host: {
'class': 'mdc-floating-label mat-mdc-floating-label',
'[class.mdc-floating-label--float-above]': 'floating',
},
})
export class MatFormFieldFloatingLabel implements OnDestroy {
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
/** Whether the label is floating. */
@Input()
get floating() {
return this._floating;
}
set floating(value: boolean) {
this._floating = value;
if (this.monitorResize) {
this._handleResize();
}
}
private _floating = false;
/** Whether to monitor for resize events on the floating label. */
@Input()
get monitorResize() {
return this._monitorResize;
}
set monitorResize(value: boolean) {
this._monitorResize = value;
if (this._monitorResize) {
this._subscribeToResize();
} else {
this._resizeSubscription.unsubscribe();
}
}
private _monitorResize = false;
/** The shared ResizeObserver. */
private _resizeObserver = inject(SharedResizeObserver);
/** The Angular zone. */
private _ngZone = inject(NgZone);
/** The parent form-field. */
private _parent = inject(FLOATING_LABEL_PARENT);
/** The current resize event subscription. */
private _resizeSubscription = new Subscription();
constructor(...args: unknown[]);
constructor() {}
ngOnDestroy() {
this._resizeSubscription.unsubscribe();
}
/** Gets the width of the label. Used for the outline notch. */
getWidth(): number {
return estimateScrollWidth(this._elementRef.nativeElement);
}
/** Gets the HTML element for the floating label. */
get element(): HTMLElement {
return this._elementRef.nativeElement;
}
/** Handles resize events from the ResizeObserver. */
private _handleResize() {
// In the case where the label grows in size, the following sequence of events occurs:
// 1. The label grows by 1px triggering the ResizeObserver
// 2. The notch is expanded to accommodate the entire label
// 3. The label expands to its full width, triggering the ResizeObserver again
//
// This is expected, but If we allow this to all happen within the same macro task it causes an
// error: `ResizeObserver loop limit exceeded`. Therefore we push the notch resize out until
// the next macro task.
setTimeout(() => this._parent._handleLabelResized());
}
/** Subscribes to resize events. */
private _subscribeToResize() {
this._resizeSubscription.unsubscribe();
this._ngZone.runOutsideAngular(() => {
this._resizeSubscription = this._resizeObserver
.observe(this._elementRef.nativeElement, {box: 'border-box'})
.subscribe(() => this._handleResize());
});
}
}
/**
* Estimates the scroll width of an element.
* via https://github.com/material-components/material-components-web/blob/c0a11ef0d000a098fd0c372be8f12d6a99302855/packages/mdc-dom/ponyfill.ts
*/
function estimateScrollWidth(element: HTMLElement): number {
// Check the offsetParent. If the element inherits display: none from any
// parent, the offsetParent property will be null (see
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetParent).
// This check ensures we only clone the node when necessary.
const htmlEl = element as HTMLElement;
if (htmlEl.offsetParent !== null) {
return htmlEl.scrollWidth;
}
const clone = htmlEl.cloneNode(true) as HTMLElement;
clone.style.setProperty('position', 'absolute');
clone.style.setProperty('transform', 'translate(-9999px, -9999px)');
document.documentElement.appendChild(clone);
const scrollWidth = clone.scrollWidth;
clone.remove();
return scrollWidth;
}
| {
"end_byte": 5123,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/directives/floating-label.ts"
} |
components/src/material/form-field/directives/error.ts_0_1519 | /**
* @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 {
Directive,
ElementRef,
InjectionToken,
Input,
HostAttributeToken,
inject,
} from '@angular/core';
let nextUniqueId = 0;
/**
* Injection token that can be used to reference instances of `MatError`. It serves as
* alternative token to the actual `MatError` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_ERROR = new InjectionToken<MatError>('MatError');
/** Single error message to be shown underneath the form-field. */
@Directive({
selector: 'mat-error, [matError]',
host: {
'class': 'mat-mdc-form-field-error mat-mdc-form-field-bottom-align',
'aria-atomic': 'true',
'[id]': 'id',
},
providers: [{provide: MAT_ERROR, useExisting: MatError}],
})
export class MatError {
@Input() id: string = `mat-mdc-error-${nextUniqueId++}`;
constructor(...args: unknown[]);
constructor() {
const ariaLive = inject(new HostAttributeToken('aria-live'), {optional: true});
// If no aria-live value is set add 'polite' as a default. This is preferred over setting
// role='alert' so that screen readers do not interrupt the current task to read this aloud.
if (!ariaLive) {
const elementRef = inject(ElementRef);
elementRef.nativeElement.setAttribute('aria-live', 'polite');
}
}
}
| {
"end_byte": 1519,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/directives/error.ts"
} |
components/src/material/form-field/directives/line-ripple.ts_0_2106 | /**
* @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 {Directive, ElementRef, NgZone, OnDestroy, inject} from '@angular/core';
/** Class added when the line ripple is active. */
const ACTIVATE_CLASS = 'mdc-line-ripple--active';
/** Class added when the line ripple is being deactivated. */
const DEACTIVATING_CLASS = 'mdc-line-ripple--deactivating';
/**
* Internal directive that creates an instance of the MDC line-ripple component. Using a
* directive allows us to conditionally render a line-ripple in the template without having
* to manually create and destroy the `MDCLineRipple` component whenever the condition changes.
*
* The directive sets up the styles for the line-ripple and provides an API for activating
* and deactivating the line-ripple.
*/
@Directive({
selector: 'div[matFormFieldLineRipple]',
host: {
'class': 'mdc-line-ripple',
},
})
export class MatFormFieldLineRipple implements OnDestroy {
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
constructor(...args: unknown[]);
constructor() {
const ngZone = inject(NgZone);
ngZone.runOutsideAngular(() => {
this._elementRef.nativeElement.addEventListener('transitionend', this._handleTransitionEnd);
});
}
activate() {
const classList = this._elementRef.nativeElement.classList;
classList.remove(DEACTIVATING_CLASS);
classList.add(ACTIVATE_CLASS);
}
deactivate() {
this._elementRef.nativeElement.classList.add(DEACTIVATING_CLASS);
}
private _handleTransitionEnd = (event: TransitionEvent) => {
const classList = this._elementRef.nativeElement.classList;
const isDeactivating = classList.contains(DEACTIVATING_CLASS);
if (event.propertyName === 'opacity' && isDeactivating) {
classList.remove(ACTIVATE_CLASS, DEACTIVATING_CLASS);
}
};
ngOnDestroy() {
this._elementRef.nativeElement.removeEventListener('transitionend', this._handleTransitionEnd);
}
}
| {
"end_byte": 2106,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/directives/line-ripple.ts"
} |
components/src/material/form-field/directives/prefix.ts_0_904 | /**
* @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 {Directive, InjectionToken, Input} from '@angular/core';
/**
* Injection token that can be used to reference instances of `MatPrefix`. It serves as
* alternative token to the actual `MatPrefix` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_PREFIX = new InjectionToken<MatPrefix>('MatPrefix');
/** Prefix to be placed in front of the form field. */
@Directive({
selector: '[matPrefix], [matIconPrefix], [matTextPrefix]',
providers: [{provide: MAT_PREFIX, useExisting: MatPrefix}],
})
export class MatPrefix {
@Input('matTextPrefix')
set _isTextSelector(value: '') {
this._isText = true;
}
_isText = false;
}
| {
"end_byte": 904,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/directives/prefix.ts"
} |
components/src/material/form-field/testing/error-harness.ts_0_1719 | /**
* @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,
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
} from '@angular/cdk/testing';
/** A set of criteria that can be used to filter a list of error harness instances. */
export interface ErrorHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose text matches the given value. */
text?: string | RegExp;
}
/** Harness for interacting with a `mat-error` in tests. */
export class MatErrorHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-form-field-error';
/**
* Gets a `HarnessPredicate` that can be used to search for an error with specific
* attributes.
* @param options Options for filtering which error instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatErrorHarness>(
this: ComponentHarnessConstructor<T>,
options: ErrorHarnessFilters = {},
): HarnessPredicate<T> {
return MatErrorHarness._getErrorPredicate(this, options);
}
protected static _getErrorPredicate<T extends MatErrorHarness>(
type: ComponentHarnessConstructor<T>,
options: ErrorHarnessFilters,
): HarnessPredicate<T> {
return new HarnessPredicate(type, options).addOption('text', options.text, (harness, text) =>
HarnessPredicate.stringMatches(harness.getText(), text),
);
}
/** Gets a promise for the error's label text. */
async getText(): Promise<string> {
return (await this.host()).text();
}
}
| {
"end_byte": 1719,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/error-harness.ts"
} |
components/src/material/form-field/testing/public-api.ts_0_676 | /**
* @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
*/
// Re-export the base control harness from the "form-field/testing/control" entry-point. To
// avoid circular dependencies, harnesses for form-field controls (i.e. input, select)
// need to import the base form-field control harness through a separate entry-point.
export {MatFormFieldControlHarness} from '@angular/material/form-field/testing/control';
export * from './form-field-harness-filters';
export * from './form-field-harness';
export * from './error-harness';
| {
"end_byte": 676,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/public-api.ts"
} |
components/src/material/form-field/testing/form-field-harness.ts_0_8724 | /**
* @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,
HarnessQuery,
parallel,
} from '@angular/cdk/testing';
import {ErrorHarnessFilters, MatErrorHarness} from './error-harness';
import {MatInputHarness} from '@angular/material/input/testing';
import {MatFormFieldControlHarness} from '@angular/material/form-field/testing/control';
import {MatSelectHarness} from '@angular/material/select/testing';
import {
MatDatepickerInputHarness,
MatDateRangeInputHarness,
} from '@angular/material/datepicker/testing';
import {FormFieldHarnessFilters} from './form-field-harness-filters';
/** Possible harnesses of controls which can be bound to a form-field. */
export type FormFieldControlHarness =
| MatInputHarness
| MatSelectHarness
| MatDatepickerInputHarness
| MatDateRangeInputHarness;
export class MatFormFieldHarness extends ComponentHarness {
private _prefixContainer = this.locatorForOptional('.mat-mdc-form-field-text-prefix');
private _suffixContainer = this.locatorForOptional('.mat-mdc-form-field-text-suffix');
private _label = this.locatorForOptional('.mdc-floating-label');
private _hints = this.locatorForAll('.mat-mdc-form-field-hint');
private _inputControl = this.locatorForOptional(MatInputHarness);
private _selectControl = this.locatorForOptional(MatSelectHarness);
private _datepickerInputControl = this.locatorForOptional(MatDatepickerInputHarness);
private _dateRangeInputControl = this.locatorForOptional(MatDateRangeInputHarness);
private _textField = this.locatorFor('.mat-mdc-text-field-wrapper');
private _errorHarness = MatErrorHarness;
static hostSelector = '.mat-mdc-form-field';
/**
* Gets a `HarnessPredicate` that can be used to search for a form field with specific
* attributes.
* @param options Options for filtering which form field instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatFormFieldHarness>(
this: ComponentHarnessConstructor<T>,
options: FormFieldHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options)
.addOption('floatingLabelText', options.floatingLabelText, async (harness, text) =>
HarnessPredicate.stringMatches(await harness.getLabel(), text),
)
.addOption(
'hasErrors',
options.hasErrors,
async (harness, hasErrors) => (await harness.hasErrors()) === hasErrors,
)
.addOption(
'isValid',
options.isValid,
async (harness, isValid) => (await harness.isControlValid()) === isValid,
);
}
/** Gets the appearance of the form-field. */
async getAppearance(): Promise<'fill' | 'outline'> {
const textFieldEl = await this._textField();
if (await textFieldEl.hasClass('mdc-text-field--outlined')) {
return 'outline';
}
return 'fill';
}
/** Whether the form-field has a label. */
async hasLabel(): Promise<boolean> {
return (await this._label()) !== null;
}
/** Whether the label is currently floating. */
async isLabelFloating(): Promise<boolean> {
const labelEl = await this._label();
return labelEl !== null ? await labelEl.hasClass('mdc-floating-label--float-above') : false;
}
/** Gets the label of the form-field. */
async getLabel(): Promise<string | null> {
const labelEl = await this._label();
return labelEl ? labelEl.text() : null;
}
/** Whether the form-field has errors. */
async hasErrors(): Promise<boolean> {
return (await this.getTextErrors()).length > 0;
}
/** Whether the form-field is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).hasClass('mat-form-field-disabled');
}
/** Whether the form-field is currently autofilled. */
async isAutofilled(): Promise<boolean> {
return (await this.host()).hasClass('mat-form-field-autofilled');
}
/**
* Gets the harness of the control that is bound to the form-field. Only
* default controls such as "MatInputHarness" and "MatSelectHarness" are
* supported.
*/
async getControl(): Promise<FormFieldControlHarness | null>;
/**
* Gets the harness of the control that is bound to the form-field. Searches
* for a control that matches the specified harness type.
*/
async getControl<X extends MatFormFieldControlHarness>(
type: ComponentHarnessConstructor<X>,
): Promise<X | null>;
/**
* Gets the harness of the control that is bound to the form-field. Searches
* for a control that matches the specified harness predicate.
*/
async getControl<X extends MatFormFieldControlHarness>(
type: HarnessPredicate<X>,
): Promise<X | null>;
// Implementation of the "getControl" method overload signatures.
async getControl<X extends MatFormFieldControlHarness>(type?: HarnessQuery<X>) {
if (type) {
return this.locatorForOptional(type)();
}
const [select, input, datepickerInput, dateRangeInput] = await parallel(() => [
this._selectControl(),
this._inputControl(),
this._datepickerInputControl(),
this._dateRangeInputControl(),
]);
// Match the datepicker inputs first since they can also have a `MatInput`.
return datepickerInput || dateRangeInput || select || input;
}
/** Gets the theme color of the form-field. */
async getThemeColor(): Promise<'primary' | 'accent' | 'warn'> {
const hostEl = await this.host();
const [isAccent, isWarn] = await parallel(() => {
return [hostEl.hasClass('mat-accent'), hostEl.hasClass('mat-warn')];
});
if (isAccent) {
return 'accent';
} else if (isWarn) {
return 'warn';
}
return 'primary';
}
/** Gets error messages which are currently displayed in the form-field. */
async getTextErrors(): Promise<string[]> {
const errors = await this.getErrors();
return parallel(() => errors.map(e => e.getText()));
}
/** Gets all of the error harnesses in the form field. */
async getErrors(filter: ErrorHarnessFilters = {}): Promise<MatErrorHarness[]> {
return this.locatorForAll(this._errorHarness.with(filter))();
}
/** Gets hint messages which are currently displayed in the form-field. */
async getTextHints(): Promise<string[]> {
const hints = await this._hints();
return parallel(() => hints.map(e => e.text()));
}
/** Gets the text inside the prefix element. */
async getPrefixText(): Promise<string> {
const prefix = await this._prefixContainer();
return prefix ? prefix.text() : '';
}
/** Gets the text inside the suffix element. */
async getSuffixText(): Promise<string> {
const suffix = await this._suffixContainer();
return suffix ? suffix.text() : '';
}
/**
* Whether the form control has been touched. Returns "null"
* if no form control is set up.
*/
async isControlTouched(): Promise<boolean | null> {
if (!(await this._hasFormControl())) {
return null;
}
return (await this.host()).hasClass('ng-touched');
}
/**
* Whether the form control is dirty. Returns "null"
* if no form control is set up.
*/
async isControlDirty(): Promise<boolean | null> {
if (!(await this._hasFormControl())) {
return null;
}
return (await this.host()).hasClass('ng-dirty');
}
/**
* Whether the form control is valid. Returns "null"
* if no form control is set up.
*/
async isControlValid(): Promise<boolean | null> {
if (!(await this._hasFormControl())) {
return null;
}
return (await this.host()).hasClass('ng-valid');
}
/**
* Whether the form control is pending validation. Returns "null"
* if no form control is set up.
*/
async isControlPending(): Promise<boolean | null> {
if (!(await this._hasFormControl())) {
return null;
}
return (await this.host()).hasClass('ng-pending');
}
/** Checks whether the form-field control has set up a form control. */
private async _hasFormControl(): Promise<boolean> {
const hostEl = await this.host();
// If no form "NgControl" is bound to the form-field control, the form-field
// is not able to forward any control status classes. Therefore if either the
// "ng-touched" or "ng-untouched" class is set, we know that it has a form control
const [isTouched, isUntouched] = await parallel(() => [
hostEl.hasClass('ng-touched'),
hostEl.hasClass('ng-untouched'),
]);
return isTouched || isUntouched;
}
}
| {
"end_byte": 8724,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/form-field-harness.ts"
} |
components/src/material/form-field/testing/form-field-harness-filters.ts_0_717 | /**
* @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 `MatFormFieldHarness` instances. */
export interface FormFieldHarnessFilters extends BaseHarnessFilters {
/** Filters based on the text of the form field's floating label. */
floatingLabelText?: string | RegExp;
/** Filters based on whether the form field has error messages. */
hasErrors?: boolean;
/** Filters based on whether the form field value is valid. */
isValid?: boolean;
}
| {
"end_byte": 717,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/form-field-harness-filters.ts"
} |
components/src/material/form-field/testing/form-field-harness.spec.ts_0_1437 | import {Component, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {ComponentHarness, HarnessLoader, HarnessPredicate, parallel} from '@angular/cdk/testing';
import {createFakeEvent, dispatchFakeEvent} from '@angular/cdk/testing/private';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {FormControl, ReactiveFormsModule, Validators} from '@angular/forms';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {
MatError,
MatFormField,
MatHint,
MatLabel,
MatPrefix,
MatSuffix,
} from '@angular/material/form-field';
import {MatAutocomplete, MatAutocompleteTrigger} from '@angular/material/autocomplete';
import {MatInput} from '@angular/material/input';
import {MatSelect} from '@angular/material/select';
import {MatNativeDateModule, MatOption} from '@angular/material/core';
import {
MatDateRangeInput,
MatDateRangePicker,
MatDatepicker,
MatDatepickerInput,
MatDatepickerModule,
MatEndDate,
MatStartDate,
} from '@angular/material/datepicker';
import {MatInputHarness} from '@angular/material/input/testing';
import {MatSelectHarness} from '@angular/material/select/testing';
import {
MatDateRangeInputHarness,
MatDatepickerInputHarness,
} from '@angular/material/datepicker/testing';
import {MatFormFieldHarness} from './form-field-harness';
import {MatErrorHarness} from './error-harness'; | {
"end_byte": 1437,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/form-field-harness.spec.ts"
} |
components/src/material/form-field/testing/form-field-harness.spec.ts_1439_9588 | describe('MatFormFieldHarness', () => {
let fixture: ComponentFixture<FormFieldHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
NoopAnimationsModule,
MatNativeDateModule,
FormFieldHarnessTest,
MatDatepickerModule,
],
});
fixture = TestBed.createComponent(FormFieldHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should be able to load harnesses', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(formFields.length).toBe(7);
});
it('should be able to load form-field that matches specific selector', async () => {
const formFieldMatches = await loader.getAllHarnesses(
MatFormFieldHarness.with({
selector: '#first-form-field',
}),
);
expect(formFieldMatches.length).toBe(1);
});
it('should be able to get appearance of form-field', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].getAppearance()).toBe('fill');
expect(await formFields[1].getAppearance()).toBe('fill');
expect(await formFields[2].getAppearance()).toBe('fill');
expect(await formFields[3].getAppearance()).toBe('outline');
expect(await formFields[4].getAppearance()).toBe('fill');
});
it('should be able to get control of form-field', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect((await formFields[0].getControl()) instanceof MatInputHarness).toBe(true);
expect((await formFields[1].getControl()) instanceof MatInputHarness).toBe(true);
expect((await formFields[2].getControl()) instanceof MatSelectHarness).toBe(true);
expect((await formFields[3].getControl()) instanceof MatInputHarness).toBe(true);
expect((await formFields[4].getControl()) instanceof MatInputHarness).toBe(true);
expect((await formFields[5].getControl()) instanceof MatDatepickerInputHarness).toBe(true);
expect((await formFields[6].getControl()) instanceof MatDateRangeInputHarness).toBe(true);
});
it('should be able to get custom control of form-field', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].getControl(CustomControlHarness)).toBe(null);
expect(
(await formFields[1].getControl(CustomControlHarness)) instanceof CustomControlHarness,
).toBe(true);
expect(await formFields[2].getControl(CustomControlHarness)).toBe(null);
expect(await formFields[3].getControl(CustomControlHarness)).toBe(null);
expect(await formFields[4].getControl(CustomControlHarness)).toBe(null);
});
it('should be able to get custom control of form-field using a predicate', async () => {
const predicate = new HarnessPredicate(CustomControlHarness, {});
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].getControl(predicate)).toBe(null);
expect((await formFields[1].getControl(predicate)) instanceof CustomControlHarness).toBe(true);
expect(await formFields[2].getControl(predicate)).toBe(null);
expect(await formFields[3].getControl(predicate)).toBe(null);
expect(await formFields[4].getControl(predicate)).toBe(null);
});
it('should be able to check whether form-field has label', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].hasLabel()).toBe(false);
expect(await formFields[1].hasLabel()).toBe(false);
expect(await formFields[2].hasLabel()).toBe(true);
expect(await formFields[3].hasLabel()).toBe(true);
expect(await formFields[4].hasLabel()).toBe(true);
});
it('should be able to check whether label is floating', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].isLabelFloating()).toBe(false);
expect(await formFields[1].isLabelFloating()).toBe(false);
expect(await formFields[2].isLabelFloating()).toBe(false);
expect(await formFields[3].isLabelFloating()).toBe(true);
expect(await formFields[4].isLabelFloating()).toBe(false);
fixture.componentInstance.shouldLabelFloat.set('always');
expect(await formFields[4].isLabelFloating()).toBe(true);
});
it('should be able to check whether form-field is disabled', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].isDisabled()).toBe(false);
expect(await formFields[1].isDisabled()).toBe(false);
expect(await formFields[2].isDisabled()).toBe(false);
expect(await formFields[3].isDisabled()).toBe(false);
expect(await formFields[4].isDisabled()).toBe(false);
fixture.componentInstance.isDisabled.set(true);
expect(await formFields[0].isDisabled()).toBe(true);
expect(await formFields[1].isDisabled()).toBe(false);
expect(await formFields[2].isDisabled()).toBe(true);
expect(await formFields[3].isDisabled()).toBe(false);
expect(await formFields[4].isDisabled()).toBe(false);
});
it('should be able to check whether form-field is auto-filled', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].isAutofilled()).toBe(false);
expect(await formFields[1].isAutofilled()).toBe(false);
expect(await formFields[2].isAutofilled()).toBe(false);
expect(await formFields[3].isAutofilled()).toBe(false);
expect(await formFields[4].isAutofilled()).toBe(false);
const autofillTriggerEvent: any = createFakeEvent('animationstart');
autofillTriggerEvent.animationName = 'cdk-text-field-autofill-start';
// Dispatch an "animationstart" event on the input to trigger the
// autofill monitor.
fixture.nativeElement
.querySelector('#first-form-field input')
.dispatchEvent(autofillTriggerEvent);
expect(await formFields[0].isAutofilled()).toBe(true);
expect(await formFields[1].isAutofilled()).toBe(false);
expect(await formFields[2].isAutofilled()).toBe(false);
expect(await formFields[3].isAutofilled()).toBe(false);
expect(await formFields[4].isAutofilled()).toBe(false);
});
it('should be able to get theme color of form-field', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].getThemeColor()).toBe('primary');
expect(await formFields[1].getThemeColor()).toBe('warn');
expect(await formFields[2].getThemeColor()).toBe('accent');
expect(await formFields[3].getThemeColor()).toBe('primary');
expect(await formFields[4].getThemeColor()).toBe('primary');
});
it('should be able to get label of form-field', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].getLabel()).toBe(null);
expect(await formFields[1].getLabel()).toBe(null);
expect(await formFields[2].getLabel()).toBe('Label');
expect(await formFields[3].getLabel()).toBe('autocomplete_label');
expect(await formFields[4].getLabel()).toBe('Label');
});
it('should be able to get error messages of form-field', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[1].getTextErrors()).toEqual([]);
fixture.componentInstance.requiredControl.setValue('');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'blur');
expect(await formFields[1].getTextErrors()).toEqual(['Error 1', 'Error 2']);
});
it('should be able to get form-field by validity', async () => {
let invalid = await loader.getAllHarnesses(MatFormFieldHarness.with({isValid: false}));
expect(invalid.length).toBe(0);
fixture.componentInstance.requiredControl.setValue('');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'blur');
invalid = await loader.getAllHarnesses(MatFormFieldHarness.with({isValid: false}));
expect(invalid.length).toBe(1);
}); | {
"end_byte": 9588,
"start_byte": 1439,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/form-field-harness.spec.ts"
} |
components/src/material/form-field/testing/form-field-harness.spec.ts_9592_17079 | it('should be able to get error harnesses from the form-field harness', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[1].getErrors()).toEqual([]);
fixture.componentInstance.requiredControl.setValue('');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'blur');
const formFieldErrorHarnesses = await formFields[1].getErrors();
expect(formFieldErrorHarnesses.length).toBe(2);
expect(await formFieldErrorHarnesses[0].getText()).toBe('Error 1');
expect(await formFieldErrorHarnesses[1].getText()).toBe('Error 2');
const error1Harnesses = await formFields[1].getErrors({text: 'Error 1'});
expect(error1Harnesses.length).toBe(1);
expect(await error1Harnesses[0].getText()).toBe('Error 1');
});
it('should be able to directly load error harnesses', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[1].getErrors()).toEqual([]);
fixture.componentInstance.requiredControl.setValue('');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'blur');
const errorHarnesses = await loader.getAllHarnesses(MatErrorHarness);
expect(errorHarnesses.length).toBe(2);
expect(await errorHarnesses[0].getText()).toBe('Error 1');
expect(await errorHarnesses[1].getText()).toBe('Error 2');
const error1Harnesses = await loader.getAllHarnesses(MatErrorHarness.with({text: 'Error 1'}));
expect(error1Harnesses.length).toBe(1);
expect(await error1Harnesses[0].getText()).toBe('Error 1');
});
it('should be able to get hint messages of form-field', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[1].getTextHints()).toEqual(['Hint 1', 'Hint 2']);
fixture.componentInstance.requiredControl.setValue('');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'blur');
expect(await formFields[1].getTextHints()).toEqual([]);
});
it('should be able to get the prefix text of a form-field', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
const prefixTexts = await parallel(() => formFields.map(f => f.getPrefixText()));
expect(prefixTexts).toEqual(['prefix_textprefix_text_2', '', '', '', '', '', '']);
});
it('should be able to get the suffix text of a form-field', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
const suffixTexts = await parallel(() => formFields.map(f => f.getSuffixText()));
expect(suffixTexts).toEqual(['suffix_text', '', '', '', '', '', '']);
});
it('should be able to check if form field has been touched', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].isControlTouched()).toBe(null);
expect(await formFields[1].isControlTouched()).toBe(false);
fixture.componentInstance.requiredControl.setValue('');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'blur');
expect(await formFields[1].isControlTouched()).toBe(true);
});
it('should be able to check if form field is invalid', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].isControlValid()).toBe(null);
expect(await formFields[1].isControlValid()).toBe(true);
fixture.componentInstance.requiredControl.setValue('');
expect(await formFields[1].isControlValid()).toBe(false);
});
it('should be able to check if form field is dirty', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].isControlDirty()).toBe(null);
expect(await formFields[1].isControlDirty()).toBe(false);
fixture.componentInstance.requiredControl.setValue('new value');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'input');
expect(await formFields[1].isControlDirty()).toBe(true);
});
it('should be able to check if form field is pending async validation', async () => {
const formFields = await loader.getAllHarnesses(MatFormFieldHarness);
expect(await formFields[0].isControlPending()).toBe(null);
expect(await formFields[1].isControlPending()).toBe(false);
fixture.componentInstance.setupAsyncValidator();
fixture.componentInstance.requiredControl.setValue('');
expect(await formFields[1].isControlPending()).toBe(true);
});
});
@Component({
template: `
<mat-form-field id="first-form-field" [floatLabel]="shouldLabelFloat()">
<span matTextPrefix>prefix_text</span>
<span matTextPrefix>prefix_text_2</span>
<input matInput value="Sushi" name="favorite-food" placeholder="With placeholder"
[disabled]="isDisabled()">
<span matTextSuffix>suffix_text</span>
</mat-form-field>
<mat-form-field appearance="fill" color="warn" id="with-errors">
<span class="custom-control">Custom control harness</span>
<input matInput [formControl]="requiredControl">
<mat-error>Error 1</mat-error>
<div matError>Error 2</div>
<mat-hint align="start">Hint 1</mat-hint>
<mat-hint align="end">Hint 2</mat-hint>
</mat-form-field>
<mat-form-field appearance="fill" color="accent">
<mat-label>Label</mat-label>
<mat-select [disabled]="isDisabled()">
<mat-option>First</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field floatLabel="always" appearance="outline" color="primary">
<mat-label>autocomplete_label</mat-label>
<input type="text" matInput [matAutocomplete]="auto">
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete">
<mat-option>autocomplete_option</mat-option>
</mat-autocomplete>
<mat-form-field id="last-form-field" [floatLabel]="shouldLabelFloat()">
<mat-label>Label</mat-label>
<input matInput>
</mat-form-field>
<mat-form-field>
<mat-label>Date</mat-label>
<input matInput [matDatepicker]="datepicker">
<mat-datepicker #datepicker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>Date range</mat-label>
<mat-date-range-input [rangePicker]="rangePicker">
<input matStartDate placeholder="Start date"/>
<input matEndDate placeholder="End date"/>
</mat-date-range-input>
<mat-date-range-picker #rangePicker></mat-date-range-picker>
</mat-form-field>
`,
standalone: true,
imports: [
ReactiveFormsModule,
MatNativeDateModule,
MatAutocomplete,
MatAutocompleteTrigger,
MatDatepicker,
MatDatepickerInput,
MatDateRangePicker,
MatDateRangeInput,
MatEndDate,
MatError,
MatFormField,
MatHint,
MatInput,
MatLabel,
MatPrefix,
MatSelect,
MatStartDate,
MatSuffix,
MatOption,
],
})
class FormFieldHarnessTest {
requiredControl = new FormControl('Initial value', [Validators.required]);
shouldLabelFloat = signal<'always' | 'auto'>('auto');
hasLabel = false;
isDisabled = signal(false);
setupAsyncValidator() {
this.requiredControl.setValidators(() => null);
this.requiredControl.setAsyncValidators(() => new Promise(res => setTimeout(res, 10000)));
}
}
class CustomControlHarness extends ComponentHarness {
static hostSelector = '.custom-control';
} | {
"end_byte": 17079,
"start_byte": 9592,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/form-field-harness.spec.ts"
} |
components/src/material/form-field/testing/BUILD.bazel_0_1286 | 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",
"//src/material/datepicker/testing",
"//src/material/form-field/testing/control",
"//src/material/input/testing",
"//src/material/select/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/private",
"//src/cdk/testing/testbed",
"//src/material/autocomplete",
"//src/material/core",
"//src/material/datepicker",
"//src/material/datepicker/testing",
"//src/material/form-field",
"//src/material/input",
"//src/material/input/testing",
"//src/material/select",
"//src/material/select/testing",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":unit_tests_lib",
],
)
| {
"end_byte": 1286,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/BUILD.bazel"
} |
components/src/material/form-field/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';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/index.ts"
} |
components/src/material/form-field/testing/control/form-field-control-harness.ts_0_484 | /**
* @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} from '@angular/cdk/testing';
/**
* Base class for custom form-field control harnesses. Harnesses for
* custom controls with form-fields need to implement this interface.
*/
export abstract class MatFormFieldControlHarness extends ComponentHarness {}
| {
"end_byte": 484,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/control/form-field-control-harness.ts"
} |
components/src/material/form-field/testing/control/BUILD.bazel_0_270 | load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "control",
srcs = glob(["**/*.ts"]),
deps = ["//src/cdk/testing"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 270,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/control/BUILD.bazel"
} |
components/src/material/form-field/testing/control/index.ts_0_250 | /**
* @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 './form-field-control-harness';
| {
"end_byte": 250,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/form-field/testing/control/index.ts"
} |
components/src/material/testing/month-constants.ts_0_546 | /**
* @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
*/
/**
* When constructing a Date, the month is zero-based. This can be confusing, since people are
* used to seeing them one-based. So we create these aliases to make writing the tests easier.
*/
export const JAN = 0,
FEB = 1,
MAR = 2,
APR = 3,
MAY = 4,
JUN = 5,
JUL = 6,
AUG = 7,
SEP = 8,
OCT = 9,
NOV = 10,
DEC = 11;
| {
"end_byte": 546,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/testing/month-constants.ts"
} |
components/src/material/testing/README.md_0_127 | Note that this is not an entry-point. This directory is just used to share testing logic
that is specific to Angular Material.
| {
"end_byte": 127,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/testing/README.md"
} |
components/src/material/testing/BUILD.bazel_0_266 | load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "testing",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//src/material/core",
"@npm//@angular/core",
],
)
| {
"end_byte": 266,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/testing/BUILD.bazel"
} |
components/src/material/testing/index.ts_0_239 | /**
* @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 './month-constants';
| {
"end_byte": 239,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/testing/index.ts"
} |
components/src/material/expansion/expansion-panel-header.ts_0_7489 | /**
* @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 {FocusableOption, FocusMonitor, FocusOrigin} from '@angular/cdk/a11y';
import {ENTER, hasModifierKey, SPACE} from '@angular/cdk/keycodes';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Directive,
ElementRef,
Input,
numberAttribute,
OnDestroy,
ViewEncapsulation,
ANIMATION_MODULE_TYPE,
inject,
HostAttributeToken,
} from '@angular/core';
import {EMPTY, merge, Subscription} from 'rxjs';
import {filter} from 'rxjs/operators';
import {MatAccordionTogglePosition} from './accordion-base';
import {matExpansionAnimations} from './expansion-animations';
import {
MatExpansionPanel,
MatExpansionPanelDefaultOptions,
MAT_EXPANSION_PANEL_DEFAULT_OPTIONS,
} from './expansion-panel';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
import {_StructuralStylesLoader} from '@angular/material/core';
/**
* Header element of a `<mat-expansion-panel>`.
*/
@Component({
selector: 'mat-expansion-panel-header',
styleUrl: 'expansion-panel-header.css',
templateUrl: 'expansion-panel-header.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
animations: [matExpansionAnimations.indicatorRotate],
host: {
'class': 'mat-expansion-panel-header mat-focus-indicator',
'role': 'button',
'[attr.id]': 'panel._headerId',
'[attr.tabindex]': 'disabled ? -1 : tabIndex',
'[attr.aria-controls]': '_getPanelId()',
'[attr.aria-expanded]': '_isExpanded()',
'[attr.aria-disabled]': 'panel.disabled',
'[class.mat-expanded]': '_isExpanded()',
'[class.mat-expansion-toggle-indicator-after]': `_getTogglePosition() === 'after'`,
'[class.mat-expansion-toggle-indicator-before]': `_getTogglePosition() === 'before'`,
'[class._mat-animation-noopable]': '_animationMode === "NoopAnimations"',
'[style.height]': '_getHeaderHeight()',
'(click)': '_toggle()',
'(keydown)': '_keydown($event)',
},
})
export class MatExpansionPanelHeader implements AfterViewInit, OnDestroy, FocusableOption {
panel = inject(MatExpansionPanel, {host: true});
private _element = inject(ElementRef);
private _focusMonitor = inject(FocusMonitor);
private _changeDetectorRef = inject(ChangeDetectorRef);
_animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
private _parentChangeSubscription = Subscription.EMPTY;
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
const panel = this.panel;
const defaultOptions = inject<MatExpansionPanelDefaultOptions>(
MAT_EXPANSION_PANEL_DEFAULT_OPTIONS,
{optional: true},
);
const tabIndex = inject(new HostAttributeToken('tabindex'), {optional: true});
const accordionHideToggleChange = panel.accordion
? panel.accordion._stateChanges.pipe(
filter(changes => !!(changes['hideToggle'] || changes['togglePosition'])),
)
: EMPTY;
this.tabIndex = parseInt(tabIndex || '') || 0;
// Since the toggle state depends on an @Input on the panel, we
// need to subscribe and trigger change detection manually.
this._parentChangeSubscription = merge(
panel.opened,
panel.closed,
accordionHideToggleChange,
panel._inputChanges.pipe(
filter(changes => {
return !!(changes['hideToggle'] || changes['disabled'] || changes['togglePosition']);
}),
),
).subscribe(() => this._changeDetectorRef.markForCheck());
// Avoids focus being lost if the panel contained the focused element and was closed.
panel.closed
.pipe(filter(() => panel._containsFocus()))
.subscribe(() => this._focusMonitor.focusVia(this._element, 'program'));
if (defaultOptions) {
this.expandedHeight = defaultOptions.expandedHeight;
this.collapsedHeight = defaultOptions.collapsedHeight;
}
}
/** Height of the header while the panel is expanded. */
@Input() expandedHeight: string;
/** Height of the header while the panel is collapsed. */
@Input() collapsedHeight: string;
/** Tab index of the header. */
@Input({
transform: (value: unknown) => (value == null ? 0 : numberAttribute(value)),
})
tabIndex: number = 0;
/**
* Whether the associated panel is disabled. Implemented as a part of `FocusableOption`.
* @docs-private
*/
get disabled(): boolean {
return this.panel.disabled;
}
/** Toggles the expanded state of the panel. */
_toggle(): void {
if (!this.disabled) {
this.panel.toggle();
}
}
/** Gets whether the panel is expanded. */
_isExpanded(): boolean {
return this.panel.expanded;
}
/** Gets the expanded state string of the panel. */
_getExpandedState(): string {
return this.panel._getExpandedState();
}
/** Gets the panel id. */
_getPanelId(): string {
return this.panel.id;
}
/** Gets the toggle position for the header. */
_getTogglePosition(): MatAccordionTogglePosition {
return this.panel.togglePosition;
}
/** Gets whether the expand indicator should be shown. */
_showToggle(): boolean {
return !this.panel.hideToggle && !this.panel.disabled;
}
/**
* Gets the current height of the header. Null if no custom height has been
* specified, and if the default height from the stylesheet should be used.
*/
_getHeaderHeight(): string | null {
const isExpanded = this._isExpanded();
if (isExpanded && this.expandedHeight) {
return this.expandedHeight;
} else if (!isExpanded && this.collapsedHeight) {
return this.collapsedHeight;
}
return null;
}
/** Handle keydown event calling to toggle() if appropriate. */
_keydown(event: KeyboardEvent) {
switch (event.keyCode) {
// Toggle for space and enter keys.
case SPACE:
case ENTER:
if (!hasModifierKey(event)) {
event.preventDefault();
this._toggle();
}
break;
default:
if (this.panel.accordion) {
this.panel.accordion._handleHeaderKeydown(event);
}
return;
}
}
/**
* Focuses the panel header. Implemented as a part of `FocusableOption`.
* @param origin Origin of the action that triggered the focus.
* @docs-private
*/
focus(origin?: FocusOrigin, options?: FocusOptions) {
if (origin) {
this._focusMonitor.focusVia(this._element, origin, options);
} else {
this._element.nativeElement.focus(options);
}
}
ngAfterViewInit() {
this._focusMonitor.monitor(this._element).subscribe(origin => {
if (origin && this.panel.accordion) {
this.panel.accordion._handleHeaderFocus(this);
}
});
}
ngOnDestroy() {
this._parentChangeSubscription.unsubscribe();
this._focusMonitor.stopMonitoring(this._element);
}
}
/**
* Description element of a `<mat-expansion-panel-header>`.
*/
@Directive({
selector: 'mat-panel-description',
host: {
class: 'mat-expansion-panel-header-description',
},
})
export class MatExpansionPanelDescription {}
/**
* Title element of a `<mat-expansion-panel-header>`.
*/
@Directive({
selector: 'mat-panel-title',
host: {
class: 'mat-expansion-panel-header-title',
},
})
export class MatExpansionPanelTitle {}
| {
"end_byte": 7489,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion-panel-header.ts"
} |
components/src/material/expansion/expansion.md_0_2833 | `<mat-expansion-panel>` provides an expandable details-summary view.
<!-- example(expansion-overview) -->
### Expansion-panel content
#### Header
The `<mat-expansion-panel-header>` shows a summary of the panel content and acts
as the control for expanding and collapsing. This header may optionally contain an
`<mat-panel-title>` and an `<mat-panel-description>`, which format the content of the
header to align with Material Design specifications.
<!-- example({"example": "expansion-overview",
"file": "expansion-overview-example.html",
"region": "basic-panel"}) -->
By default, the expansion-panel header includes a toggle icon at the end of the
header to indicate the expansion state. This icon can be hidden via the
`hideToggle` property.
<!-- example({"example": "expansion-overview",
"file": "expansion-overview-example.html",
"region": "hide-toggle"}) -->
#### Action bar
Actions may optionally be included at the bottom of the panel, visible only when the expansion
is in its expanded state.
<!-- example({"example": "expansion-steps",
"file": "expansion-steps-example.html",
"region": "action-bar"}) -->
#### Disabling a panel
Expansion panels can be disabled using the `disabled` attribute. A disabled expansion panel can't
be toggled by the user, but can still be manipulated programmatically.
<!-- example({"example": "expansion-expand-collapse-all",
"file": "expansion-expand-collapse-all-example.html",
"region": "disabled"}) -->
### Accordion
Multiple expansion-panels can be combined into an accordion. The `multi="true"` input allows the
expansions state to be set independently of each other. When `multi="false"` (default) just one
panel can be expanded at a given time:
<!-- example({"example": "expansion-expand-collapse-all",
"file": "expansion-expand-collapse-all-example.html",
"region": "multi"}) -->
### Lazy rendering
By default, the expansion panel content will be initialized even when the panel is closed.
To instead defer initialization until the panel is open, the content should be provided as
an `ng-template`:
```html
<mat-expansion-panel>
<mat-expansion-panel-header>
This is the expansion title
</mat-expansion-panel-header>
<ng-template matExpansionPanelContent>
Some deferred content
</ng-template>
</mat-expansion-panel>
```
### Accessibility
`MatExpansionPanel` imitates the experience of the native `<details>` and `<summary>` elements.
The expansion panel header applies `role="button"` and the `aria-controls` attribute with the
content element's ID.
Because expansion panel headers are buttons, avoid adding interactive controls as children
of `<mat-expansion-panel-header>`, including buttons and anchors.
| {
"end_byte": 2833,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion.md"
} |
components/src/material/expansion/_expansion-variables.scss_0_1133 | // Default minimum and maximum height for collapsed panel headers.
$header-collapsed-height: 48px !default;
$header-collapsed-minimum-height: 36px !default;
$header-collapsed-maximum-height:
$header-collapsed-height !default;
// Default minimum and maximum height for expanded panel headers.
$header-expanded-height: 64px !default;
$header-expanded-minimum-height: 48px !default;
$header-expanded-maximum-height:
$header-expanded-height !default;
// Density configuration for the expansion panel. Captures the
// height for both expanded and collapsed panel headers.
$header-density-config: (
collapsed-height: (
default: $header-collapsed-height,
maximum: $header-collapsed-maximum-height,
minimum: $header-collapsed-minimum-height,
),
expanded-height: (
default: $header-expanded-height,
maximum: $header-expanded-maximum-height,
minimum: $header-expanded-minimum-height,
)
) !default;
// Note: Keep this in sync with the animation timing for the toggle indicator
// and body expansion. These are animated using Angular animations.
$header-transition: 225ms cubic-bezier(0.4, 0, 0.2, 1);
| {
"end_byte": 1133,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/_expansion-variables.scss"
} |
components/src/material/expansion/public-api.ts_0_523 | /**
* @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 './expansion-module';
export * from './accordion';
export * from './accordion-base';
export * from './expansion-panel';
export * from './expansion-panel-header';
export * from './expansion-panel-content';
export * from './expansion-animations';
export {MAT_EXPANSION_PANEL} from './expansion-panel-base';
| {
"end_byte": 523,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/public-api.ts"
} |
components/src/material/expansion/accordion-base.ts_0_1389 | /**
* @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 {InjectionToken} from '@angular/core';
import {CdkAccordion} from '@angular/cdk/accordion';
/** MatAccordion's display modes. */
export type MatAccordionDisplayMode = 'default' | 'flat';
/** MatAccordion's toggle positions. */
export type MatAccordionTogglePosition = 'before' | 'after';
/**
* Base interface for a `MatAccordion`.
* @docs-private
*/
export interface MatAccordionBase extends CdkAccordion {
/** Whether the expansion indicator should be hidden. */
hideToggle: boolean;
/** Display mode used for all expansion panels in the accordion. */
displayMode: MatAccordionDisplayMode;
/** The position of the expansion indicator. */
togglePosition: MatAccordionTogglePosition;
/** Handles keyboard events coming in from the panel headers. */
_handleHeaderKeydown: (event: KeyboardEvent) => void;
/** Handles focus events on the panel headers. */
_handleHeaderFocus: (header: any) => void;
}
/**
* Token used to provide a `MatAccordion` to `MatExpansionPanel`.
* Used primarily to avoid circular imports between `MatAccordion` and `MatExpansionPanel`.
*/
export const MAT_ACCORDION = new InjectionToken<MatAccordionBase>('MAT_ACCORDION');
| {
"end_byte": 1389,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/accordion-base.ts"
} |
components/src/material/expansion/expansion-panel-base.ts_0_807 | /**
* @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 {InjectionToken} from '@angular/core';
import {CdkAccordionItem} from '@angular/cdk/accordion';
/**
* Base interface for a `MatExpansionPanel`.
* @docs-private
*/
export interface MatExpansionPanelBase extends CdkAccordionItem {
/** Whether the toggle indicator should be hidden. */
hideToggle: boolean;
}
/**
* Token used to provide a `MatExpansionPanel` to `MatExpansionPanelContent`.
* Used to avoid circular imports between `MatExpansionPanel` and `MatExpansionPanelContent`.
*/
export const MAT_EXPANSION_PANEL = new InjectionToken<MatExpansionPanelBase>('MAT_EXPANSION_PANEL');
| {
"end_byte": 807,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion-panel-base.ts"
} |
components/src/material/expansion/accordion.ts_0_3138 | /**
* @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 {
Directive,
Input,
ContentChildren,
QueryList,
AfterContentInit,
OnDestroy,
booleanAttribute,
} from '@angular/core';
import {CdkAccordion} from '@angular/cdk/accordion';
import {FocusKeyManager} from '@angular/cdk/a11y';
import {startWith} from 'rxjs/operators';
import {
MAT_ACCORDION,
MatAccordionBase,
MatAccordionDisplayMode,
MatAccordionTogglePosition,
} from './accordion-base';
import {MatExpansionPanelHeader} from './expansion-panel-header';
/**
* Directive for a Material Design Accordion.
*/
@Directive({
selector: 'mat-accordion',
exportAs: 'matAccordion',
providers: [
{
provide: MAT_ACCORDION,
useExisting: MatAccordion,
},
],
host: {
class: 'mat-accordion',
// Class binding which is only used by the test harness as there is no other
// way for the harness to detect if multiple panel support is enabled.
'[class.mat-accordion-multi]': 'this.multi',
},
})
export class MatAccordion
extends CdkAccordion
implements MatAccordionBase, AfterContentInit, OnDestroy
{
private _keyManager: FocusKeyManager<MatExpansionPanelHeader>;
/** Headers belonging to this accordion. */
private _ownHeaders = new QueryList<MatExpansionPanelHeader>();
/** All headers inside the accordion. Includes headers inside nested accordions. */
@ContentChildren(MatExpansionPanelHeader, {descendants: true})
_headers: QueryList<MatExpansionPanelHeader>;
/** Whether the expansion indicator should be hidden. */
@Input({transform: booleanAttribute})
hideToggle: boolean = false;
/**
* Display mode used for all expansion panels in the accordion. Currently two display
* modes exist:
* default - a gutter-like spacing is placed around any expanded panel, placing the expanded
* panel at a different elevation from the rest of the accordion.
* flat - no spacing is placed around expanded panels, showing all panels at the same
* elevation.
*/
@Input() displayMode: MatAccordionDisplayMode = 'default';
/** The position of the expansion indicator. */
@Input() togglePosition: MatAccordionTogglePosition = 'after';
ngAfterContentInit() {
this._headers.changes
.pipe(startWith(this._headers))
.subscribe((headers: QueryList<MatExpansionPanelHeader>) => {
this._ownHeaders.reset(headers.filter(header => header.panel.accordion === this));
this._ownHeaders.notifyOnChanges();
});
this._keyManager = new FocusKeyManager(this._ownHeaders).withWrap().withHomeAndEnd();
}
/** Handles keyboard events coming in from the panel headers. */
_handleHeaderKeydown(event: KeyboardEvent) {
this._keyManager.onKeydown(event);
}
_handleHeaderFocus(header: MatExpansionPanelHeader) {
this._keyManager.updateActiveItem(header);
}
override ngOnDestroy() {
super.ngOnDestroy();
this._keyManager?.destroy();
this._ownHeaders.destroy();
}
}
| {
"end_byte": 3138,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/accordion.ts"
} |
components/src/material/expansion/accordion.spec.ts_0_614 | import {FocusMonitor} from '@angular/cdk/a11y';
import {DOWN_ARROW, END, HOME, UP_ARROW} from '@angular/cdk/keycodes';
import {
createKeyboardEvent,
dispatchEvent,
dispatchKeyboardEvent,
} from '@angular/cdk/testing/private';
import {Component, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {TestBed, inject, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {
MatAccordion,
MatExpansionModule,
MatExpansionPanel,
MatExpansionPanelHeader,
} from './index'; | {
"end_byte": 614,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/accordion.spec.ts"
} |
components/src/material/expansion/accordion.spec.ts_616_10543 | describe('MatAccordion', () => {
let focusMonitor: FocusMonitor;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
BrowserAnimationsModule,
MatExpansionModule,
AccordionWithHideToggle,
AccordionWithTogglePosition,
NestedPanel,
SetOfItems,
NestedAccordions,
],
});
inject([FocusMonitor], (fm: FocusMonitor) => {
focusMonitor = fm;
})();
}));
it('should ensure only one item is expanded at a time', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.detectChanges();
const items = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
const panelInstances = fixture.componentInstance.panels.toArray();
panelInstances[0].expanded = true;
fixture.detectChanges();
expect(items[0].classes['mat-expanded']).toBeTruthy();
expect(items[1].classes['mat-expanded']).toBeFalsy();
panelInstances[1].expanded = true;
fixture.detectChanges();
expect(items[0].classes['mat-expanded']).toBeFalsy();
expect(items[1].classes['mat-expanded']).toBeTruthy();
});
it('should allow multiple items to be expanded simultaneously', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.componentInstance.multi = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
const panelInstances = fixture.componentInstance.panels.toArray();
panelInstances[0].expanded = true;
panelInstances[1].expanded = true;
fixture.detectChanges();
expect(panels[0].classes['mat-expanded']).toBeTruthy();
expect(panels[1].classes['mat-expanded']).toBeTruthy();
});
it('should expand or collapse all enabled items', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.detectChanges();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
fixture.componentInstance.multi = true;
fixture.componentInstance.panels.toArray()[1].expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(panels[0].classes['mat-expanded']).toBeFalsy();
expect(panels[1].classes['mat-expanded']).toBeTruthy();
fixture.componentInstance.accordion.openAll();
fixture.detectChanges();
expect(panels[0].classes['mat-expanded']).toBeTruthy();
expect(panels[1].classes['mat-expanded']).toBeTruthy();
fixture.componentInstance.accordion.closeAll();
fixture.detectChanges();
expect(panels[0].classes['mat-expanded']).toBeFalsy();
expect(panels[1].classes['mat-expanded']).toBeFalsy();
});
it('should not expand or collapse disabled items', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.detectChanges();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
fixture.componentInstance.multi = true;
fixture.componentInstance.panels.toArray()[1].disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.accordion.openAll();
fixture.detectChanges();
expect(panels[0].classes['mat-expanded']).toBeTruthy();
expect(panels[1].classes['mat-expanded']).toBeFalsy();
fixture.componentInstance.accordion.closeAll();
fixture.detectChanges();
expect(panels[0].classes['mat-expanded']).toBeFalsy();
expect(panels[1].classes['mat-expanded']).toBeFalsy();
});
it('should not register nested panels to the same accordion', () => {
const fixture = TestBed.createComponent(NestedPanel);
fixture.detectChanges();
const innerPanel = fixture.componentInstance.innerPanel;
const outerPanel = fixture.componentInstance.outerPanel;
expect(innerPanel.accordion).not.toBe(outerPanel.accordion);
});
it('should update the expansion panel if hideToggle changed', () => {
const fixture = TestBed.createComponent(AccordionWithHideToggle);
const panel = fixture.debugElement.query(By.directive(MatExpansionPanel))!;
fixture.detectChanges();
expect(panel.nativeElement.querySelector('.mat-expansion-indicator'))
.withContext('Expected the expansion indicator to be present.')
.toBeTruthy();
fixture.componentInstance.hideToggle = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(panel.nativeElement.querySelector('.mat-expansion-indicator'))
.withContext('Expected the expansion indicator to be removed.')
.toBeFalsy();
});
it('should update the expansion panel if togglePosition changed', () => {
const fixture = TestBed.createComponent(AccordionWithTogglePosition);
const panel = fixture.debugElement.query(By.directive(MatExpansionPanel))!;
fixture.detectChanges();
expect(panel.nativeElement.querySelector('.mat-expansion-toggle-indicator-after'))
.withContext('Expected the expansion indicator to be positioned after.')
.toBeTruthy();
fixture.componentInstance.togglePosition = 'before';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(panel.nativeElement.querySelector('.mat-expansion-toggle-indicator-before'))
.withContext('Expected the expansion indicator to be positioned before.')
.toBeTruthy();
});
it('should move focus to the next header when pressing the down arrow', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.detectChanges();
const headerElements = fixture.debugElement.queryAll(By.css('mat-expansion-panel-header'));
const headers = fixture.componentInstance.headers.toArray();
focusMonitor.focusVia(headerElements[0].nativeElement, 'keyboard');
headers.forEach(header => spyOn(header, 'focus'));
// Stop at the second-last header so focus doesn't wrap around.
for (let i = 0; i < headerElements.length - 1; i++) {
dispatchKeyboardEvent(headerElements[i].nativeElement, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(headers[i + 1].focus).toHaveBeenCalledTimes(1);
}
});
it('should not move focus into nested accordions', () => {
const fixture = TestBed.createComponent(NestedAccordions);
fixture.detectChanges();
const headerElements = fixture.debugElement.queryAll(By.css('mat-expansion-panel-header'));
const headers = fixture.componentInstance.headers.toArray();
const {firstInnerHeader, secondOuterHeader} = fixture.componentInstance;
focusMonitor.focusVia(headerElements[0].nativeElement, 'keyboard');
headers.forEach(header => spyOn(header, 'focus'));
dispatchKeyboardEvent(headerElements[0].nativeElement, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(secondOuterHeader.focus).toHaveBeenCalledTimes(1);
expect(firstInnerHeader.focus).not.toHaveBeenCalled();
});
it('should move focus to the next header when pressing the up arrow', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.detectChanges();
const headerElements = fixture.debugElement.queryAll(By.css('mat-expansion-panel-header'));
const headers = fixture.componentInstance.headers.toArray();
focusMonitor.focusVia(headerElements[headerElements.length - 1].nativeElement, 'keyboard');
headers.forEach(header => spyOn(header, 'focus'));
// Stop before the first header
for (let i = headers.length - 1; i > 0; i--) {
dispatchKeyboardEvent(headerElements[i].nativeElement, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(headers[i - 1].focus).toHaveBeenCalledTimes(1);
}
});
it('should skip disabled items when moving focus with the keyboard', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.detectChanges();
const headerElements = fixture.debugElement.queryAll(By.css('mat-expansion-panel-header'));
const panels = fixture.componentInstance.panels.toArray();
const headers = fixture.componentInstance.headers.toArray();
focusMonitor.focusVia(headerElements[0].nativeElement, 'keyboard');
headers.forEach(header => spyOn(header, 'focus'));
panels[1].disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchKeyboardEvent(headerElements[0].nativeElement, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(headers[1].focus).not.toHaveBeenCalled();
expect(headers[2].focus).toHaveBeenCalledTimes(1);
});
it('should focus the first header when pressing the home key', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.detectChanges();
const headerElements = fixture.debugElement.queryAll(By.css('mat-expansion-panel-header'));
const headers = fixture.componentInstance.headers.toArray();
headers.forEach(header => spyOn(header, 'focus'));
const event = dispatchKeyboardEvent(
headerElements[headerElements.length - 1].nativeElement,
'keydown',
HOME,
);
fixture.detectChanges();
expect(headers[0].focus).toHaveBeenCalledTimes(1);
expect(event.defaultPrevented).toBe(true);
});
it('should not handle the home key when it is pressed with a modifier', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.detectChanges();
const headerElements = fixture.debugElement.queryAll(By.css('mat-expansion-panel-header'));
const headers = fixture.componentInstance.headers.toArray();
headers.forEach(header => spyOn(header, 'focus'));
const eventTarget = headerElements[headerElements.length - 1].nativeElement;
const event = createKeyboardEvent('keydown', HOME, undefined, {alt: true});
dispatchEvent(eventTarget, event);
fixture.detectChanges();
expect(headers[0].focus).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(false);
}); | {
"end_byte": 10543,
"start_byte": 616,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/accordion.spec.ts"
} |
components/src/material/expansion/accordion.spec.ts_10547_14681 | it('should focus the last header when pressing the end key', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.detectChanges();
const headerElements = fixture.debugElement.queryAll(By.css('mat-expansion-panel-header'));
const headers = fixture.componentInstance.headers.toArray();
headers.forEach(header => spyOn(header, 'focus'));
const event = dispatchKeyboardEvent(headerElements[0].nativeElement, 'keydown', END);
fixture.detectChanges();
expect(headers[headers.length - 1].focus).toHaveBeenCalledTimes(1);
expect(event.defaultPrevented).toBe(true);
});
it('should not handle the end key when it is pressed with a modifier', () => {
const fixture = TestBed.createComponent(SetOfItems);
fixture.detectChanges();
const headerElements = fixture.debugElement.queryAll(By.css('mat-expansion-panel-header'));
const headers = fixture.componentInstance.headers.toArray();
headers.forEach(header => spyOn(header, 'focus'));
const eventTarget = headerElements[0].nativeElement;
const event = createKeyboardEvent('keydown', END, undefined, {alt: true});
dispatchEvent(eventTarget, event);
fixture.detectChanges();
expect(headers[headers.length - 1].focus).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(false);
});
});
@Component({
template: `
<mat-accordion [multi]="multi">
@for (i of [0, 1, 2, 3]; track i) {
<mat-expansion-panel>
<mat-expansion-panel-header>Summary {{i}}</mat-expansion-panel-header>
<p>Content</p>
</mat-expansion-panel>
}
</mat-accordion>`,
standalone: true,
imports: [MatExpansionModule],
})
class SetOfItems {
@ViewChild(MatAccordion) accordion: MatAccordion;
@ViewChildren(MatExpansionPanel) panels: QueryList<MatExpansionPanel>;
@ViewChildren(MatExpansionPanelHeader) headers: QueryList<MatExpansionPanelHeader>;
multi: boolean = false;
}
@Component({
template: `
<mat-accordion>
<mat-expansion-panel>
<mat-expansion-panel-header>Summary 0</mat-expansion-panel-header>
Content 0
<mat-expansion-panel>
<mat-expansion-panel-header #firstInnerHeader>Summary 0-0</mat-expansion-panel-header>
Content 0-0
</mat-expansion-panel>
</mat-expansion-panel>
<mat-expansion-panel>
<mat-expansion-panel-header #secondOuterHeader>Summary 1</mat-expansion-panel-header>
Content 1
</mat-expansion-panel>
</mat-accordion>`,
standalone: true,
imports: [MatExpansionModule],
})
class NestedAccordions {
@ViewChildren(MatExpansionPanelHeader) headers: QueryList<MatExpansionPanelHeader>;
@ViewChild('secondOuterHeader') secondOuterHeader: MatExpansionPanelHeader;
@ViewChild('firstInnerHeader') firstInnerHeader: MatExpansionPanelHeader;
}
@Component({
template: `
<mat-accordion>
<mat-expansion-panel #outerPanel="matExpansionPanel">
<mat-expansion-panel-header>Outer Panel</mat-expansion-panel-header>
<mat-expansion-panel #innerPanel="matExpansionPanel">
<mat-expansion-panel-header>Inner Panel</mat-expansion-panel-header>
<p>Content</p>
</mat-expansion-panel>
</mat-expansion-panel>
</mat-accordion>`,
standalone: true,
imports: [MatExpansionModule],
})
class NestedPanel {
@ViewChild('outerPanel') outerPanel: MatExpansionPanel;
@ViewChild('innerPanel') innerPanel: MatExpansionPanel;
}
@Component({
template: `
<mat-accordion [hideToggle]="hideToggle">
<mat-expansion-panel>
<mat-expansion-panel-header>Header</mat-expansion-panel-header>
<p>Content</p>
</mat-expansion-panel>
</mat-accordion>`,
standalone: true,
imports: [MatExpansionModule],
})
class AccordionWithHideToggle {
hideToggle = false;
}
@Component({
template: `
<mat-accordion [togglePosition]="togglePosition">
<mat-expansion-panel>
<mat-expansion-panel-header>Header</mat-expansion-panel-header>
<p>Content</p>
</mat-expansion-panel>
</mat-accordion>`,
standalone: true,
imports: [MatExpansionModule],
})
class AccordionWithTogglePosition {
togglePosition = 'after';
} | {
"end_byte": 14681,
"start_byte": 10547,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/accordion.spec.ts"
} |
components/src/material/expansion/expansion-panel-header.scss_0_5217 | @use '@angular/cdk';
@use '../core/tokens/m2/mat/expansion' as tokens-mat-expansion;
@use '../core/tokens/token-utils';
@use './expansion-variables';
.mat-expansion-panel-header {
display: flex;
flex-direction: row;
align-items: center;
padding: 0 24px;
border-radius: inherit;
transition: height expansion-variables.$header-transition;
@include token-utils.use-tokens(
tokens-mat-expansion.$prefix, tokens-mat-expansion.get-token-slots()) {
@include token-utils.create-token-slot(height, header-collapsed-state-height);
@include token-utils.create-token-slot(font-family, header-text-font);
@include token-utils.create-token-slot(font-size, header-text-size);
@include token-utils.create-token-slot(font-weight, header-text-weight);
@include token-utils.create-token-slot(line-height, header-text-line-height);
@include token-utils.create-token-slot(letter-spacing, header-text-tracking);
&.mat-expanded {
@include token-utils.create-token-slot(height, header-expanded-state-height);
}
&[aria-disabled='true'] {
@include token-utils.create-token-slot(color, header-disabled-state-text-color);
}
&:not([aria-disabled='true']) {
cursor: pointer;
.mat-expansion-panel:not(.mat-expanded) &:hover {
@include token-utils.create-token-slot(background, header-hover-state-layer-color);
// Disable the hover on touch devices since it can appear like it is stuck. We can't use
// `@media (hover)` above, because the desktop support browser support isn't great.
@media (hover: none) {
@include token-utils.create-token-slot(background, container-background-color);
}
}
// The `.mat-expansion-panel` here is redundant, but we need the additional specificity.
.mat-expansion-panel &.cdk-keyboard-focused,
.mat-expansion-panel &.cdk-program-focused {
@include token-utils.create-token-slot(background, header-focus-state-layer-color);
}
}
}
// If the `NoopAnimationsModule` is used, disable the height transition.
&._mat-animation-noopable {
transition: none;
}
&:focus,
&:hover {
outline: none;
}
&.mat-expanded:focus,
&.mat-expanded:hover {
background: inherit;
}
&.mat-expansion-toggle-indicator-before {
flex-direction: row-reverse;
.mat-expansion-indicator {
margin: 0 16px 0 0;
[dir='rtl'] & {
margin: 0 0 0 16px;
}
}
}
}
.mat-content {
display: flex;
flex: 1;
flex-direction: row;
overflow: hidden;
// width of .mat-expansion-indicator::after element
&.mat-content-hide-toggle {
margin-right: 8px;
[dir='rtl'] & {
margin-right: 0;
margin-left: 8px;
}
.mat-expansion-toggle-indicator-before & {
margin-left: 24px;
margin-right: 0;
[dir='rtl'] & {
margin-right: 24px;
margin-left: 0;
}
}
}
}
.mat-expansion-panel-header-title {
@include token-utils.use-tokens(
tokens-mat-expansion.$prefix, tokens-mat-expansion.get-token-slots()) {
@include token-utils.create-token-slot(color, header-text-color);
}
}
.mat-expansion-panel-header-title,
.mat-expansion-panel-header-description {
display: flex;
flex-grow: 1;
flex-basis: 0;
margin-right: 16px;
align-items: center;
[dir='rtl'] & {
margin-right: 0;
margin-left: 16px;
}
.mat-expansion-panel-header[aria-disabled='true'] & {
color: inherit;
}
}
.mat-expansion-panel-header-description {
flex-grow: 2;
@include token-utils.use-tokens(
tokens-mat-expansion.$prefix, tokens-mat-expansion.get-token-slots()) {
@include token-utils.create-token-slot(color, header-description-color);
}
}
// Creates the expansion indicator arrow. Done using ::after
// rather than having additional nodes in the template.
.mat-expansion-indicator {
&::after {
border-style: solid;
border-width: 0 2px 2px 0;
content: '';
display: inline-block;
padding: 3px;
transform: rotate(45deg);
vertical-align: middle;
@include token-utils.use-tokens(
tokens-mat-expansion.$prefix, tokens-mat-expansion.get-token-slots()) {
@include token-utils.create-token-slot(color, header-indicator-color);
@include token-utils.create-token-slot(display, legacy-header-indicator-display,
inline-block);
}
}
svg {
width: 24px;
height: 24px;
// The SVG icon isn't edge-to-edge so we need to offset
// it slightly so it's aligned correctly horizontally.
margin: 0 -8px;
// Since the container is `display: inline`, we need to set this to center the arrow.
// Ideally we'd make the container `inline-flex`, but that affects M2.
vertical-align: middle;
@include token-utils.use-tokens(
tokens-mat-expansion.$prefix, tokens-mat-expansion.get-token-slots()) {
@include token-utils.create-token-slot(fill, header-indicator-color);
@include token-utils.create-token-slot(display, header-indicator-display, none);
}
}
}
@include cdk.high-contrast {
.mat-expansion-panel-content {
border-top: 1px solid;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
}
| {
"end_byte": 5217,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion-panel-header.scss"
} |
components/src/material/expansion/expansion.spec.ts_0_591 | import {ENTER, SPACE} from '@angular/cdk/keycodes';
import {
createKeyboardEvent,
dispatchEvent,
dispatchKeyboardEvent,
} from '@angular/cdk/testing/private';
import {Component, ViewChild} from '@angular/core';
import {
ComponentFixture,
TestBed,
fakeAsync,
flush,
tick,
waitForAsync,
} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {
MAT_EXPANSION_PANEL_DEFAULT_OPTIONS,
MatExpansionModule,
MatExpansionPanel,
MatExpansionPanelHeader,
} from './index'; | {
"end_byte": 591,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion.spec.ts"
} |
components/src/material/expansion/expansion.spec.ts_593_10531 | describe('MatExpansionPanel', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatExpansionModule,
NoopAnimationsModule,
PanelWithContent,
PanelWithContentInNgIf,
PanelWithCustomMargin,
LazyPanelWithContent,
LazyPanelOpenOnLoad,
PanelWithTwoWayBinding,
PanelWithHeaderTabindex,
NestedLazyPanelWithContent,
],
});
}));
it('should expand and collapse the panel', fakeAsync(() => {
const fixture = TestBed.createComponent(PanelWithContent);
const headerEl = fixture.nativeElement.querySelector('.mat-expansion-panel-header');
fixture.detectChanges();
expect(headerEl.classList).not.toContain('mat-expanded');
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(headerEl.classList).toContain('mat-expanded');
}));
it('should add strong focus indication', () => {
const fixture = TestBed.createComponent(PanelWithContent);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.mat-expansion-panel-header').classList).toContain(
'mat-focus-indicator',
);
});
it('should be able to render panel content lazily', () => {
const fixture = TestBed.createComponent(LazyPanelWithContent);
const content = fixture.debugElement.query(
By.css('.mat-expansion-panel-content'),
)!.nativeElement;
fixture.detectChanges();
expect(content.textContent.trim())
.withContext('Expected content element to be empty.')
.toBe('');
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(content.textContent.trim())
.withContext('Expected content to be rendered.')
.toContain('Some content');
});
it('should render the content for a lazy-loaded panel that is opened on init', () => {
const fixture = TestBed.createComponent(LazyPanelOpenOnLoad);
const content = fixture.debugElement.query(
By.css('.mat-expansion-panel-content'),
)!.nativeElement;
fixture.detectChanges();
expect(content.textContent.trim())
.withContext('Expected content to be rendered.')
.toContain('Some content');
});
it('should not render lazy content from a child panel inside the parent', () => {
const fixture = TestBed.createComponent(NestedLazyPanelWithContent);
fixture.componentInstance.parentExpanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const parentContent: HTMLElement = fixture.nativeElement.querySelector(
'.parent-panel .mat-expansion-panel-content',
);
const childContent: HTMLElement = fixture.nativeElement.querySelector(
'.child-panel .mat-expansion-panel-content',
);
expect(parentContent.textContent!.trim()).toBe(
'Parent content',
'Expected only parent content to be rendered.',
);
expect(childContent.textContent!.trim()).toBe(
'',
'Expected child content element to be empty.',
);
fixture.componentInstance.childExpanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(childContent.textContent!.trim()).toBe(
'Child content',
'Expected child content element to be rendered.',
);
});
it('emit correct events for change in panel expanded state', () => {
const fixture = TestBed.createComponent(PanelWithContent);
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.openCallback).toHaveBeenCalled();
fixture.componentInstance.expanded = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.closeCallback).toHaveBeenCalled();
});
it('should create a unique panel id for each panel', () => {
const fixtureOne = TestBed.createComponent(PanelWithContent);
const headerElOne = fixtureOne.nativeElement.querySelector('.mat-expansion-panel-header');
const fixtureTwo = TestBed.createComponent(PanelWithContent);
const headerElTwo = fixtureTwo.nativeElement.querySelector('.mat-expansion-panel-header');
fixtureOne.detectChanges();
fixtureTwo.detectChanges();
const panelIdOne = headerElOne.getAttribute('aria-controls');
const panelIdTwo = headerElTwo.getAttribute('aria-controls');
expect(panelIdOne).not.toBe(panelIdTwo);
});
it('should set `aria-labelledby` of the content to the header id', () => {
const fixture = TestBed.createComponent(PanelWithContent);
const headerEl = fixture.nativeElement.querySelector('.mat-expansion-panel-header');
const contentEl = fixture.nativeElement.querySelector('.mat-expansion-panel-content');
fixture.detectChanges();
const headerId = headerEl.getAttribute('id');
const contentLabel = contentEl.getAttribute('aria-labelledby');
expect(headerId).toBeTruthy();
expect(contentLabel).toBeTruthy();
expect(headerId).toBe(contentLabel);
});
it('should set the proper role on the content element', () => {
const fixture = TestBed.createComponent(PanelWithContent);
const contentEl = fixture.nativeElement.querySelector('.mat-expansion-panel-content');
expect(contentEl.getAttribute('role')).toBe('region');
});
it('should toggle the panel when pressing SPACE on the header', () => {
const fixture = TestBed.createComponent(PanelWithContent);
fixture.detectChanges();
const headerEl = fixture.nativeElement.querySelector('.mat-expansion-panel-header');
spyOn(fixture.componentInstance.panel, 'toggle');
const event = dispatchKeyboardEvent(headerEl, 'keydown', SPACE);
fixture.detectChanges();
expect(fixture.componentInstance.panel.toggle).toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
});
it('should toggle the panel when pressing ENTER on the header', () => {
const fixture = TestBed.createComponent(PanelWithContent);
fixture.detectChanges();
const headerEl = fixture.nativeElement.querySelector('.mat-expansion-panel-header');
spyOn(fixture.componentInstance.panel, 'toggle');
const event = dispatchKeyboardEvent(headerEl, 'keydown', ENTER);
fixture.detectChanges();
expect(fixture.componentInstance.panel.toggle).toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
});
it('should not toggle if a modifier key is pressed', () => {
const fixture = TestBed.createComponent(PanelWithContent);
fixture.detectChanges();
const headerEl = fixture.nativeElement.querySelector('.mat-expansion-panel-header');
spyOn(fixture.componentInstance.panel, 'toggle');
['altKey', 'metaKey', 'shiftKey', 'ctrlKey'].forEach(modifier => {
const event = createKeyboardEvent('keydown', ENTER);
Object.defineProperty(event, modifier, {get: () => true});
dispatchEvent(headerEl, event);
fixture.detectChanges();
expect(fixture.componentInstance.panel.toggle).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(false);
});
});
it('should not be able to focus content while closed', fakeAsync(() => {
const fixture = TestBed.createComponent(PanelWithContent);
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick(250);
const button = fixture.debugElement.query(By.css('button'))!.nativeElement;
button.focus();
expect(document.activeElement)
.withContext('Expected button to start off focusable.')
.toBe(button);
button.blur();
fixture.componentInstance.expanded = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick(250);
// Enforce a style recalculation as otherwise browsers like Safari on iOS 14 require
// us to wait until the next tick using actual async/await. Not retrieving the computed
// styles would result in the `visibility: hidden` on the expansion content to not apply.
getComputedStyle(button).getPropertyValue('visibility');
button.focus();
expect(document.activeElement)
.not.withContext('Expected button to no longer be focusable.')
.toBe(button);
}));
it('should restore focus to header if focused element is inside panel on close', fakeAsync(() => {
const fixture = TestBed.createComponent(PanelWithContent);
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick(250);
const button = fixture.debugElement.query(By.css('button'))!.nativeElement;
const header = fixture.debugElement.query(By.css('mat-expansion-panel-header'))!.nativeElement;
button.focus();
expect(document.activeElement)
.withContext('Expected button to start off focusable.')
.toBe(button);
fixture.componentInstance.expanded = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick(250);
expect(document.activeElement).withContext('Expected header to be focused.').toBe(header);
}));
it('should not change focus origin if origin not specified', fakeAsync(() => {
const fixture = TestBed.createComponent(PanelWithContent);
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick(250);
const header = fixture.debugElement.query(By.css('mat-expansion-panel-header'))!;
const headerInstance = header.componentInstance;
headerInstance.focus('mouse');
headerInstance.focus();
fixture.detectChanges();
tick(250);
expect(header.nativeElement.classList).toContain('cdk-focused');
expect(header.nativeElement.classList).toContain('cdk-mouse-focused');
})); | {
"end_byte": 10531,
"start_byte": 593,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion.spec.ts"
} |
components/src/material/expansion/expansion.spec.ts_10535_20734 | it('should not override the panel margin if it is not inside an accordion', fakeAsync(() => {
const fixture = TestBed.createComponent(PanelWithCustomMargin);
fixture.detectChanges();
const panel = fixture.debugElement.query(By.css('mat-expansion-panel'))!;
let styles = getComputedStyle(panel.nativeElement);
expect(panel.componentInstance._hasSpacing()).toBe(false);
expect(styles.marginTop).toBe('13px');
expect(styles.marginBottom).toBe('13px');
expect(styles.marginLeft).toBe('37px');
expect(styles.marginRight).toBe('37px');
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick(250);
styles = getComputedStyle(panel.nativeElement);
expect(panel.componentInstance._hasSpacing()).toBe(false);
expect(styles.marginTop).toBe('13px');
expect(styles.marginBottom).toBe('13px');
expect(styles.marginLeft).toBe('37px');
expect(styles.marginRight).toBe('37px');
}));
it('should be able to hide the toggle', () => {
const fixture = TestBed.createComponent(PanelWithContent);
const header = fixture.debugElement.query(By.css('.mat-expansion-panel-header'))!.nativeElement;
const content = fixture.debugElement.query(By.css('.mat-content'))!.nativeElement;
fixture.detectChanges();
expect(header.querySelector('.mat-expansion-indicator'))
.withContext('Expected indicator to be shown.')
.toBeTruthy();
expect(content.classList).not.toContain('mat-content-hide-toggle');
fixture.componentInstance.hideToggle = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(header.querySelector('.mat-expansion-indicator'))
.withContext('Expected indicator to be hidden.')
.toBeFalsy();
expect(content.classList).toContain('mat-content-hide-toggle');
});
it('should update the indicator rotation when the expanded state is toggled programmatically', fakeAsync(() => {
const fixture = TestBed.createComponent(PanelWithContent);
fixture.detectChanges();
tick(250);
const arrow = fixture.debugElement.query(By.css('.mat-expansion-indicator'))!.nativeElement;
expect(arrow.style.transform).withContext('Expected no rotation.').toBe('rotate(0deg)');
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick(250);
expect(arrow.style.transform)
.withContext('Expected 180 degree rotation.')
.toBe('rotate(180deg)');
}));
it('should make sure accordion item runs ngOnDestroy when expansion panel is destroyed', () => {
const fixture = TestBed.createComponent(PanelWithContentInNgIf);
fixture.detectChanges();
let destroyedOk = false;
fixture.componentInstance.panel.destroyed.subscribe(() => (destroyedOk = true));
fixture.componentInstance.expansionShown = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(destroyedOk).toBe(true);
});
it('should support two-way binding of the `expanded` property', () => {
const fixture = TestBed.createComponent(PanelWithTwoWayBinding);
const header = fixture.debugElement.query(By.css('mat-expansion-panel-header'))!.nativeElement;
fixture.detectChanges();
expect(fixture.componentInstance.expanded).toBe(false);
header.click();
fixture.detectChanges();
expect(fixture.componentInstance.expanded).toBe(true);
header.click();
fixture.detectChanges();
expect(fixture.componentInstance.expanded).toBe(false);
});
it('should emit events for body expanding and collapsing animations', fakeAsync(() => {
const fixture = TestBed.createComponent(PanelWithContent);
fixture.detectChanges();
let afterExpand = 0;
let afterCollapse = 0;
fixture.componentInstance.panel.afterExpand.subscribe(() => afterExpand++);
fixture.componentInstance.panel.afterCollapse.subscribe(() => afterCollapse++);
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(afterExpand).toBe(1);
expect(afterCollapse).toBe(0);
fixture.componentInstance.expanded = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(afterExpand).toBe(1);
expect(afterCollapse).toBe(1);
}));
it('should be able to set the default options through the injection token', () => {
TestBed.resetTestingModule().configureTestingModule({
imports: [MatExpansionModule, NoopAnimationsModule],
providers: [
{
provide: MAT_EXPANSION_PANEL_DEFAULT_OPTIONS,
useValue: {
hideToggle: true,
expandedHeight: '10px',
collapsedHeight: '16px',
},
},
],
});
const fixture = TestBed.createComponent(PanelWithTwoWayBinding);
fixture.detectChanges();
const panel = fixture.debugElement.query(By.directive(MatExpansionPanel))!;
const header = fixture.debugElement.query(By.directive(MatExpansionPanelHeader))!;
expect(panel.componentInstance.hideToggle).toBe(true);
expect(header.componentInstance.expandedHeight).toBe('10px');
expect(header.componentInstance.collapsedHeight).toBe('16px');
expect(header.nativeElement.style.height).toBe('16px');
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(header.nativeElement.style.height).toBe('10px');
});
it('should be able to set a custom tabindex on the header', () => {
const fixture = TestBed.createComponent(PanelWithHeaderTabindex);
const headerEl = fixture.nativeElement.querySelector('.mat-expansion-panel-header');
fixture.detectChanges();
expect(headerEl.getAttribute('tabindex')).toBe('7');
});
describe('disabled state', () => {
let fixture: ComponentFixture<PanelWithContent>;
let panel: HTMLElement;
let header: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(PanelWithContent);
fixture.detectChanges();
panel = fixture.debugElement.query(By.css('mat-expansion-panel'))!.nativeElement;
header = fixture.debugElement.query(By.css('mat-expansion-panel-header'))!.nativeElement;
});
it('should toggle the aria-disabled attribute on the header', () => {
expect(header.getAttribute('aria-disabled')).toBe('false');
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(header.getAttribute('aria-disabled')).toBe('true');
});
it('should toggle the expansion indicator', () => {
expect(panel.querySelector('.mat-expansion-indicator')).toBeTruthy();
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(panel.querySelector('.mat-expansion-indicator')).toBeFalsy();
});
it('should not be able to toggle the panel via a user action if disabled', () => {
expect(fixture.componentInstance.panel.expanded).toBe(false);
expect(header.classList).not.toContain('mat-expanded');
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
header.click();
fixture.detectChanges();
expect(fixture.componentInstance.panel.expanded).toBe(false);
expect(header.classList).not.toContain('mat-expanded');
});
it('should be able to toggle a disabled expansion panel programmatically', () => {
expect(fixture.componentInstance.panel.expanded).toBe(false);
expect(header.classList).not.toContain('mat-expanded');
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.expanded = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.panel.expanded).toBe(true);
expect(header.classList).toContain('mat-expanded');
});
it(
'should be able to toggle a disabled expansion panel programmatically via the ' +
'open/close methods',
() => {
const panelInstance = fixture.componentInstance.panel;
expect(panelInstance.expanded).toBe(false);
expect(header.classList).not.toContain('mat-expanded');
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
panelInstance.open();
fixture.detectChanges();
expect(panelInstance.expanded).toBe(true);
expect(header.classList).toContain('mat-expanded');
panelInstance.close();
fixture.detectChanges();
expect(panelInstance.expanded).toBe(false);
expect(header.classList).not.toContain('mat-expanded');
},
);
it(
'should be able to toggle a disabled expansion panel programmatically via the ' +
'toggle method',
() => {
const panelInstance = fixture.componentInstance.panel;
expect(panelInstance.expanded).toBe(false);
expect(header.classList).not.toContain('mat-expanded');
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
panelInstance.toggle();
fixture.detectChanges();
expect(panelInstance.expanded).toBe(true);
expect(header.classList).toContain('mat-expanded');
panelInstance.toggle();
fixture.detectChanges();
expect(panelInstance.expanded).toBe(false);
expect(header.classList).not.toContain('mat-expanded');
},
);
it('should update the tabindex if the header becomes disabled', () => {
expect(header.getAttribute('tabindex')).toBe('0');
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(header.getAttribute('tabindex')).toBe('-1');
});
});
}); | {
"end_byte": 20734,
"start_byte": 10535,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion.spec.ts"
} |
components/src/material/expansion/expansion.spec.ts_20736_24078 | @Component({
template: `
<mat-expansion-panel [expanded]="expanded"
[hideToggle]="hideToggle"
[disabled]="disabled"
(opened)="openCallback()"
(closed)="closeCallback()">
<mat-expansion-panel-header>Panel Title</mat-expansion-panel-header>
<p>Some content</p>
<button>I am a button</button>
</mat-expansion-panel>`,
standalone: true,
imports: [MatExpansionModule],
})
class PanelWithContent {
expanded = false;
hideToggle = false;
disabled = false;
openCallback = jasmine.createSpy('openCallback');
closeCallback = jasmine.createSpy('closeCallback');
@ViewChild(MatExpansionPanel) panel: MatExpansionPanel;
}
@Component({
template: `
@if (expansionShown) {
<div>
<mat-expansion-panel>
<mat-expansion-panel-header>Panel Title</mat-expansion-panel-header>
</mat-expansion-panel>
</div>
}
`,
standalone: true,
imports: [MatExpansionModule],
})
class PanelWithContentInNgIf {
expansionShown = true;
@ViewChild(MatExpansionPanel) panel: MatExpansionPanel;
}
@Component({
styles: `mat-expansion-panel {
margin: 13px 37px;
}`,
template: `
<mat-expansion-panel [expanded]="expanded">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores officia, aliquam dicta
corrupti maxime voluptate accusamus impedit atque incidunt pariatur.
</mat-expansion-panel>`,
standalone: true,
imports: [MatExpansionModule],
})
class PanelWithCustomMargin {
expanded = false;
}
@Component({
template: `
<mat-expansion-panel [expanded]="expanded">
<mat-expansion-panel-header>Panel Title</mat-expansion-panel-header>
<ng-template matExpansionPanelContent>
<p>Some content</p>
<button>I am a button</button>
</ng-template>
</mat-expansion-panel>`,
standalone: true,
imports: [MatExpansionModule],
})
class LazyPanelWithContent {
expanded = false;
}
@Component({
template: `
<mat-expansion-panel [expanded]="true">
<mat-expansion-panel-header>Panel Title</mat-expansion-panel-header>
<ng-template matExpansionPanelContent>
<p>Some content</p>
</ng-template>
</mat-expansion-panel>`,
standalone: true,
imports: [MatExpansionModule],
})
class LazyPanelOpenOnLoad {}
@Component({
template: `
<mat-expansion-panel [(expanded)]="expanded">
<mat-expansion-panel-header>Panel Title</mat-expansion-panel-header>
</mat-expansion-panel>`,
standalone: true,
imports: [MatExpansionModule],
})
class PanelWithTwoWayBinding {
expanded = false;
}
@Component({
template: `
<mat-expansion-panel>
<mat-expansion-panel-header tabindex="7">Panel Title</mat-expansion-panel-header>
</mat-expansion-panel>`,
standalone: true,
imports: [MatExpansionModule],
})
class PanelWithHeaderTabindex {}
@Component({
template: `
<mat-expansion-panel class="parent-panel" [expanded]="parentExpanded">
Parent content
<mat-expansion-panel class="child-panel" [expanded]="childExpanded">
<ng-template matExpansionPanelContent>Child content</ng-template>
</mat-expansion-panel>
</mat-expansion-panel>
`,
standalone: true,
imports: [MatExpansionModule],
})
class NestedLazyPanelWithContent {
parentExpanded = false;
childExpanded = false;
} | {
"end_byte": 24078,
"start_byte": 20736,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion.spec.ts"
} |
components/src/material/expansion/expansion-module.ts_0_1267 | /**
* @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 {CdkAccordionModule} from '@angular/cdk/accordion';
import {PortalModule} from '@angular/cdk/portal';
import {NgModule} from '@angular/core';
import {MatCommonModule} from '@angular/material/core';
import {MatAccordion} from './accordion';
import {MatExpansionPanel, MatExpansionPanelActionRow} from './expansion-panel';
import {MatExpansionPanelContent} from './expansion-panel-content';
import {
MatExpansionPanelDescription,
MatExpansionPanelHeader,
MatExpansionPanelTitle,
} from './expansion-panel-header';
@NgModule({
imports: [
MatCommonModule,
CdkAccordionModule,
PortalModule,
MatAccordion,
MatExpansionPanel,
MatExpansionPanelActionRow,
MatExpansionPanelHeader,
MatExpansionPanelTitle,
MatExpansionPanelDescription,
MatExpansionPanelContent,
],
exports: [
MatAccordion,
MatExpansionPanel,
MatExpansionPanelActionRow,
MatExpansionPanelHeader,
MatExpansionPanelTitle,
MatExpansionPanelDescription,
MatExpansionPanelContent,
],
})
export class MatExpansionModule {}
| {
"end_byte": 1267,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion-module.ts"
} |
components/src/material/expansion/_expansion-theme.scss_0_3257 | @use 'sass:map';
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/style/sass-utils';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/expansion' as tokens-mat-expansion;
@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-expansion.$prefix,
tokens-mat-expansion.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-expansion.$prefix,
tokens-mat-expansion.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 {
// TODO(mmalerba): Stop calling this and resolve resulting screen diffs.
$theme: inspection.private-get-typography-back-compat-theme($theme);
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-expansion.$prefix,
tokens-mat-expansion.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-mat-expansion.$prefix,
tokens-mat-expansion.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-expansion.$prefix,
tokens: tokens-mat-expansion.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-expansion') {
@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-expansion.$prefix,
map.get($tokens, tokens-mat-expansion.$prefix)
);
}
}
| {
"end_byte": 3257,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/_expansion-theme.scss"
} |
components/src/material/expansion/expansion-panel-header.html_0_555 | <span class="mat-content" [class.mat-content-hide-toggle]="!_showToggle()">
<ng-content select="mat-panel-title"></ng-content>
<ng-content select="mat-panel-description"></ng-content>
<ng-content></ng-content>
</span>
@if (_showToggle()) {
<span [@indicatorRotate]="_getExpandedState()" class="mat-expansion-indicator">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 -960 960 960"
aria-hidden="true"
focusable="false">
<path d="M480-345 240-585l56-56 184 184 184-184 56 56-240 240Z"/>
</svg>
</span>
}
| {
"end_byte": 555,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion-panel-header.html"
} |
components/src/material/expansion/BUILD.bazel_0_1898 | 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 = "expansion",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = glob(["**/*.html"]) + [
":expansion-panel.css",
":expansion-panel-header.css",
],
deps = [
"//src/cdk/a11y",
"//src/cdk/accordion",
"//src/cdk/collections",
"//src/cdk/keycodes",
"//src/cdk/portal",
"//src/material/core",
"@npm//@angular/animations",
"@npm//@angular/core",
"@npm//@angular/platform-browser",
"@npm//rxjs",
],
)
sass_library(
name = "expansion_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = ["//src/material/core:core_scss_lib"],
)
sass_binary(
name = "expansion_panel_scss",
src = "expansion-panel.scss",
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "expansion_panel_header_scss",
src = "expansion-panel-header.scss",
deps = [
":expansion_scss_lib",
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":expansion",
"//src/cdk/a11y",
"//src/cdk/keycodes",
"//src/cdk/testing/private",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [":expansion.md"],
)
extract_tokens(
name = "tokens",
srcs = [":expansion_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1898,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/BUILD.bazel"
} |
components/src/material/expansion/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';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/index.ts"
} |
components/src/material/expansion/expansion-panel.html_0_540 | <ng-content select="mat-expansion-panel-header"></ng-content>
<div class="mat-expansion-panel-content"
role="region"
[@bodyExpansion]="_getExpandedState()"
(@bodyExpansion.start)="_animationStarted($event)"
(@bodyExpansion.done)="_animationDone($event)"
[attr.aria-labelledby]="_headerId"
[id]="id"
#body>
<div class="mat-expansion-panel-body">
<ng-content></ng-content>
<ng-template [cdkPortalOutlet]="_portal"></ng-template>
</div>
<ng-content select="mat-action-row"></ng-content>
</div>
| {
"end_byte": 540,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion-panel.html"
} |
components/src/material/expansion/expansion-panel-content.ts_0_772 | /**
* @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 {Directive, TemplateRef, inject} from '@angular/core';
import {MAT_EXPANSION_PANEL, MatExpansionPanelBase} from './expansion-panel-base';
/**
* Expansion panel content that will be rendered lazily
* after the panel is opened for the first time.
*/
@Directive({
selector: 'ng-template[matExpansionPanelContent]',
})
export class MatExpansionPanelContent {
_template = inject<TemplateRef<any>>(TemplateRef);
_expansionPanel = inject<MatExpansionPanelBase>(MAT_EXPANSION_PANEL, {optional: true});
constructor(...args: unknown[]);
constructor() {}
}
| {
"end_byte": 772,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion-panel-content.ts"
} |
components/src/material/expansion/expansion-panel.scss_1_3835 | @use '@angular/cdk';
@use '../core/tokens/m2/mat/expansion' as tokens-mat-expansion;
@use '../core/tokens/token-utils';
@use '../core/style/variables';
@use '../core/style/elevation';
.mat-expansion-panel {
box-sizing: content-box;
display: block;
margin: 0;
overflow: hidden;
transition: margin 225ms variables.$fast-out-slow-in-timing-function,
elevation.private-transition-property-value();
// Required so that the `box-shadow` works after the
// focus indicator relatively positions the header.
position: relative;
@include token-utils.use-tokens(
tokens-mat-expansion.$prefix, tokens-mat-expansion.get-token-slots()) {
@include token-utils.create-token-slot(background, container-background-color);
@include token-utils.create-token-slot(color, container-text-color);
@include token-utils.create-token-slot(border-radius, container-shape);
}
@include elevation.overridable-elevation(2);
.mat-accordion & {
&:not(.mat-expanded), &:not(.mat-expansion-panel-spacing) {
border-radius: 0;
}
@include token-utils.use-tokens(
tokens-mat-expansion.$prefix, tokens-mat-expansion.get-token-slots()) {
&:first-of-type {
@include token-utils.create-token-slot(border-top-right-radius, container-shape);
@include token-utils.create-token-slot(border-top-left-radius, container-shape);
}
&:last-of-type {
@include token-utils.create-token-slot(border-bottom-right-radius, container-shape);
@include token-utils.create-token-slot(border-bottom-left-radius, container-shape);
}
}
}
@include cdk.high-contrast {
outline: solid 1px;
}
&.ng-animate-disabled,
.ng-animate-disabled &,
&._mat-animation-noopable {
transition: none;
}
}
.mat-expansion-panel-content {
display: flex;
flex-direction: column;
overflow: visible;
@include token-utils.use-tokens(
tokens-mat-expansion.$prefix, tokens-mat-expansion.get-token-slots()) {
@include token-utils.create-token-slot(font-family, container-text-font);
@include token-utils.create-token-slot(font-size, container-text-size);
@include token-utils.create-token-slot(font-weight, container-text-weight);
@include token-utils.create-token-slot(line-height, container-text-line-height);
@include token-utils.create-token-slot(letter-spacing, container-text-tracking);
}
// Usually the `visibility: hidden` added by the animation is enough to prevent focus from
// entering the collapsed content, but children with their own `visibility` can override it.
// In other components we set a `display: none` at the root to stop focus from reaching the
// elements, however we can't do that here, because the content can determine the width
// of an expansion panel. The most practical fallback is to use `!important` to override
// any custom visibility.
&[style*='visibility: hidden'] * {
visibility: hidden !important;
}
}
.mat-expansion-panel-body {
padding: 0 24px 16px;
}
.mat-expansion-panel-spacing {
margin: 16px 0;
.mat-accordion > &:first-child,
.mat-accordion > *:first-child:not(.mat-expansion-panel) & {
margin-top: 0;
}
.mat-accordion > &:last-child,
.mat-accordion > *:last-child:not(.mat-expansion-panel) & {
margin-bottom: 0;
}
}
.mat-action-row {
border-top-style: solid;
border-top-width: 1px;
display: flex;
flex-direction: row;
justify-content: flex-end;
padding: 16px 8px 16px 24px;
@include token-utils.use-tokens(
tokens-mat-expansion.$prefix, tokens-mat-expansion.get-token-slots()) {
@include token-utils.create-token-slot(border-top-color, actions-divider-color);
}
.mat-button-base, .mat-mdc-button-base {
margin-left: 8px;
[dir='rtl'] & {
margin-left: 0;
margin-right: 8px;
}
}
}
| {
"end_byte": 3835,
"start_byte": 1,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion-panel.scss"
} |
components/src/material/expansion/expansion-animations.ts_0_2894 | /**
* @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,
AnimationTriggerMetadata,
state,
style,
transition,
trigger,
} from '@angular/animations';
/** Time and timing curve for expansion panel animations. */
// Note: Keep this in sync with the Sass variable for the panel header animation.
export const EXPANSION_PANEL_ANIMATION_TIMING = '225ms cubic-bezier(0.4,0.0,0.2,1)';
/**
* Animations used by the Material expansion panel.
*
* A bug in angular animation's `state` when ViewContainers are moved using ViewContainerRef.move()
* causes the animation state of moved components to become `void` upon exit, and not update again
* upon reentry into the DOM. This can lead a to situation for the expansion panel where the state
* of the panel is `expanded` or `collapsed` but the animation state is `void`.
*
* To correctly handle animating to the next state, we animate between `void` and `collapsed` which
* are defined to have the same styles. Since angular animates from the current styles to the
* destination state's style definition, in situations where we are moving from `void`'s styles to
* `collapsed` this acts a noop since no style values change.
*
* In the case where angular's animation state is out of sync with the expansion panel's state, the
* expansion panel being `expanded` and angular animations being `void`, the animation from the
* `expanded`'s effective styles (though in a `void` animation state) to the collapsed state will
* occur as expected.
*
* Angular Bug: https://github.com/angular/angular/issues/18847
*
* @docs-private
*/
export const matExpansionAnimations: {
readonly indicatorRotate: AnimationTriggerMetadata;
readonly bodyExpansion: AnimationTriggerMetadata;
} = {
/** Animation that rotates the indicator arrow. */
indicatorRotate: trigger('indicatorRotate', [
state('collapsed, void', style({transform: 'rotate(0deg)'})),
state('expanded', style({transform: 'rotate(180deg)'})),
transition(
'expanded <=> collapsed, void => collapsed',
animate(EXPANSION_PANEL_ANIMATION_TIMING),
),
]),
/** Animation that expands and collapses the panel content. */
bodyExpansion: trigger('bodyExpansion', [
state('collapsed, void', style({height: '0px', visibility: 'hidden'})),
// Clear the `visibility` while open, otherwise the content will be visible when placed in
// a parent that's `visibility: hidden`, because `visibility` doesn't apply to descendants
// that have a `visibility` of their own (see #27436).
state('expanded', style({height: '*', visibility: ''})),
transition(
'expanded <=> collapsed, void => collapsed',
animate(EXPANSION_PANEL_ANIMATION_TIMING),
),
]),
};
| {
"end_byte": 2894,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion-animations.ts"
} |
components/src/material/expansion/expansion-panel.ts_0_8645 | /**
* @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 {CdkAccordionItem} from '@angular/cdk/accordion';
import {UniqueSelectionDispatcher} from '@angular/cdk/collections';
import {CdkPortalOutlet, TemplatePortal} from '@angular/cdk/portal';
import {DOCUMENT} from '@angular/common';
import {
AfterContentInit,
ChangeDetectionStrategy,
Component,
ContentChild,
Directive,
ElementRef,
EventEmitter,
InjectionToken,
Input,
OnChanges,
OnDestroy,
Output,
SimpleChanges,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
booleanAttribute,
ANIMATION_MODULE_TYPE,
inject,
} from '@angular/core';
import {Subject} from 'rxjs';
import {filter, startWith, take} from 'rxjs/operators';
import {MatAccordionBase, MatAccordionTogglePosition, MAT_ACCORDION} from './accordion-base';
import {matExpansionAnimations} from './expansion-animations';
import {MAT_EXPANSION_PANEL} from './expansion-panel-base';
import {MatExpansionPanelContent} from './expansion-panel-content';
/** MatExpansionPanel's states. */
export type MatExpansionPanelState = 'expanded' | 'collapsed';
/** Counter for generating unique element ids. */
let uniqueId = 0;
/**
* Object that can be used to override the default options
* for all of the expansion panels in a module.
*/
export interface MatExpansionPanelDefaultOptions {
/** Height of the header while the panel is expanded. */
expandedHeight: string;
/** Height of the header while the panel is collapsed. */
collapsedHeight: string;
/** Whether the toggle indicator should be hidden. */
hideToggle: boolean;
}
/**
* Injection token that can be used to configure the default
* options for the expansion panel component.
*/
export const MAT_EXPANSION_PANEL_DEFAULT_OPTIONS =
new InjectionToken<MatExpansionPanelDefaultOptions>('MAT_EXPANSION_PANEL_DEFAULT_OPTIONS');
/**
* This component can be used as a single element to show expandable content, or as one of
* multiple children of an element with the MatAccordion directive attached.
*/
@Component({
styleUrl: 'expansion-panel.css',
selector: 'mat-expansion-panel',
exportAs: 'matExpansionPanel',
templateUrl: 'expansion-panel.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
animations: [matExpansionAnimations.bodyExpansion],
providers: [
// Provide MatAccordion as undefined to prevent nested expansion panels from registering
// to the same accordion.
{provide: MAT_ACCORDION, useValue: undefined},
{provide: MAT_EXPANSION_PANEL, useExisting: MatExpansionPanel},
],
host: {
'class': 'mat-expansion-panel',
'[class.mat-expanded]': 'expanded',
'[class._mat-animation-noopable]': '_animationsDisabled',
'[class.mat-expansion-panel-spacing]': '_hasSpacing()',
},
imports: [CdkPortalOutlet],
})
export class MatExpansionPanel
extends CdkAccordionItem
implements AfterContentInit, OnChanges, OnDestroy
{
private _viewContainerRef = inject(ViewContainerRef);
_animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
protected _animationsDisabled: boolean;
private _document = inject(DOCUMENT);
/** Whether the toggle indicator should be hidden. */
@Input({transform: booleanAttribute})
get hideToggle(): boolean {
return this._hideToggle || (this.accordion && this.accordion.hideToggle);
}
set hideToggle(value: boolean) {
this._hideToggle = value;
}
private _hideToggle = false;
/** The position of the expansion indicator. */
@Input()
get togglePosition(): MatAccordionTogglePosition {
return this._togglePosition || (this.accordion && this.accordion.togglePosition);
}
set togglePosition(value: MatAccordionTogglePosition) {
this._togglePosition = value;
}
private _togglePosition: MatAccordionTogglePosition;
/** An event emitted after the body's expansion animation happens. */
@Output() readonly afterExpand = new EventEmitter<void>();
/** An event emitted after the body's collapse animation happens. */
@Output() readonly afterCollapse = new EventEmitter<void>();
/** Stream that emits for changes in `@Input` properties. */
readonly _inputChanges = new Subject<SimpleChanges>();
/** Optionally defined accordion the expansion panel belongs to. */
override accordion = inject<MatAccordionBase>(MAT_ACCORDION, {optional: true, skipSelf: true})!;
/** Content that will be rendered lazily. */
@ContentChild(MatExpansionPanelContent) _lazyContent: MatExpansionPanelContent;
/** Element containing the panel's user-provided content. */
@ViewChild('body') _body: ElementRef<HTMLElement>;
/** Portal holding the user's content. */
_portal: TemplatePortal;
/** ID for the associated header element. Used for a11y labelling. */
_headerId = `mat-expansion-panel-header-${uniqueId++}`;
constructor(...args: unknown[]);
constructor() {
super();
const defaultOptions = inject<MatExpansionPanelDefaultOptions>(
MAT_EXPANSION_PANEL_DEFAULT_OPTIONS,
{optional: true},
);
this._expansionDispatcher = inject(UniqueSelectionDispatcher);
this._animationsDisabled = this._animationMode === 'NoopAnimations';
if (defaultOptions) {
this.hideToggle = defaultOptions.hideToggle;
}
}
/** Determines whether the expansion panel should have spacing between it and its siblings. */
_hasSpacing(): boolean {
if (this.accordion) {
return this.expanded && this.accordion.displayMode === 'default';
}
return false;
}
/** Gets the expanded state string. */
_getExpandedState(): MatExpansionPanelState {
return this.expanded ? 'expanded' : 'collapsed';
}
/** Toggles the expanded state of the expansion panel. */
override toggle(): void {
this.expanded = !this.expanded;
}
/** Sets the expanded state of the expansion panel to false. */
override close(): void {
this.expanded = false;
}
/** Sets the expanded state of the expansion panel to true. */
override open(): void {
this.expanded = true;
}
ngAfterContentInit() {
if (this._lazyContent && this._lazyContent._expansionPanel === this) {
// Render the content as soon as the panel becomes open.
this.opened
.pipe(
startWith(null),
filter(() => this.expanded && !this._portal),
take(1),
)
.subscribe(() => {
this._portal = new TemplatePortal(this._lazyContent._template, this._viewContainerRef);
});
}
}
ngOnChanges(changes: SimpleChanges) {
this._inputChanges.next(changes);
}
override ngOnDestroy() {
super.ngOnDestroy();
this._inputChanges.complete();
}
/** Checks whether the expansion panel's content contains the currently-focused element. */
_containsFocus(): boolean {
if (this._body) {
const focusedElement = this._document.activeElement;
const bodyElement = this._body.nativeElement;
return focusedElement === bodyElement || bodyElement.contains(focusedElement);
}
return false;
}
/** Called when the expansion animation has started. */
protected _animationStarted(event: AnimationEvent) {
if (!isInitialAnimation(event) && !this._animationsDisabled && this._body) {
// Prevent the user from tabbing into the content while it's animating.
// TODO(crisbeto): maybe use `inert` to prevent focus from entering while closed as well
// instead of `visibility`? Will allow us to clean up some code but needs more testing.
this._body?.nativeElement.setAttribute('inert', '');
}
}
/** Called when the expansion animation has finished. */
protected _animationDone(event: AnimationEvent) {
if (!isInitialAnimation(event)) {
if (event.toState === 'expanded') {
this.afterExpand.emit();
} else if (event.toState === 'collapsed') {
this.afterCollapse.emit();
}
// Re-enable tabbing once the animation is finished.
if (!this._animationsDisabled && this._body) {
this._body.nativeElement.removeAttribute('inert');
}
}
}
}
/** Checks whether an animation is the initial setup animation. */
function isInitialAnimation(event: AnimationEvent): boolean {
return event.fromState === 'void';
}
/**
* Actions of a `<mat-expansion-panel>`.
*/
@Directive({
selector: 'mat-action-row',
host: {
class: 'mat-action-row',
},
})
export class MatExpansionPanelActionRow {}
| {
"end_byte": 8645,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/expansion-panel.ts"
} |
components/src/material/expansion/testing/expansion-harness.spec.ts_0_543 | import {ComponentHarness, HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatAccordionTogglePosition, MatExpansionModule} from '@angular/material/expansion';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatAccordionHarness} from './accordion-harness';
import {MatExpansionPanelHarness} from './expansion-harness'; | {
"end_byte": 543,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/testing/expansion-harness.spec.ts"
} |
components/src/material/expansion/testing/expansion-harness.spec.ts_545_9236 | describe('MatExpansionHarness', () => {
let fixture: ComponentFixture<ExpansionHarnessTestComponent>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatExpansionModule, NoopAnimationsModule, ExpansionHarnessTestComponent],
});
fixture = TestBed.createComponent(ExpansionHarnessTestComponent);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should be able to load accordion', async () => {
const accordions = await loader.getAllHarnesses(MatAccordionHarness);
expect(accordions.length).toBe(2);
});
it('should be able to load an accordion by selector', async () => {
const accordions = await loader.getAllHarnesses(
MatAccordionHarness.with({selector: '#accordion2'}),
);
expect(accordions.length).toBe(1);
});
it('should be able to load expansion panels', async () => {
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(5);
});
it('should be able to load expansion panel by title matching regex', async () => {
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness.with({title: /Panel#2/}));
expect(panels.length).toBe(1);
expect(await panels[0].getTitle()).toBe('Title of Panel#2');
});
it('should be able to load expansion panel by title matching exact text', async () => {
const panels = await loader.getAllHarnesses(
MatExpansionPanelHarness.with({title: 'Standalone Panel Title'}),
);
expect(panels.length).toBe(1);
expect(await panels[0].getTitle()).toBe('Standalone Panel Title');
});
it('should be able to load expansion panel without title', async () => {
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness.with({title: null}));
expect(panels.length).toBe(1);
});
it('should be able to load expansion panel by description matching regex', async () => {
const panels = await loader.getAllHarnesses(
MatExpansionPanelHarness.with({description: /Panel#2/}),
);
expect(panels.length).toBe(1);
expect(await panels[0].getDescription()).toBe('Description of Panel#2');
});
it('should be able to load expansion panel by description matching exact text', async () => {
const panels = await loader.getAllHarnesses(
MatExpansionPanelHarness.with({description: 'Description of Panel#1'}),
);
expect(panels.length).toBe(1);
expect(await panels[0].getDescription()).toBe('Description of Panel#1');
});
it('should be able to load expansion panel without description', async () => {
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness.with({description: null}));
expect(panels.length).toBe(3);
});
it('should be able to load expanded panels', async () => {
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness.with({expanded: true}));
expect(panels.length).toBe(2);
expect(await panels[0].getTitle()).toBe('Title of Panel#2');
expect(await panels[1].getTitle()).toBe('Standalone Panel Title');
});
it('should be able to load collapsed panels', async () => {
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness.with({expanded: false}));
expect(panels.length).toBe(3);
expect(await panels[0].getTitle()).toBe('Title of Panel#1');
expect(await panels[1].getTextContent()).toBe('Accordion #2 - Content');
expect(await panels[2].getTitle()).toBe('Disabled Panel Title');
});
it('should be able to load expansion panel by content matching regex', async () => {
const panels = await loader.getAllHarnesses(
MatExpansionPanelHarness.with({content: /Accordion #2/}),
);
expect(panels.length).toBe(1);
expect(await panels[0].getTextContent()).toBe('Accordion #2 - Content');
});
it('should be able to load expansion panel by content matching exact string', async () => {
const panels = await loader.getAllHarnesses(
MatExpansionPanelHarness.with({content: 'Content of Panel#2'}),
);
expect(panels.length).toBe(1);
expect(await panels[0].getTextContent()).toBe('Content of Panel#2');
});
it('should be able to load expansion panels based on disabled state', async () => {
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness.with({disabled: true}));
expect(panels.length).toBe(1);
expect(await panels[0].getTitle()).toBe('Disabled Panel Title');
});
it('should be able to get expansion state of panel', async () => {
const panel = await loader.getHarness(MatExpansionPanelHarness.with({title: /Panel#1/}));
expect(await panel.isExpanded()).toBe(false);
fixture.componentInstance.panel1Expanded = true;
fixture.changeDetectorRef.markForCheck();
expect(await panel.isExpanded()).toBe(true);
});
it('should be able to get title of panel', async () => {
const panel = await loader.getHarness(MatExpansionPanelHarness.with({content: /Panel#1/}));
expect(await panel.getTitle()).toBe('Title of Panel#1');
fixture.componentInstance.panel1Title = 'new title';
fixture.changeDetectorRef.markForCheck();
expect(await panel.getTitle()).toBe('new title');
});
it('should be able to get description of panel', async () => {
const panel = await loader.getHarness(MatExpansionPanelHarness.with({content: /Panel#1/}));
expect(await panel.getDescription()).toBe('Description of Panel#1');
fixture.componentInstance.panel1Description = 'new description';
fixture.changeDetectorRef.markForCheck();
expect(await panel.getDescription()).toBe('new description');
});
it('should be able to get disabled state of panel', async () => {
const panel = await loader.getHarness(
MatExpansionPanelHarness.with({selector: '#disabledPanel'}),
);
expect(await panel.isDisabled()).toBe(true);
fixture.componentInstance.isDisabled = false;
fixture.changeDetectorRef.markForCheck();
expect(await panel.isDisabled()).toBe(false);
});
it('should be able to toggle expansion state of panel', async () => {
const panel = await loader.getHarness(MatExpansionPanelHarness);
expect(await panel.isExpanded()).toBe(false);
await panel.toggle();
expect(await panel.isExpanded()).toBe(true);
});
it('should be able to expand a panel', async () => {
const panel = await loader.getHarness(MatExpansionPanelHarness);
expect(await panel.isExpanded()).toBe(false);
await panel.expand();
expect(await panel.isExpanded()).toBe(true);
// checking a second time to ensure it does not modify
// the state if already expanded.
await panel.expand();
expect(await panel.isExpanded()).toBe(true);
});
it('should be able to collapse a panel', async () => {
const panel = await loader.getHarness(MatExpansionPanelHarness);
expect(await panel.isExpanded()).toBe(false);
await panel.expand();
expect(await panel.isExpanded()).toBe(true);
await panel.collapse();
expect(await panel.isExpanded()).toBe(false);
// checking a second time to ensure it does not modify
// the state if already collapsed.
await panel.collapse();
expect(await panel.isExpanded()).toBe(false);
});
it('should be able to get text content of expansion panel', async () => {
const panel = await loader.getHarness(MatExpansionPanelHarness);
expect(await panel.getTextContent()).toBe('Content of Panel#1');
fixture.componentInstance.panel1Content = 'new content';
fixture.changeDetectorRef.markForCheck();
expect(await panel.getTextContent()).toBe('new content');
});
it('should be able to get harness loader for content of panel', async () => {
const panel = await loader.getHarness(
MatExpansionPanelHarness.with({selector: '#standalonePanel'}),
);
const matchedHarnesses = await panel.getAllHarnesses(TestContentHarness);
expect(matchedHarnesses.length).toBe(1);
expect(await matchedHarnesses[0].getText()).toBe('Part of expansion panel');
});
it('should be able to focus expansion panel', async () => {
const panel = await loader.getHarness(MatExpansionPanelHarness);
expect(getActiveElementTag()).not.toBe('mat-expansion-panel-header');
await panel.focus();
expect(getActiveElementTag()).toBe('mat-expansion-panel-header');
});
it('should be able to blur expansion panel', async () => {
const panel = await loader.getHarness(MatExpansionPanelHarness);
await panel.focus();
expect(getActiveElementTag()).toBe('mat-expansion-panel-header');
await panel.blur();
expect(getActiveElementTag()).not.toBe('mat-expansion-panel-header');
}); | {
"end_byte": 9236,
"start_byte": 545,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/testing/expansion-harness.spec.ts"
} |
components/src/material/expansion/testing/expansion-harness.spec.ts_9240_14646 | it('should be able to check if expansion panel has toggle indicator', async () => {
const accordion = await loader.getHarness(MatAccordionHarness);
const standalonePanel = await loader.getHarness(
MatExpansionPanelHarness.with({selector: '#standalonePanel'}),
);
const expansionPanels = [standalonePanel, ...(await accordion.getExpansionPanels())];
let toggleIndicatorChecks = await parallel(() => {
return expansionPanels.map(p => p.hasToggleIndicator());
});
expect(toggleIndicatorChecks.every(s => s)).toBe(true);
fixture.componentInstance.hideToggleIndicators = true;
fixture.changeDetectorRef.markForCheck();
toggleIndicatorChecks = await parallel(() => expansionPanels.map(p => p.hasToggleIndicator()));
expect(toggleIndicatorChecks.every(s => !s)).toBe(true);
});
it('should be able to get toggle indicator position of panels', async () => {
const accordion = await loader.getHarness(MatAccordionHarness);
const standalonePanel = await loader.getHarness(
MatExpansionPanelHarness.with({selector: '#standalonePanel'}),
);
const expansionPanels = [standalonePanel, ...(await accordion.getExpansionPanels())];
let togglePositions = await parallel(() =>
expansionPanels.map(p => p.getToggleIndicatorPosition()),
);
expect(togglePositions.every(p => p === 'after')).toBe(true);
fixture.componentInstance.toggleIndicatorsPosition = 'before';
fixture.changeDetectorRef.markForCheck();
togglePositions = await parallel(() => {
return expansionPanels.map(p => p.getToggleIndicatorPosition());
});
expect(togglePositions.every(p => p === 'before')).toBe(true);
});
it('should be able to get expansion panels of accordion', async () => {
const accordion = await loader.getHarness(MatAccordionHarness);
const panels = await accordion.getExpansionPanels();
expect(panels.length).toBe(2);
expect(await panels[0].getTitle()).toBe('Title of Panel#1');
expect(await panels[1].getTitle()).toBe('Title of Panel#2');
});
it('should be able to get expansion panels of accordion with filter', async () => {
const accordion = await loader.getHarness(MatAccordionHarness);
const panels = await accordion.getExpansionPanels({title: /Panel#1/});
expect(panels.length).toBe(1);
expect(await panels[0].getTitle()).toBe('Title of Panel#1');
});
it('should be able to check if accordion has multi panel support enabled', async () => {
const accordion = await loader.getHarness(MatAccordionHarness);
expect(await accordion.isMulti()).toBe(false);
fixture.componentInstance.multiMode = true;
fixture.changeDetectorRef.markForCheck();
expect(await accordion.isMulti()).toBe(true);
});
});
function getActiveElementTag() {
return document.activeElement ? document.activeElement.tagName.toLowerCase() : '';
}
@Component({
template: `
<mat-accordion id="accordion1" [hideToggle]="hideToggleIndicators"
[togglePosition]="toggleIndicatorsPosition"
[multi]="multiMode">
<mat-expansion-panel [expanded]="panel1Expanded" id="panel1">
<mat-expansion-panel-header>
<mat-panel-title>{{panel1Title}}</mat-panel-title>
<mat-panel-description>{{panel1Description}}</mat-panel-description>
</mat-expansion-panel-header>
{{panel1Content}}
</mat-expansion-panel>
<mat-expansion-panel expanded>
<mat-expansion-panel-header>
<mat-panel-title>
Title of Panel#2
</mat-panel-title>
<mat-panel-description>
Description of Panel#2
</mat-panel-description>
</mat-expansion-panel-header>
Content of Panel#2
</mat-expansion-panel>
</mat-accordion>
<mat-accordion id="accordion2">
<mat-expansion-panel>
<mat-expansion-panel-header>
Accordion #2 - Header
</mat-expansion-panel-header>
<p>Accordion #2 - Content</p>
</mat-expansion-panel>
</mat-accordion>
<mat-expansion-panel id="standalonePanel" expanded
[hideToggle]="hideToggleIndicators"
[togglePosition]="toggleIndicatorsPosition">
<mat-expansion-panel-header>
<mat-panel-title>Standalone Panel Title</mat-panel-title>
</mat-expansion-panel-header>
<div>
<span>Standalone Panel Body</span>
<div class="test-content-harness">Part of expansion panel</div>
</div>
</mat-expansion-panel>
<mat-expansion-panel id="disabledPanel" [disabled]="isDisabled">
<mat-expansion-panel-header>
<mat-panel-title>Disabled Panel Title</mat-panel-title>
</mat-expansion-panel-header>
</mat-expansion-panel>
<div class="test-content-harness">Outside of expansion panel</div>
`,
standalone: true,
imports: [MatExpansionModule],
})
class ExpansionHarnessTestComponent {
panel1Expanded = false;
panel1Title = 'Title of Panel#1';
panel1Description = 'Description of Panel#1';
panel1Content = 'Content of Panel#1';
hideToggleIndicators = false;
toggleIndicatorsPosition: MatAccordionTogglePosition;
isDisabled = true;
multiMode = false;
}
class TestContentHarness extends ComponentHarness {
static hostSelector = '.test-content-harness';
async getText() {
return (await this.host()).text();
}
} | {
"end_byte": 14646,
"start_byte": 9240,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/testing/expansion-harness.spec.ts"
} |
components/src/material/expansion/testing/public-api.ts_0_323 | /**
* @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 './accordion-harness';
export * from './expansion-harness';
export * from './expansion-harness-filters';
| {
"end_byte": 323,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/testing/public-api.ts"
} |
components/src/material/expansion/testing/accordion-harness.ts_0_1466 | /**
* @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, HarnessPredicate} from '@angular/cdk/testing';
import {MatExpansionPanelHarness} from './expansion-harness';
import {AccordionHarnessFilters, ExpansionPanelHarnessFilters} from './expansion-harness-filters';
/** Harness for interacting with a standard mat-accordion in tests. */
export class MatAccordionHarness extends ComponentHarness {
static hostSelector = '.mat-accordion';
/**
* Gets a `HarnessPredicate` that can be used to search for an accordion
* with specific attributes.
* @param options Options for narrowing the search.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: AccordionHarnessFilters = {}): HarnessPredicate<MatAccordionHarness> {
return new HarnessPredicate(MatAccordionHarness, options);
}
/** Gets all expansion panels which are part of the accordion. */
async getExpansionPanels(
filter: ExpansionPanelHarnessFilters = {},
): Promise<MatExpansionPanelHarness[]> {
return this.locatorForAll(MatExpansionPanelHarness.with(filter))();
}
/** Whether the accordion allows multiple expanded panels simultaneously. */
async isMulti(): Promise<boolean> {
return (await this.host()).hasClass('mat-accordion-multi');
}
}
| {
"end_byte": 1466,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/testing/accordion-harness.ts"
} |
components/src/material/expansion/testing/expansion-harness.ts_0_5648 | /**
* @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,
HarnessLoader,
HarnessPredicate,
} from '@angular/cdk/testing';
import {ExpansionPanelHarnessFilters} from './expansion-harness-filters';
/** Selectors for the various `mat-expansion-panel` sections that may contain user content. */
export enum MatExpansionPanelSection {
HEADER = '.mat-expansion-panel-header',
TITLE = '.mat-expansion-panel-header-title',
DESCRIPTION = '.mat-expansion-panel-header-description',
CONTENT = '.mat-expansion-panel-content',
}
/** Harness for interacting with a standard mat-expansion-panel in tests. */
export class MatExpansionPanelHarness extends ContentContainerComponentHarness<MatExpansionPanelSection> {
static hostSelector = '.mat-expansion-panel';
private _header = this.locatorFor(MatExpansionPanelSection.HEADER);
private _title = this.locatorForOptional(MatExpansionPanelSection.TITLE);
private _description = this.locatorForOptional(MatExpansionPanelSection.DESCRIPTION);
private _expansionIndicator = this.locatorForOptional('.mat-expansion-indicator');
private _content = this.locatorFor(MatExpansionPanelSection.CONTENT);
/**
* Gets a `HarnessPredicate` that can be used to search for an expansion-panel
* with specific attributes.
* @param options Options for narrowing the search:
* - `title` finds an expansion-panel with a specific title text.
* - `description` finds an expansion-panel with a specific description text.
* - `expanded` finds an expansion-panel that is currently expanded.
* - `disabled` finds an expansion-panel that is disabled.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(
options: ExpansionPanelHarnessFilters = {},
): HarnessPredicate<MatExpansionPanelHarness> {
return new HarnessPredicate(MatExpansionPanelHarness, options)
.addOption('title', options.title, (harness, title) =>
HarnessPredicate.stringMatches(harness.getTitle(), title),
)
.addOption('description', options.description, (harness, description) =>
HarnessPredicate.stringMatches(harness.getDescription(), description),
)
.addOption('content', options.content, (harness, content) =>
HarnessPredicate.stringMatches(harness.getTextContent(), content),
)
.addOption(
'expanded',
options.expanded,
async (harness, expanded) => (await harness.isExpanded()) === expanded,
)
.addOption(
'disabled',
options.disabled,
async (harness, disabled) => (await harness.isDisabled()) === disabled,
);
}
/** Whether the panel is expanded. */
async isExpanded(): Promise<boolean> {
return (await this.host()).hasClass('mat-expanded');
}
/**
* Gets the title text of the panel.
* @returns Title text or `null` if no title is set up.
*/
async getTitle(): Promise<string | null> {
const titleEl = await this._title();
return titleEl ? titleEl.text() : null;
}
/**
* Gets the description text of the panel.
* @returns Description text or `null` if no description is set up.
*/
async getDescription(): Promise<string | null> {
const descriptionEl = await this._description();
return descriptionEl ? descriptionEl.text() : null;
}
/** Whether the panel is disabled. */
async isDisabled(): Promise<boolean> {
return (await (await this._header()).getAttribute('aria-disabled')) === 'true';
}
/**
* Toggles the expanded state of the panel by clicking on the panel
* header. This method will not work if the panel is disabled.
*/
async toggle(): Promise<void> {
await (await this._header()).click();
}
/** Expands the expansion panel if collapsed. */
async expand(): Promise<void> {
if (!(await this.isExpanded())) {
await this.toggle();
}
}
/** Collapses the expansion panel if expanded. */
async collapse(): Promise<void> {
if (await this.isExpanded()) {
await this.toggle();
}
}
/** Gets the text content of the panel. */
async getTextContent(): Promise<string> {
return (await this._content()).text();
}
/**
* Gets a `HarnessLoader` that can be used to load harnesses for
* components within the panel's content area.
* @deprecated Use either `getChildLoader(MatExpansionPanelSection.CONTENT)`, `getHarness` or
* `getAllHarnesses` instead.
* @breaking-change 12.0.0
*/
async getHarnessLoaderForContent(): Promise<HarnessLoader> {
return this.getChildLoader(MatExpansionPanelSection.CONTENT);
}
/** Focuses the panel. */
async focus(): Promise<void> {
return (await this._header()).focus();
}
/** Blurs the panel. */
async blur(): Promise<void> {
return (await this._header()).blur();
}
/** Whether the panel is focused. */
async isFocused(): Promise<boolean> {
return (await this._header()).isFocused();
}
/** Whether the panel has a toggle indicator displayed. */
async hasToggleIndicator(): Promise<boolean> {
return (await this._expansionIndicator()) !== null;
}
/** Gets the position of the toggle indicator. */
async getToggleIndicatorPosition(): Promise<'before' | 'after'> {
// By default the expansion indicator will show "after" the panel header content.
if (await (await this._header()).hasClass('mat-expansion-toggle-indicator-before')) {
return 'before';
}
return 'after';
}
}
| {
"end_byte": 5648,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/testing/expansion-harness.ts"
} |
components/src/material/expansion/testing/expansion-harness-filters.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 {BaseHarnessFilters} from '@angular/cdk/testing';
export interface AccordionHarnessFilters extends BaseHarnessFilters {}
export interface ExpansionPanelHarnessFilters extends BaseHarnessFilters {
title?: string | RegExp | null;
description?: string | RegExp | null;
content?: string | RegExp;
expanded?: boolean;
disabled?: boolean;
}
| {
"end_byte": 558,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/testing/expansion-harness-filters.ts"
} |
components/src/material/expansion/testing/BUILD.bazel_0_724 | 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/expansion",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 724,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/testing/BUILD.bazel"
} |
components/src/material/expansion/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';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/expansion/testing/index.ts"
} |
components/src/material/button-toggle/button-toggle.html_0_1830 | <button #button class="mat-button-toggle-button mat-focus-indicator"
type="button"
[id]="buttonId"
[attr.role]="isSingleSelector() ? 'radio' : 'button'"
[attr.tabindex]="disabled && !disabledInteractive ? -1 : tabIndex"
[attr.aria-pressed]="!isSingleSelector() ? checked : null"
[attr.aria-checked]="isSingleSelector() ? checked : null"
[disabled]="(disabled && !disabledInteractive) || null"
[attr.name]="_getButtonName()"
[attr.aria-label]="ariaLabel"
[attr.aria-labelledby]="ariaLabelledby"
[attr.aria-disabled]="disabled && disabledInteractive ? 'true' : null"
(click)="_onButtonClick()">
<span class="mat-button-toggle-label-content">
<!-- Render checkmark at the beginning for single-selection. -->
@if (buttonToggleGroup && checked && !buttonToggleGroup.multiple && !buttonToggleGroup.hideSingleSelectionIndicator) {
<mat-pseudo-checkbox
class="mat-mdc-option-pseudo-checkbox"
[disabled]="disabled"
state="checked"
aria-hidden="true"
appearance="minimal"></mat-pseudo-checkbox>
}
<!-- Render checkmark at the beginning for multiple-selection. -->
@if (buttonToggleGroup && checked && buttonToggleGroup.multiple && !buttonToggleGroup.hideMultipleSelectionIndicator) {
<mat-pseudo-checkbox
class="mat-mdc-option-pseudo-checkbox"
[disabled]="disabled"
state="checked"
aria-hidden="true"
appearance="minimal"></mat-pseudo-checkbox>
}
<ng-content></ng-content>
</span>
</button>
<span class="mat-button-toggle-focus-overlay"></span>
<span class="mat-button-toggle-ripple" matRipple
[matRippleTrigger]="button"
[matRippleDisabled]="this.disableRipple || this.disabled">
</span>
| {
"end_byte": 1830,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.html"
} |
components/src/material/button-toggle/public-api.ts_0_277 | /**
* @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 './button-toggle';
export * from './button-toggle-module';
| {
"end_byte": 277,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/public-api.ts"
} |
components/src/material/button-toggle/button-toggle.scss_0_8571 | @use '@angular/cdk';
@use '../core/style/vendor-prefixes';
@use '../core/style/layout-common';
@use '../core/style/elevation';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/legacy-button-toggle' as tokens-mat-legacy-button-toggle;
@use '../core/tokens/m2/mat/standard-button-toggle' as tokens-mat-standard-button-toggle;
$standard-padding: 0 12px !default;
$legacy-padding: 0 16px !default;
$checkmark-padding: 12px !default;
// TODO(crisbeto): these variables aren't used anymore and should be removed.
$legacy-height: 36px !default;
$standard-border-radius: 4px !default;
$legacy-border-radius: 2px !default;
$_legacy-tokens: (
tokens-mat-legacy-button-toggle.$prefix,
tokens-mat-legacy-button-toggle.get-token-slots()
);
$_standard-tokens: (
tokens-mat-standard-button-toggle.$prefix,
tokens-mat-standard-button-toggle.get-token-slots()
);
.mat-button-toggle-standalone,
.mat-button-toggle-group {
position: relative;
display: inline-flex;
flex-direction: row;
white-space: nowrap;
overflow: hidden;
-webkit-tap-highlight-color: transparent;
// Fixes the ripples not being clipped to the border radius on Safari.
transform: translateZ(0);
@include token-utils.use-tokens($_legacy-tokens...) {
@include token-utils.create-token-slot(border-radius, shape);
}
@include elevation.overridable-elevation(2);
@include cdk.high-contrast {
outline: solid 1px;
}
}
.mat-button-toggle-standalone.mat-button-toggle-appearance-standard,
.mat-button-toggle-group-appearance-standard {
@include token-utils.use-tokens($_standard-tokens...) {
@include token-utils.create-token-slot(border-radius, shape);
border: solid 1px token-utils.get-token-variable(divider-color);
.mat-pseudo-checkbox {
--mat-minimal-pseudo-checkbox-selected-checkmark-color: #{
token-utils.get-token-variable(selected-state-text-color)};
}
}
&:not([class*='mat-elevation-z']) {
box-shadow: none;
}
@include cdk.high-contrast {
outline: 0;
}
}
.mat-button-toggle-vertical {
flex-direction: column;
.mat-button-toggle-label-content {
// Vertical button toggles shouldn't be an inline-block, because the toggles should
// fill the available width in the group.
display: block;
}
}
.mat-button-toggle {
white-space: nowrap;
position: relative;
@include token-utils.use-tokens($_legacy-tokens...) {
@include token-utils.create-token-slot(color, text-color);
@include token-utils.create-token-slot(font-family, label-text-font);
@include token-utils.create-token-slot(font-size, label-text-size);
@include token-utils.create-token-slot(line-height, label-text-line-height);
@include token-utils.create-token-slot(font-weight, label-text-weight);
@include token-utils.create-token-slot(letter-spacing, label-text-tracking);
--mat-minimal-pseudo-checkbox-selected-checkmark-color: #{
token-utils.get-token-variable(selected-state-text-color)};
&.cdk-keyboard-focused .mat-button-toggle-focus-overlay {
@include token-utils.create-token-slot(opacity, focus-state-layer-opacity);
}
}
// Fixes SVG icons that get thrown off because of the `vertical-align` on the parent.
.mat-icon svg {
vertical-align: top;
}
.mat-pseudo-checkbox {
margin-right: $checkmark-padding;
[dir='rtl'] & {
margin-right: 0;
margin-left: $checkmark-padding;
}
}
}
.mat-button-toggle-checked {
@include token-utils.use-tokens($_legacy-tokens...) {
@include token-utils.create-token-slot(color, selected-state-text-color);
@include token-utils.create-token-slot(background-color, selected-state-background-color);
}
}
.mat-button-toggle-disabled {
pointer-events: none;
@include token-utils.use-tokens($_legacy-tokens...) {
@include token-utils.create-token-slot(color, disabled-state-text-color);
@include token-utils.create-token-slot(background-color, disabled-state-background-color);
--mat-minimal-pseudo-checkbox-disabled-selected-checkmark-color: #{
token-utils.get-token-variable(disabled-state-text-color)};
&.mat-button-toggle-checked {
@include token-utils.create-token-slot(background-color,
disabled-selected-state-background-color);
}
}
}
.mat-button-toggle-disabled-interactive {
pointer-events: auto;
}
.mat-button-toggle-appearance-standard {
@include token-utils.use-tokens($_standard-tokens...) {
$divider-color: token-utils.get-token-variable(divider-color);
@include token-utils.create-token-slot(color, text-color);
@include token-utils.create-token-slot(background-color, background-color);
@include token-utils.create-token-slot(font-family, label-text-font);
@include token-utils.create-token-slot(font-size, label-text-size);
@include token-utils.create-token-slot(line-height, label-text-line-height);
@include token-utils.create-token-slot(font-weight, label-text-weight);
@include token-utils.create-token-slot(letter-spacing, label-text-tracking);
.mat-button-toggle-group-appearance-standard & + & {
border-left: solid 1px $divider-color;
}
[dir='rtl'] .mat-button-toggle-group-appearance-standard & + & {
border-left: none;
border-right: solid 1px $divider-color;
}
.mat-button-toggle-group-appearance-standard.mat-button-toggle-vertical & + & {
border-left: none;
border-right: none;
border-top: solid 1px $divider-color;
}
&.mat-button-toggle-checked {
@include token-utils.create-token-slot(color, selected-state-text-color);
@include token-utils.create-token-slot(background-color, selected-state-background-color);
}
&.mat-button-toggle-disabled {
@include token-utils.create-token-slot(color, disabled-state-text-color);
@include token-utils.create-token-slot(background-color, disabled-state-background-color);
.mat-pseudo-checkbox {
--mat-minimal-pseudo-checkbox-disabled-selected-checkmark-color: #{
token-utils.get-token-variable(disabled-selected-state-text-color)};
}
&.mat-button-toggle-checked {
@include token-utils.create-token-slot(color, disabled-selected-state-text-color);
@include token-utils.create-token-slot(background-color,
disabled-selected-state-background-color);
}
}
.mat-button-toggle-focus-overlay {
@include token-utils.create-token-slot(background-color, state-layer-color);
}
&:hover .mat-button-toggle-focus-overlay {
@include token-utils.create-token-slot(opacity, hover-state-layer-opacity);
}
// Similar to components like the checkbox, slide-toggle and radio, we cannot show the focus
// overlay for `.cdk-program-focused` because mouse clicks on the <label> element would be
// always treated as programmatic focus.
// TODO(paul): support `program` as well. See https://github.com/angular/components/issues/9889
&.cdk-keyboard-focused .mat-button-toggle-focus-overlay {
@include token-utils.create-token-slot(opacity, focus-state-layer-opacity);
}
}
// On touch devices the hover state will linger on the element after the user has tapped.
// Disable it, because it can be confused with focus. We target the :hover state explicitly,
// because we still want to preserve the keyboard focus state for hybrid devices that have
// a keyboard and a touchscreen.
@media (hover: none) {
&:hover .mat-button-toggle-focus-overlay {
display: none;
}
}
}
.mat-button-toggle-label-content {
@include vendor-prefixes.user-select(none);
display: inline-block;
padding: $legacy-padding;
@include token-utils.use-tokens($_legacy-tokens...) {
@include token-utils.create-token-slot(line-height, height);
}
// Prevents IE from shifting the content on click.
position: relative;
.mat-button-toggle-appearance-standard & {
padding: $standard-padding;
@include token-utils.use-tokens($_standard-tokens...) {
@include token-utils.create-token-slot(line-height, height);
}
}
}
.mat-button-toggle-label-content > * {
vertical-align: middle;
}
// Overlay to be used as a tint.
.mat-button-toggle-focus-overlay {
@include layout-common.fill;
border-radius: inherit;
// Disable pointer events to prevent it from hijacking user events.
pointer-events: none;
opacity: 0;
@include token-utils.use-tokens($_legacy-tokens...) {
@include token-utils.create-token-slot(background-color, state-layer-color);
}
}
@include cdk | {
"end_byte": 8571,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.scss"
} |
components/src/material/button-toggle/button-toggle.scss_8571_11423 | .high-contrast {
// Changing the background color for the selected item won't be visible in high contrast mode.
// We fall back to using the overlay to draw a brighter, semi-transparent tint on top instead.
// It uses a border, because the browser will render it using a brighter color.
.mat-button-toggle-checked {
.mat-button-toggle-focus-overlay {
border-bottom: solid 500px;
opacity: 0.5;
height: 0;
}
&:hover .mat-button-toggle-focus-overlay {
opacity: 0.6;
}
&.mat-button-toggle-appearance-standard .mat-button-toggle-focus-overlay {
// In high contrast mode, we use a border for the checked state because backgrounds
// can either be opaque or transparent. We set the border height to a value that is larger
// than usual button toggles are. This allows us to keep this high contrast style in the
// base component style, instead of making it dependent on height determined through density.
border-bottom: solid 500px;
}
}
}
// Increase specificity because ripple styles are part of the `mat-core` mixin and can
// potentially overwrite the absolute position of the container.
.mat-button-toggle .mat-button-toggle-ripple {
@include layout-common.fill;
// Disable pointer events for the ripple container, because the container will overlay the user
// content and we don't want to prevent mouse clicks that should toggle the state.
// Pointer events can be safely disabled because the ripple trigger element is the label element.
pointer-events: none;
}
.mat-button-toggle-button {
border: 0;
background: none;
color: inherit;
padding: 0;
margin: 0;
font: inherit;
outline: none;
width: 100%; // Stretch the button in case the consumer set a custom width.
cursor: pointer;
.mat-button-toggle-disabled & {
cursor: default;
}
// Remove the extra focus outline that is added by Firefox on native buttons.
&::-moz-focus-inner {
border: 0;
}
}
// Change the border-radius of the focus indicator to match the
// radius of the button-toggle-group or standalone button-toggle.
@include token-utils.use-tokens($_standard-tokens...) {
.mat-button-toggle-standalone.mat-button-toggle-appearance-standard {
@include token-utils.create-token-slot(--mat-focus-indicator-border-radius, shape);
}
.mat-button-toggle-group-appearance-standard .mat-button-toggle {
&:last-of-type .mat-button-toggle-button::before {
@include token-utils.create-token-slot(border-top-right-radius, shape);
@include token-utils.create-token-slot(border-bottom-right-radius, shape);
}
&:first-of-type .mat-button-toggle-button::before {
@include token-utils.create-token-slot(border-top-left-radius, shape);
@include token-utils.create-token-slot(border-bottom-left-radius, shape);
}
}
} | {
"end_byte": 11423,
"start_byte": 8571,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.scss"
} |
components/src/material/button-toggle/README.md_0_103 | Please see the official documentation at https://material.angular.io/components/component/button-toggle | {
"end_byte": 103,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/README.md"
} |
components/src/material/button-toggle/button-toggle.md_0_2573 | `<mat-button-toggle>` are on/off toggles with the appearance of a button. These toggles can be
configured to behave as either radio-buttons or checkboxes. While they can be standalone, they are
typically part of a `mat-button-toggle-group`.
<!-- example(button-toggle-overview) -->
### Exclusive selection vs. multiple selection
By default, `mat-button-toggle-group` acts like a radio-button group- only one item can be selected.
In this mode, the `value` of the `mat-button-toggle-group` will reflect the value of the selected
button and `ngModel` is supported.
Adding the `multiple` attribute allows multiple items to be selected (checkbox behavior). In this
mode the values of the toggles are not used, the `mat-button-toggle-group` does not have a value,
and `ngModel` is not supported.
<!-- example(button-toggle-mode) -->
### Appearance
By default, the appearance of `mat-button-toggle-group` and `mat-button-toggle` will follow the
latest Material Design guidelines. If you want to, you can switch back to the appearance that was
following a previous Material Design spec by using the `appearance` input. The `appearance` can
be configured globally using the `MAT_BUTTON_TOGGLE_DEFAULT_OPTIONS` injection token.
<!-- example(button-toggle-appearance) -->
### Use with `@angular/forms`
`<mat-button-toggle-group>` is compatible with `@angular/forms` and supports both `FormsModule`
and `ReactiveFormsModule`.
### Orientation
The button-toggles can be rendered in a vertical orientation by adding the `vertical` attribute.
### Accessibility
`MatButtonToggle` internally uses native `button` elements with `aria-pressed` to convey toggle
state. If a toggle contains only an icon, you should specify a meaningful label via `aria-label`
or `aria-labelledby`. For dynamic labels, `MatButtonToggle` provides input properties for binding
`aria-label` and `aria-labelledby`. This means that you should not use the `attr.` prefix when
binding these properties, as demonstrated below.
```html
<mat-button-toggle [aria-label]="alertsEnabled ? 'Disable alerts' : 'Enable alerts'">
<mat-icon>notifications</mat-icon>
</mat-button-toggle>
```
The `MatButtonToggleGroup` surrounding the individual buttons applies
`role="group"` to convey the association between the individual toggles. Each
`<mat-button-toggle-group>` element should be given a label with `aria-label` or `aria-labelledby`
that communicates the collective meaning of all toggles. For example, if you have toggles for
"Bold", "Italic", and "Underline", you might label the parent group "Font styles".
| {
"end_byte": 2573,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.md"
} |
components/src/material/button-toggle/button-toggle.spec.ts_0_9846 | import {dispatchMouseEvent} from '@angular/cdk/testing/private';
import {Component, DebugElement, QueryList, ViewChild, ViewChildren} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing';
import {FormControl, FormsModule, NgModel, ReactiveFormsModule} from '@angular/forms';
import {By} from '@angular/platform-browser';
import {
MAT_BUTTON_TOGGLE_DEFAULT_OPTIONS,
MatButtonToggle,
MatButtonToggleChange,
MatButtonToggleGroup,
MatButtonToggleModule,
} from './index';
describe('MatButtonToggle with forms', () => {
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [
MatButtonToggleModule,
FormsModule,
ReactiveFormsModule,
ButtonToggleGroupWithNgModel,
ButtonToggleGroupWithFormControl,
ButtonToggleGroupWithIndirectDescendantToggles,
ButtonToggleGroupWithFormControlAndDynamicButtons,
],
});
}));
describe('using FormControl', () => {
let fixture: ComponentFixture<ButtonToggleGroupWithFormControl>;
let groupDebugElement: DebugElement;
let groupInstance: MatButtonToggleGroup;
let testComponent: ButtonToggleGroupWithFormControl;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(ButtonToggleGroupWithFormControl);
fixture.detectChanges();
testComponent = fixture.debugElement.componentInstance;
groupDebugElement = fixture.debugElement.query(By.directive(MatButtonToggleGroup))!;
groupInstance = groupDebugElement.injector.get<MatButtonToggleGroup>(MatButtonToggleGroup);
}));
it('should toggle the disabled state', () => {
testComponent.control.disable();
expect(groupInstance.disabled).toBe(true);
testComponent.control.enable();
expect(groupInstance.disabled).toBe(false);
});
it('should set the value', () => {
testComponent.control.setValue('green');
expect(groupInstance.value).toBe('green');
testComponent.control.setValue('red');
expect(groupInstance.value).toBe('red');
});
it('should register the on change callback', () => {
const spy = jasmine.createSpy('onChange callback');
testComponent.control.registerOnChange(spy);
testComponent.control.setValue('blue');
expect(spy).toHaveBeenCalled();
});
});
describe('button toggle group with ngModel and change event', () => {
let fixture: ComponentFixture<ButtonToggleGroupWithNgModel>;
let groupDebugElement: DebugElement;
let buttonToggleDebugElements: DebugElement[];
let groupInstance: MatButtonToggleGroup;
let buttonToggleInstances: MatButtonToggle[];
let testComponent: ButtonToggleGroupWithNgModel;
let groupNgModel: NgModel;
let innerButtons: HTMLElement[];
beforeEach(() => {
fixture = TestBed.createComponent(ButtonToggleGroupWithNgModel);
fixture.detectChanges();
testComponent = fixture.debugElement.componentInstance;
groupDebugElement = fixture.debugElement.query(By.directive(MatButtonToggleGroup))!;
groupInstance = groupDebugElement.injector.get<MatButtonToggleGroup>(MatButtonToggleGroup);
groupNgModel = groupDebugElement.injector.get<NgModel>(NgModel);
buttonToggleDebugElements = fixture.debugElement.queryAll(By.directive(MatButtonToggle));
buttonToggleInstances = buttonToggleDebugElements.map(debugEl => debugEl.componentInstance);
innerButtons = buttonToggleDebugElements.map(
debugEl => debugEl.query(By.css('button'))!.nativeElement,
);
fixture.detectChanges();
});
it('should update the model before firing change event', fakeAsync(() => {
expect(testComponent.modelValue).toBeUndefined();
expect(testComponent.lastEvent).toBeUndefined();
innerButtons[0].click();
fixture.detectChanges();
tick();
expect(testComponent.modelValue).toBe('red');
expect(testComponent.lastEvent.value).toBe('red');
}));
it('should set individual radio names based on the group name', () => {
expect(groupInstance.name).toBeTruthy();
for (let buttonToggle of innerButtons) {
expect(buttonToggle.getAttribute('name')).toBe(groupInstance.name);
}
groupInstance.name = 'new name';
fixture.detectChanges();
for (let buttonToggle of innerButtons) {
expect(buttonToggle.getAttribute('name')).toBe(groupInstance.name);
}
});
it('should update the name of radio DOM elements if the name of the group changes', () => {
expect(innerButtons.every(button => button.getAttribute('name') === groupInstance.name))
.withContext('Expected all buttons to have the initial name.')
.toBe(true);
fixture.componentInstance.groupName = 'changed-name';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(groupInstance.name).toBe('changed-name');
expect(innerButtons.every(button => button.getAttribute('name') === groupInstance.name))
.withContext('Expected all buttons to have the new name.')
.toBe(true);
});
it('should set the name of the buttons to the group name if the name of the button changes after init', () => {
const firstButton = innerButtons[0];
expect(firstButton.getAttribute('name')).toBe(fixture.componentInstance.groupName);
fixture.componentInstance.options[0].name = 'changed-name';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(firstButton.getAttribute('name')).toBe(fixture.componentInstance.groupName);
});
it('should check the corresponding button toggle on a group value change', () => {
expect(groupInstance.value).toBeFalsy();
for (let buttonToggle of buttonToggleInstances) {
expect(buttonToggle.checked).toBeFalsy();
}
groupInstance.value = 'red';
for (let buttonToggle of buttonToggleInstances) {
expect(buttonToggle.checked).toBe(groupInstance.value === buttonToggle.value);
}
const selected = groupInstance.selected as MatButtonToggle;
expect(selected.value).toBe(groupInstance.value);
});
it('should have the correct FormControl state initially and after interaction', fakeAsync(() => {
expect(groupNgModel.valid).toBe(true);
expect(groupNgModel.pristine).toBe(true);
expect(groupNgModel.touched).toBe(false);
buttonToggleInstances[1].checked = true;
fixture.detectChanges();
tick();
expect(groupNgModel.valid).toBe(true);
expect(groupNgModel.pristine).toBe(true);
expect(groupNgModel.touched).toBe(false);
innerButtons[2].click();
fixture.detectChanges();
tick();
expect(groupNgModel.valid).toBe(true);
expect(groupNgModel.pristine).toBe(false);
expect(groupNgModel.touched).toBe(true);
}));
it('should update the ngModel value when selecting a button toggle', fakeAsync(() => {
innerButtons[1].click();
fixture.detectChanges();
tick();
expect(testComponent.modelValue).toBe('green');
}));
it('should show a ripple on label click', () => {
const groupElement = groupDebugElement.nativeElement;
expect(groupElement.querySelectorAll('.mat-ripple-element').length).toBe(0);
dispatchMouseEvent(innerButtons[0], 'mousedown');
dispatchMouseEvent(innerButtons[0], 'mouseup');
expect(groupElement.querySelectorAll('.mat-ripple-element').length).toBe(1);
});
it('should allow ripples to be disabled', () => {
const groupElement = groupDebugElement.nativeElement;
testComponent.disableRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(groupElement.querySelectorAll('.mat-ripple-element').length).toBe(0);
dispatchMouseEvent(innerButtons[0], 'mousedown');
dispatchMouseEvent(innerButtons[0], 'mouseup');
expect(groupElement.querySelectorAll('.mat-ripple-element').length).toBe(0);
});
it(
'should maintain the selected value when swapping out the list of toggles with one ' +
'that still contains the value',
fakeAsync(() => {
expect(buttonToggleInstances[0].checked).toBe(false);
expect(fixture.componentInstance.modelValue).toBeFalsy();
expect(groupInstance.value).toBeFalsy();
groupInstance.value = 'red';
fixture.detectChanges();
expect(buttonToggleInstances[0].checked).toBe(true);
expect(groupInstance.value).toBe('red');
fixture.componentInstance.options = [...fixture.componentInstance.options];
fixture.detectChanges();
tick();
fixture.detectChanges();
buttonToggleDebugElements = fixture.debugElement.queryAll(By.directive(MatButtonToggle));
buttonToggleInstances = buttonToggleDebugElements.map(debugEl => debugEl.componentInstance);
expect(buttonToggleInstances[0].checked).toBe(true);
expect(groupInstance.value).toBe('red');
}),
);
});
it('should be able to pick up toggles that are not direct descendants', fakeAsync(() => {
const fixture = TestBed.createComponent(ButtonToggleGroupWithIndirectDescendantToggles);
fixture.detectChanges();
const button = fixture.nativeElement.querySelector('.mat-button-toggle button');
const groupDebugElement = fixture.debugElement.query(By.directive(MatButtonToggleGroup))!;
const groupInstance =
groupDebugElement.injector.get<MatButtonToggleGroup>(MatButtonToggleGroup);
button.click();
fixture.detectChanges();
tick();
expect(groupInstance.value).toBe('red');
expect(fixture.componentInstance.control.value).toBe('red');
expect(groupInstance._buttonToggles.length).toBe(3);
})); | {
"end_byte": 9846,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.spec.ts"
} |
components/src/material/button-toggle/button-toggle.spec.ts_9850_12214 | it('should preserve the selection if the pre-selected option is removed and re-added', () => {
const fixture = TestBed.createComponent(ButtonToggleGroupWithFormControlAndDynamicButtons);
const instance = fixture.componentInstance;
instance.control.setValue('a');
fixture.detectChanges();
const buttons = fixture.nativeElement.querySelectorAll('.mat-button-toggle-button');
expect(instance.toggles.map(t => t.checked)).toEqual([true, false, false]);
buttons[2].click();
fixture.detectChanges();
instance.values.shift();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(instance.toggles.map(t => t.checked)).toEqual([false, true]);
instance.values.unshift('a');
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(instance.toggles.map(t => t.checked)).toEqual([false, false, true]);
});
it('should preserve the pre-selected option if it is removed and re-added', () => {
const fixture = TestBed.createComponent(ButtonToggleGroupWithFormControlAndDynamicButtons);
const instance = fixture.componentInstance;
instance.control.setValue('a');
fixture.detectChanges();
expect(instance.toggles.map(t => t.checked)).toEqual([true, false, false]);
instance.values.shift();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(instance.toggles.map(t => t.checked)).toEqual([false, false]);
instance.values.unshift('a');
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(instance.toggles.map(t => t.checked)).toEqual([true, false, false]);
});
});
describe('MatButtonToggle without forms', () => {
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [
MatButtonToggleModule,
ButtonTogglesInsideButtonToggleGroup,
ButtonTogglesInsideButtonToggleGroupMultiple,
FalsyButtonTogglesInsideButtonToggleGroupMultiple,
ButtonToggleGroupWithInitialValue,
StandaloneButtonToggle,
ButtonToggleWithAriaLabel,
ButtonToggleWithAriaLabelledby,
RepeatedButtonTogglesWithPreselectedValue,
ButtonToggleWithTabindex,
ButtonToggleWithStaticName,
ButtonToggleWithStaticChecked,
ButtonToggleWithStaticAriaAttributes,
],
});
})); | {
"end_byte": 12214,
"start_byte": 9850,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.spec.ts"
} |
components/src/material/button-toggle/button-toggle.spec.ts_12218_22077 | describe('inside of an exclusive selection group', () => {
let fixture: ComponentFixture<ButtonTogglesInsideButtonToggleGroup>;
let groupDebugElement: DebugElement;
let groupNativeElement: HTMLElement;
let buttonToggleDebugElements: DebugElement[];
let buttonToggleNativeElements: HTMLElement[];
let buttonToggleLabelElements: HTMLLabelElement[];
let groupInstance: MatButtonToggleGroup;
let buttonToggleInstances: MatButtonToggle[];
let testComponent: ButtonTogglesInsideButtonToggleGroup;
beforeEach(() => {
fixture = TestBed.createComponent(ButtonTogglesInsideButtonToggleGroup);
fixture.detectChanges();
testComponent = fixture.debugElement.componentInstance;
groupDebugElement = fixture.debugElement.query(By.directive(MatButtonToggleGroup))!;
groupNativeElement = groupDebugElement.nativeElement;
groupInstance = groupDebugElement.injector.get<MatButtonToggleGroup>(MatButtonToggleGroup);
buttonToggleDebugElements = fixture.debugElement.queryAll(By.directive(MatButtonToggle));
buttonToggleNativeElements = buttonToggleDebugElements.map(debugEl => debugEl.nativeElement);
buttonToggleLabelElements = fixture.debugElement
.queryAll(By.css('button'))
.map(debugEl => debugEl.nativeElement);
buttonToggleInstances = buttonToggleDebugElements.map(debugEl => debugEl.componentInstance);
});
it('should initialize the tab index correctly', () => {
buttonToggleLabelElements.forEach((buttonToggle, index) => {
if (index === 0) {
expect(buttonToggle.getAttribute('tabindex')).toBe('0');
} else {
expect(buttonToggle.getAttribute('tabindex')).toBe('-1');
}
});
});
it('should update the tab index correctly', () => {
buttonToggleLabelElements[1].click();
fixture.detectChanges();
expect(buttonToggleLabelElements[0].getAttribute('tabindex')).toBe('-1');
expect(buttonToggleLabelElements[1].getAttribute('tabindex')).toBe('0');
});
it('should set individual button toggle names based on the group name', () => {
expect(groupInstance.name).toBeTruthy();
for (let buttonToggle of buttonToggleLabelElements) {
expect(buttonToggle.getAttribute('name')).toBe(groupInstance.name);
}
});
it('should disable click interactions when the group is disabled', () => {
testComponent.isGroupDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
buttonToggleNativeElements[0].click();
expect(buttonToggleInstances[0].checked).toBe(false);
expect(buttonToggleInstances[0].disabled).toBe(true);
testComponent.isGroupDisabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttonToggleInstances[0].disabled).toBe(false);
buttonToggleLabelElements[0].click();
fixture.detectChanges();
expect(buttonToggleInstances[0].checked).toBe(true);
});
it('should set aria-disabled based on whether the group is disabled', () => {
expect(groupNativeElement.getAttribute('aria-disabled')).toBe('false');
testComponent.isGroupDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(groupNativeElement.getAttribute('aria-disabled')).toBe('true');
});
it('should disable the underlying button when the group is disabled', () => {
const buttons = buttonToggleNativeElements.map(toggle => toggle.querySelector('button')!);
expect(buttons.every(input => input.disabled)).toBe(false);
testComponent.isGroupDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(buttons.every(input => input.disabled)).toBe(true);
});
it('should be able to keep the button interactive while disabled', () => {
const button = buttonToggleNativeElements[0].querySelector('button')!;
testComponent.isGroupDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(button.hasAttribute('disabled')).toBe(true);
expect(button.hasAttribute('aria-disabled')).toBe(false);
expect(button.getAttribute('tabindex')).toBe('-1');
testComponent.disabledIntearctive = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(button.hasAttribute('disabled')).toBe(false);
expect(button.getAttribute('aria-disabled')).toBe('true');
expect(button.getAttribute('tabindex')).toBe('0');
});
it('should update the group value when one of the toggles changes', () => {
expect(groupInstance.value).toBeFalsy();
buttonToggleLabelElements[0].click();
fixture.detectChanges();
expect(groupInstance.value).toBe('test1');
expect(groupInstance.selected).toBe(buttonToggleInstances[0]);
});
it('should propagate the value change back up via a two-way binding', () => {
expect(groupInstance.value).toBeFalsy();
buttonToggleLabelElements[0].click();
fixture.detectChanges();
expect(groupInstance.value).toBe('test1');
expect(testComponent.groupValue).toBe('test1');
});
it('should update the group and toggles when one of the button toggles is clicked', () => {
expect(groupInstance.value).toBeFalsy();
buttonToggleLabelElements[0].click();
fixture.detectChanges();
expect(groupInstance.value).toBe('test1');
expect(groupInstance.selected).toBe(buttonToggleInstances[0]);
expect(buttonToggleInstances[0].checked).toBe(true);
expect(buttonToggleInstances[1].checked).toBe(false);
buttonToggleLabelElements[1].click();
fixture.detectChanges();
expect(groupInstance.value).toBe('test2');
expect(groupInstance.selected).toBe(buttonToggleInstances[1]);
expect(buttonToggleInstances[0].checked).toBe(false);
expect(buttonToggleInstances[1].checked).toBe(true);
});
it('should check a button toggle upon interaction with underlying native radio button', () => {
buttonToggleLabelElements[0].click();
fixture.detectChanges();
expect(buttonToggleInstances[0].checked).toBe(true);
expect(groupInstance.value).toBe('test1');
});
it('should change the vertical state', () => {
expect(groupNativeElement.classList).not.toContain('mat-button-toggle-vertical');
groupInstance.vertical = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(groupNativeElement.classList).toContain('mat-button-toggle-vertical');
});
it('should emit a change event from button toggles', fakeAsync(() => {
expect(buttonToggleInstances[0].checked).toBe(false);
const changeSpy = jasmine.createSpy('button-toggle change listener');
buttonToggleInstances[0].change.subscribe(changeSpy);
buttonToggleLabelElements[0].click();
fixture.detectChanges();
tick();
expect(changeSpy).toHaveBeenCalledTimes(1);
buttonToggleLabelElements[0].click();
fixture.detectChanges();
tick();
// Always emit change event when button toggle is clicked
expect(changeSpy).toHaveBeenCalledTimes(2);
}));
it('should emit a change event from the button toggle group', fakeAsync(() => {
expect(groupInstance.value).toBeFalsy();
const changeSpy = jasmine.createSpy('button-toggle-group change listener');
groupInstance.change.subscribe(changeSpy);
buttonToggleLabelElements[0].click();
fixture.detectChanges();
tick();
expect(changeSpy).toHaveBeenCalled();
buttonToggleLabelElements[1].click();
fixture.detectChanges();
tick();
expect(changeSpy).toHaveBeenCalledTimes(2);
}));
it('should update the group and button toggles when updating the group value', () => {
expect(groupInstance.value).toBeFalsy();
testComponent.groupValue = 'test1';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(groupInstance.value).toBe('test1');
expect(groupInstance.selected).toBe(buttonToggleInstances[0]);
expect(buttonToggleInstances[0].checked).toBe(true);
expect(buttonToggleInstances[1].checked).toBe(false);
testComponent.groupValue = 'test2';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(groupInstance.value).toBe('test2');
expect(groupInstance.selected).toBe(buttonToggleInstances[1]);
expect(buttonToggleInstances[0].checked).toBe(false);
expect(buttonToggleInstances[1].checked).toBe(true);
});
it('should deselect all of the checkboxes when the group value is cleared', () => {
buttonToggleInstances[0].checked = true;
expect(groupInstance.value).toBeTruthy();
groupInstance.value = null;
expect(buttonToggleInstances.every(toggle => !toggle.checked)).toBe(true);
});
it('should update the model if a selected toggle is removed', fakeAsync(() => {
expect(groupInstance.value).toBeFalsy();
buttonToggleLabelElements[0].click();
fixture.detectChanges();
expect(groupInstance.value).toBe('test1');
expect(groupInstance.selected).toBe(buttonToggleInstances[0]);
testComponent.renderFirstToggle = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(groupInstance.value).toBeFalsy();
expect(groupInstance.selected).toBeFalsy();
}));
it('should show checkmark indicator by default', () => {
buttonToggleLabelElements[0].click();
fixture.detectChanges();
expect(document.querySelectorAll('.mat-pseudo-checkbox').length).toBe(1);
});
}); | {
"end_byte": 22077,
"start_byte": 12218,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.spec.ts"
} |
components/src/material/button-toggle/button-toggle.spec.ts_22081_31264 | describe('with initial value and change event', () => {
it('should not fire an initial change event', () => {
const fixture = TestBed.createComponent(ButtonToggleGroupWithInitialValue);
const testComponent = fixture.debugElement.componentInstance;
const groupDebugElement = fixture.debugElement.query(By.directive(MatButtonToggleGroup))!;
const groupInstance: MatButtonToggleGroup =
groupDebugElement.injector.get<MatButtonToggleGroup>(MatButtonToggleGroup);
fixture.detectChanges();
// Note that we cast to a boolean, because the event has some circular references
// which will crash the runner when Jasmine attempts to stringify them.
expect(!!testComponent.lastEvent).toBe(false);
expect(groupInstance.value).toBe('red');
groupInstance.value = 'green';
fixture.detectChanges();
expect(!!testComponent.lastEvent).toBe(false);
expect(groupInstance.value).toBe('green');
});
});
describe('inside of a multiple selection group', () => {
let fixture: ComponentFixture<ButtonTogglesInsideButtonToggleGroupMultiple>;
let groupDebugElement: DebugElement;
let groupNativeElement: HTMLElement;
let buttonToggleDebugElements: DebugElement[];
let buttonToggleNativeElements: HTMLElement[];
let buttonToggleLabelElements: HTMLLabelElement[];
let groupInstance: MatButtonToggleGroup;
let buttonToggleInstances: MatButtonToggle[];
let testComponent: ButtonTogglesInsideButtonToggleGroupMultiple;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(ButtonTogglesInsideButtonToggleGroupMultiple);
fixture.detectChanges();
testComponent = fixture.debugElement.componentInstance;
groupDebugElement = fixture.debugElement.query(By.directive(MatButtonToggleGroup))!;
groupNativeElement = groupDebugElement.nativeElement;
groupInstance = groupDebugElement.injector.get<MatButtonToggleGroup>(MatButtonToggleGroup);
buttonToggleDebugElements = fixture.debugElement.queryAll(By.directive(MatButtonToggle));
buttonToggleNativeElements = buttonToggleDebugElements.map(debugEl => debugEl.nativeElement);
buttonToggleLabelElements = fixture.debugElement
.queryAll(By.css('button'))
.map(debugEl => debugEl.nativeElement);
buttonToggleInstances = buttonToggleDebugElements.map(debugEl => debugEl.componentInstance);
}));
it('should disable click interactions when the group is disabled', () => {
testComponent.isGroupDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
buttonToggleNativeElements[0].click();
expect(buttonToggleInstances[0].checked).toBe(false);
});
it('should check a button toggle when clicked', () => {
expect(buttonToggleInstances.every(buttonToggle => !buttonToggle.checked)).toBe(true);
const nativeCheckboxLabel = buttonToggleDebugElements[0].query(
By.css('button'),
)!.nativeElement;
nativeCheckboxLabel.click();
expect(groupInstance.value).toEqual(['eggs']);
expect(buttonToggleInstances[0].checked).toBe(true);
});
it('should allow for multiple toggles to be selected', () => {
buttonToggleInstances[0].checked = true;
fixture.detectChanges();
expect(groupInstance.value).toEqual(['eggs']);
expect(buttonToggleInstances[0].checked).toBe(true);
buttonToggleInstances[1].checked = true;
fixture.detectChanges();
expect(groupInstance.value).toEqual(['eggs', 'flour']);
expect(buttonToggleInstances[1].checked).toBe(true);
expect(buttonToggleInstances[0].checked).toBe(true);
});
it('should check a button toggle upon interaction with underlying native checkbox', () => {
const nativeCheckboxButton = buttonToggleDebugElements[0].query(
By.css('button'),
)!.nativeElement;
nativeCheckboxButton.click();
fixture.detectChanges();
expect(groupInstance.value).toEqual(['eggs']);
expect(buttonToggleInstances[0].checked).toBe(true);
});
it('should change the vertical state', () => {
expect(groupNativeElement.classList).not.toContain('mat-button-toggle-vertical');
groupInstance.vertical = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(groupNativeElement.classList).toContain('mat-button-toggle-vertical');
});
it('should deselect a button toggle when selected twice', fakeAsync(() => {
buttonToggleLabelElements[0].click();
fixture.detectChanges();
tick();
expect(buttonToggleInstances[0].checked).toBe(true);
expect(groupInstance.value).toEqual(['eggs']);
buttonToggleLabelElements[0].click();
fixture.detectChanges();
tick();
expect(groupInstance.value).toEqual([]);
expect(buttonToggleInstances[0].checked).toBe(false);
}));
it('should emit a change event for state changes', fakeAsync(() => {
expect(buttonToggleInstances[0].checked).toBe(false);
const changeSpy = jasmine.createSpy('button-toggle change listener');
buttonToggleInstances[0].change.subscribe(changeSpy);
buttonToggleLabelElements[0].click();
fixture.detectChanges();
tick();
expect(changeSpy).toHaveBeenCalled();
expect(groupInstance.value).toEqual(['eggs']);
buttonToggleLabelElements[0].click();
fixture.detectChanges();
tick();
expect(groupInstance.value).toEqual([]);
// The default browser behavior is to emit an event, when the value was set
// to false. That's because the current input type is set to `checkbox` when
// using the multiple mode.
expect(changeSpy).toHaveBeenCalledTimes(2);
}));
it('should throw when attempting to assign a non-array value', () => {
expect(() => {
groupInstance.value = 'not-an-array';
}).toThrowError(/Value must be an array/);
});
it('should show checkmark indicator by default', () => {
buttonToggleLabelElements[0].click();
buttonToggleLabelElements[1].click();
fixture.detectChanges();
expect(document.querySelectorAll('.mat-pseudo-checkbox').length).toBe(2);
});
});
describe('as standalone', () => {
let fixture: ComponentFixture<StandaloneButtonToggle>;
let buttonToggleDebugElement: DebugElement;
let buttonToggleNativeElement: HTMLElement;
let buttonToggleLabelElement: HTMLLabelElement;
let buttonToggleInstance: MatButtonToggle;
let buttonToggleButtonElement: HTMLButtonElement;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(StandaloneButtonToggle);
fixture.detectChanges();
buttonToggleDebugElement = fixture.debugElement.query(By.directive(MatButtonToggle))!;
buttonToggleNativeElement = buttonToggleDebugElement.nativeElement;
buttonToggleLabelElement = fixture.debugElement.query(
By.css('.mat-button-toggle-label-content'),
)!.nativeElement;
buttonToggleInstance = buttonToggleDebugElement.componentInstance;
buttonToggleButtonElement = buttonToggleNativeElement.querySelector(
'button',
)! as HTMLButtonElement;
}));
it('should toggle when clicked', fakeAsync(() => {
buttonToggleLabelElement.click();
fixture.detectChanges();
flush();
expect(buttonToggleInstance.checked).toBe(true);
buttonToggleLabelElement.click();
fixture.detectChanges();
flush();
expect(buttonToggleInstance.checked).toBe(false);
}));
it('should emit a change event for state changes', fakeAsync(() => {
expect(buttonToggleInstance.checked).toBe(false);
const changeSpy = jasmine.createSpy('button-toggle change listener');
buttonToggleInstance.change.subscribe(changeSpy);
buttonToggleLabelElement.click();
fixture.detectChanges();
tick();
expect(changeSpy).toHaveBeenCalled();
buttonToggleLabelElement.click();
fixture.detectChanges();
tick();
// The default browser behavior is to emit an event, when the value was set
// to false. That's because the current input type is set to `checkbox`.
expect(changeSpy).toHaveBeenCalledTimes(2);
}));
it('should focus on underlying input element when focus() is called', () => {
const nativeButton = buttonToggleDebugElement.query(By.css('button'))!.nativeElement;
expect(document.activeElement).not.toBe(nativeButton);
buttonToggleInstance.focus();
fixture.detectChanges();
expect(document.activeElement).toBe(nativeButton);
});
it('should not assign a name to the underlying input if one is not passed in', () => {
expect(buttonToggleButtonElement.getAttribute('name')).toBeFalsy();
});
it('should have correct aria-pressed attribute', () => {
expect(buttonToggleButtonElement.getAttribute('aria-pressed')).toBe('false');
buttonToggleLabelElement.click();
fixture.detectChanges();
expect(buttonToggleButtonElement.getAttribute('aria-pressed')).toBe('true');
});
}); | {
"end_byte": 31264,
"start_byte": 22081,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.spec.ts"
} |
components/src/material/button-toggle/button-toggle.spec.ts_31268_41013 | describe('aria-label handling ', () => {
it('should not set the aria-label attribute if none is provided', () => {
const fixture = TestBed.createComponent(StandaloneButtonToggle);
const checkboxDebugElement = fixture.debugElement.query(By.directive(MatButtonToggle))!;
const checkboxNativeElement = checkboxDebugElement.nativeElement;
const buttonElement = checkboxNativeElement.querySelector('button') as HTMLButtonElement;
fixture.detectChanges();
expect(buttonElement.hasAttribute('aria-label')).toBe(false);
});
it('should use the provided aria-label', () => {
const fixture = TestBed.createComponent(ButtonToggleWithAriaLabel);
const checkboxDebugElement = fixture.debugElement.query(By.directive(MatButtonToggle))!;
const checkboxNativeElement = checkboxDebugElement.nativeElement;
const buttonElement = checkboxNativeElement.querySelector('button') as HTMLButtonElement;
fixture.detectChanges();
expect(buttonElement.getAttribute('aria-label')).toBe('Super effective');
});
it('should clear the static aria from the host node', () => {
const fixture = TestBed.createComponent(ButtonToggleWithStaticAriaAttributes);
fixture.detectChanges();
const hostNode: HTMLElement = fixture.nativeElement.querySelector('mat-button-toggle');
expect(hostNode.hasAttribute('aria-label')).toBe(false);
expect(hostNode.hasAttribute('aria-labelledby')).toBe(false);
});
});
describe('with provided aria-labelledby ', () => {
let checkboxDebugElement: DebugElement;
let checkboxNativeElement: HTMLElement;
let buttonElement: HTMLButtonElement;
it('should use the provided aria-labelledby', () => {
const fixture = TestBed.createComponent(ButtonToggleWithAriaLabelledby);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatButtonToggle))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
buttonElement = checkboxNativeElement.querySelector('button') as HTMLButtonElement;
fixture.detectChanges();
expect(buttonElement.getAttribute('aria-labelledby')).toBe('some-id');
});
it('should not assign aria-labelledby if none is provided', () => {
const fixture = TestBed.createComponent(StandaloneButtonToggle);
checkboxDebugElement = fixture.debugElement.query(By.directive(MatButtonToggle))!;
checkboxNativeElement = checkboxDebugElement.nativeElement;
buttonElement = checkboxNativeElement.querySelector('button') as HTMLButtonElement;
fixture.detectChanges();
expect(buttonElement.getAttribute('aria-labelledby')).toBe(null);
});
});
describe('with tabindex', () => {
it('should forward the tabindex to the underlying button', () => {
const fixture = TestBed.createComponent(ButtonToggleWithTabindex);
fixture.detectChanges();
const button = fixture.nativeElement.querySelector('.mat-button-toggle button');
expect(button.getAttribute('tabindex')).toBe('3');
});
it('should have role "presentation"', () => {
const fixture = TestBed.createComponent(ButtonToggleWithTabindex);
fixture.detectChanges();
const host = fixture.nativeElement.querySelector('.mat-button-toggle');
expect(host.getAttribute('role')).toBe('presentation');
});
it('should forward focus to the underlying button when the host is focused', () => {
const fixture = TestBed.createComponent(ButtonToggleWithTabindex);
fixture.detectChanges();
const host = fixture.nativeElement.querySelector('.mat-button-toggle');
const button = host.querySelector('button');
expect(document.activeElement).not.toBe(button);
host.focus();
expect(document.activeElement).toBe(button);
});
});
describe('with tokens to hide checkmark selection indicators', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
MatButtonToggleModule,
ButtonTogglesInsideButtonToggleGroup,
ButtonTogglesInsideButtonToggleGroupMultiple,
],
providers: [
{
provide: MAT_BUTTON_TOGGLE_DEFAULT_OPTIONS,
useValue: {
hideSingleSelectionIndicator: true,
hideMultipleSelectionIndicator: true,
},
},
],
});
});
it('should hide checkmark indicator for single selection', () => {
const fixture = TestBed.createComponent(ButtonTogglesInsideButtonToggleGroup);
fixture.detectChanges();
fixture.debugElement.query(By.css('button')).nativeElement.click();
fixture.detectChanges();
expect(document.querySelectorAll('.mat-pseudo-checkbox').length).toBe(0);
});
it('should hide checkmark indicator for multiple selection', () => {
const fixture = TestBed.createComponent(ButtonTogglesInsideButtonToggleGroupMultiple);
fixture.detectChanges();
// Check all button toggles in the group
fixture.debugElement
.queryAll(By.css('button'))
.forEach(toggleButton => toggleButton.nativeElement.click());
fixture.detectChanges();
expect(document.querySelectorAll('.mat-pseudo-checkbox').length).toBe(0);
});
});
it('should not throw on init when toggles are repeated and there is an initial value', () => {
const fixture = TestBed.createComponent(RepeatedButtonTogglesWithPreselectedValue);
expect(() => fixture.detectChanges()).not.toThrow();
expect(fixture.componentInstance.toggleGroup.value).toBe('Two');
expect(fixture.componentInstance.toggles.toArray()[1].checked).toBe(true);
});
it('should not throw on init when toggles are repeated and there is an initial value', () => {
const fixture = TestBed.createComponent(ButtonToggleWithStaticName);
fixture.detectChanges();
const hostNode: HTMLElement = fixture.nativeElement.querySelector('.mat-button-toggle');
expect(hostNode.hasAttribute('name')).toBe(false);
expect(hostNode.querySelector('button')!.getAttribute('name')).toBe('custom-name');
});
it(
'should maintain the selected state when the value and toggles are swapped out at ' +
'the same time',
() => {
const fixture = TestBed.createComponent(RepeatedButtonTogglesWithPreselectedValue);
fixture.detectChanges();
expect(fixture.componentInstance.toggleGroup.value).toBe('Two');
expect(fixture.componentInstance.toggles.toArray()[1].checked).toBe(true);
fixture.componentInstance.possibleValues = ['Five', 'Six', 'Seven'];
fixture.componentInstance.value = 'Seven';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.toggleGroup.value).toBe('Seven');
expect(fixture.componentInstance.toggles.toArray()[2].checked).toBe(true);
},
);
it('should select falsy button toggle value in multiple selection', () => {
const fixture = TestBed.createComponent(FalsyButtonTogglesInsideButtonToggleGroupMultiple);
fixture.detectChanges();
expect(fixture.componentInstance.toggles.toArray()[0].checked).toBe(true);
expect(fixture.componentInstance.toggles.toArray()[1].checked).toBe(false);
expect(fixture.componentInstance.toggles.toArray()[2].checked).toBe(false);
fixture.componentInstance.value = [0, false];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.toggles.toArray()[0].checked).toBe(true);
expect(fixture.componentInstance.toggles.toArray()[1].checked).toBe(false);
expect(fixture.componentInstance.toggles.toArray()[2].checked).toBe(true);
});
it('should not throw if initial value is set during creation', () => {
const fixture = TestBed.createComponent(ButtonTogglesInsideButtonToggleGroupMultiple);
// In Ivy static inputs are set during creation. We simulate this by not calling
// `fixture.detectChanges` immediately, but getting a hold of the instance via the
// DebugElement and setting the value ourselves.
expect(() => {
const toggle = fixture.debugElement.query(By.css('mat-button-toggle'))!.componentInstance;
toggle.checked = true;
fixture.detectChanges();
}).not.toThrow();
});
it('should have a focus indicator', () => {
const fixture = TestBed.createComponent(ButtonTogglesInsideButtonToggleGroup);
const buttonNativeElements = [...fixture.debugElement.nativeElement.querySelectorAll('button')];
expect(
buttonNativeElements.every(element => element.classList.contains('mat-focus-indicator')),
).toBe(true);
});
it('should be able to pre-check a button toggle using a static checked binding', () => {
const fixture = TestBed.createComponent(ButtonToggleWithStaticChecked);
fixture.detectChanges();
expect(fixture.componentInstance.toggles.map(t => t.checked)).toEqual([false, true]);
expect(fixture.componentInstance.group.value).toBe('2');
});
});
@Component({
template: `
<mat-button-toggle-group
[disabled]="isGroupDisabled"
[disabledInteractive]="disabledIntearctive"
[vertical]="isVertical"
[(value)]="groupValue">
@if (renderFirstToggle) {
<mat-button-toggle value="test1">Test1</mat-button-toggle>
}
<mat-button-toggle value="test2">Test2</mat-button-toggle>
<mat-button-toggle value="test3">Test3</mat-button-toggle>
</mat-button-toggle-group>
`,
standalone: true,
imports: [MatButtonToggleModule],
})
class ButtonTogglesInsideButtonToggleGroup {
isGroupDisabled: boolean = false;
disabledIntearctive = false;
isVertical: boolean = false;
groupValue: string;
renderFirstToggle = true;
} | {
"end_byte": 41013,
"start_byte": 31268,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.spec.ts"
} |
components/src/material/button-toggle/button-toggle.spec.ts_41015_47225 | @Component({
template: `
<mat-button-toggle-group
[name]="groupName"
[(ngModel)]="modelValue"
(change)="lastEvent = $event">
@for (option of options; track option) {
<mat-button-toggle
[value]="option.value"
[disableRipple]="disableRipple"
[name]="option.name">{{option.label}}</mat-button-toggle>
}
</mat-button-toggle-group>
`,
standalone: true,
imports: [MatButtonToggleModule, FormsModule, ReactiveFormsModule],
})
class ButtonToggleGroupWithNgModel {
groupName = 'group-name';
modelValue: string;
options = [
{label: 'Red', value: 'red', name: ''},
{label: 'Green', value: 'green', name: ''},
{label: 'Blue', value: 'blue', name: ''},
];
lastEvent: MatButtonToggleChange;
disableRipple = false;
}
@Component({
template: `
<mat-button-toggle-group [disabled]="isGroupDisabled" [vertical]="isVertical" multiple>
<mat-button-toggle value="eggs">Eggs</mat-button-toggle>
<mat-button-toggle value="flour">Flour</mat-button-toggle>
<mat-button-toggle value="sugar">Sugar</mat-button-toggle>
</mat-button-toggle-group>
`,
standalone: true,
imports: [MatButtonToggleModule],
})
class ButtonTogglesInsideButtonToggleGroupMultiple {
isGroupDisabled: boolean = false;
isVertical: boolean = false;
}
@Component({
template: `
<mat-button-toggle-group multiple [value]="value">
<mat-button-toggle [value]="0">Eggs</mat-button-toggle>
<mat-button-toggle [value]="null">Flour</mat-button-toggle>
<mat-button-toggle [value]="false">Sugar</mat-button-toggle>
<mat-button-toggle>Sugar</mat-button-toggle>
</mat-button-toggle-group>
`,
standalone: true,
imports: [MatButtonToggleModule],
})
class FalsyButtonTogglesInsideButtonToggleGroupMultiple {
value: ('' | number | null | undefined | boolean)[] = [0];
@ViewChildren(MatButtonToggle) toggles: QueryList<MatButtonToggle>;
}
@Component({
template: `
<mat-button-toggle>Yes</mat-button-toggle>
`,
standalone: true,
imports: [MatButtonToggleModule],
})
class StandaloneButtonToggle {}
@Component({
template: `
<mat-button-toggle-group (change)="lastEvent = $event" value="red">
<mat-button-toggle value="red">Value Red</mat-button-toggle>
<mat-button-toggle value="green">Value Green</mat-button-toggle>
</mat-button-toggle-group>
`,
standalone: true,
imports: [MatButtonToggleModule],
})
class ButtonToggleGroupWithInitialValue {
lastEvent: MatButtonToggleChange;
}
@Component({
template: `
<mat-button-toggle-group [formControl]="control">
<mat-button-toggle value="red">Value Red</mat-button-toggle>
<mat-button-toggle value="green">Value Green</mat-button-toggle>
<mat-button-toggle value="blue">Value Blue</mat-button-toggle>
</mat-button-toggle-group>
`,
standalone: true,
imports: [MatButtonToggleModule, FormsModule, ReactiveFormsModule],
})
class ButtonToggleGroupWithFormControl {
control = new FormControl('');
}
@Component({
// We need the `@if` so that there's a container between the group and the toggles.
template: `
<mat-button-toggle-group [formControl]="control">
@if (true) {
<mat-button-toggle value="red">Value Red</mat-button-toggle>
<mat-button-toggle value="green">Value Green</mat-button-toggle>
<mat-button-toggle value="blue">Value Blue</mat-button-toggle>
}
</mat-button-toggle-group>
`,
standalone: true,
imports: [MatButtonToggleModule, FormsModule, ReactiveFormsModule],
})
class ButtonToggleGroupWithIndirectDescendantToggles {
control = new FormControl('');
}
/** Simple test component with an aria-label set. */
@Component({
template: `<mat-button-toggle aria-label="Super effective"></mat-button-toggle>`,
standalone: true,
imports: [MatButtonToggleModule],
})
class ButtonToggleWithAriaLabel {}
/** Simple test component with an aria-label set. */
@Component({
template: `<mat-button-toggle aria-labelledby="some-id"></mat-button-toggle>`,
standalone: true,
imports: [MatButtonToggleModule],
})
class ButtonToggleWithAriaLabelledby {}
@Component({
template: `
<mat-button-toggle-group [(value)]="value">
@for (toggle of possibleValues; track toggle) {
<mat-button-toggle [value]="toggle">{{toggle}}</mat-button-toggle>
}
</mat-button-toggle-group>
`,
standalone: true,
imports: [MatButtonToggleModule],
})
class RepeatedButtonTogglesWithPreselectedValue {
@ViewChild(MatButtonToggleGroup) toggleGroup: MatButtonToggleGroup;
@ViewChildren(MatButtonToggle) toggles: QueryList<MatButtonToggle>;
possibleValues = ['One', 'Two', 'Three'];
value = 'Two';
}
@Component({
template: `<mat-button-toggle tabindex="3"></mat-button-toggle>`,
standalone: true,
imports: [MatButtonToggleModule],
})
class ButtonToggleWithTabindex {}
@Component({
template: `<mat-button-toggle name="custom-name"></mat-button-toggle>`,
standalone: true,
imports: [MatButtonToggleModule],
})
class ButtonToggleWithStaticName {}
@Component({
template: `
<mat-button-toggle-group>
<mat-button-toggle value="1">One</mat-button-toggle>
<mat-button-toggle value="2" checked>Two</mat-button-toggle>
</mat-button-toggle-group>
`,
standalone: true,
imports: [MatButtonToggleModule],
})
class ButtonToggleWithStaticChecked {
@ViewChild(MatButtonToggleGroup) group: MatButtonToggleGroup;
@ViewChildren(MatButtonToggle) toggles: QueryList<MatButtonToggle>;
}
@Component({
template: `
<mat-button-toggle aria-label="Toggle me" aria-labelledby="something"></mat-button-toggle>
`,
standalone: true,
imports: [MatButtonToggleModule],
})
class ButtonToggleWithStaticAriaAttributes {}
@Component({
template: `
<mat-button-toggle-group [formControl]="control">
@for (value of values; track value) {
<mat-button-toggle [value]="value">{{value}}</mat-button-toggle>
}
</mat-button-toggle-group>
`,
standalone: true,
imports: [MatButtonToggleModule, FormsModule, ReactiveFormsModule],
})
class ButtonToggleGroupWithFormControlAndDynamicButtons {
@ViewChildren(MatButtonToggle) toggles: QueryList<MatButtonToggle>;
control = new FormControl('');
values = ['a', 'b', 'c'];
} | {
"end_byte": 47225,
"start_byte": 41015,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.spec.ts"
} |
components/src/material/button-toggle/BUILD.bazel_0_1629 | 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 = "button-toggle",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [":button-toggle.css"] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/cdk/a11y",
"//src/cdk/collections",
"//src/material/core",
"@npm//@angular/core",
"@npm//@angular/forms",
],
)
sass_library(
name = "button_toggle_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/cdk/a11y:a11y_scss_lib",
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "button_toggle_scss",
src = "button-toggle.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":button-toggle",
"//src/cdk/testing",
"//src/cdk/testing/private",
"@npm//@angular/common",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [":button-toggle.md"],
)
extract_tokens(
name = "tokens",
srcs = [":button_toggle_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1629,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/BUILD.bazel"
} |
components/src/material/button-toggle/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';
| {
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/index.ts"
} |
components/src/material/button-toggle/_button-toggle-theme.scss_0_5789 | @use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
@use '../core/tokens/m2/mat/legacy-button-toggle' as tokens-mat-legacy-button-toggle;
@use '../core/tokens/m2/mat/standard-button-toggle' as tokens-mat-standard-button-toggle;
@use '../core/tokens/token-utils';
@use '../core/style/sass-utils';
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-button-toggle.
/// @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-mat-legacy-button-toggle.$prefix,
tokens-mat-legacy-button-toggle.get-unthemable-tokens()
);
@include token-utils.create-token-values(
tokens-mat-standard-button-toggle.$prefix,
tokens-mat-standard-button-toggle.get-unthemable-tokens()
);
}
}
}
/// Outputs color theme styles for the mat-button-toggle.
/// @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 button toggle: primary, secondary, tertiary,
/// or error (If not specified, default secondary 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 {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-legacy-button-toggle.$prefix,
tokens-mat-legacy-button-toggle.get-color-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-standard-button-toggle.$prefix,
tokens-mat-standard-button-toggle.get-color-tokens($theme)
);
}
}
}
/// Outputs typography theme styles for the mat-button-toggle.
/// @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-mat-legacy-button-toggle.$prefix,
tokens-mat-legacy-button-toggle.get-typography-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-standard-button-toggle.$prefix,
tokens-mat-standard-button-toggle.get-typography-tokens($theme)
);
}
}
}
/// Outputs density theme styles for the mat-button-toggle.
/// @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 {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-legacy-button-toggle.$prefix,
tokens-mat-legacy-button-toggle.get-density-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-standard-button-toggle.$prefix,
tokens-mat-standard-button-toggle.get-density-tokens($theme)
);
}
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
$legacy-tokens: tokens-mat-legacy-button-toggle.get-token-slots();
$standard-tokens: tokens-mat-standard-button-toggle.get-token-slots();
@return (
(
namespace: tokens-mat-legacy-button-toggle.$prefix,
tokens: $legacy-tokens,
prefix: 'legacy-',
),
(
namespace: tokens-mat-standard-button-toggle.$prefix,
tokens: $standard-tokens,
),
);
}
/// 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-button-toggle.
/// @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 button toggle: primary, secondary, tertiary,
/// or error (If not specified, default secondary color will be used).
@mixin theme($theme, $options...) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-button-toggle') {
@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'
);
$mat-standard-button-toggle-tokens: token-utils.get-tokens-for(
$tokens,
tokens-mat-standard-button-toggle.$prefix,
$options...
);
@include token-utils.create-token-values(
tokens-mat-standard-button-toggle.$prefix,
$mat-standard-button-toggle-tokens
);
}
| {
"end_byte": 5789,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/_button-toggle-theme.scss"
} |
components/src/material/button-toggle/button-toggle.ts_0_3786 | /**
* @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} from '@angular/cdk/a11y';
import {SelectionModel} from '@angular/cdk/collections';
import {DOWN_ARROW, LEFT_ARROW, RIGHT_ARROW, UP_ARROW, SPACE, ENTER} from '@angular/cdk/keycodes';
import {
AfterContentInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
Directive,
ElementRef,
EventEmitter,
forwardRef,
Input,
OnDestroy,
OnInit,
Output,
QueryList,
ViewChild,
ViewEncapsulation,
InjectionToken,
AfterViewInit,
booleanAttribute,
inject,
HostAttributeToken,
} from '@angular/core';
import {Direction, Directionality} from '@angular/cdk/bidi';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {MatRipple, MatPseudoCheckbox, _StructuralStylesLoader} from '@angular/material/core';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
/**
* @deprecated No longer used.
* @breaking-change 11.0.0
*/
export type ToggleType = 'checkbox' | 'radio';
/** Possible appearance styles for the button toggle. */
export type MatButtonToggleAppearance = 'legacy' | 'standard';
/**
* Represents the default options for the button toggle that can be configured
* using the `MAT_BUTTON_TOGGLE_DEFAULT_OPTIONS` injection token.
*/
export interface MatButtonToggleDefaultOptions {
/**
* Default appearance to be used by button toggles. Can be overridden by explicitly
* setting an appearance on a button toggle or group.
*/
appearance?: MatButtonToggleAppearance;
/** Whetehr icon indicators should be hidden for single-selection button toggle groups. */
hideSingleSelectionIndicator?: boolean;
/** Whether icon indicators should be hidden for multiple-selection button toggle groups. */
hideMultipleSelectionIndicator?: boolean;
/** Whether disabled toggle buttons should be interactive. */
disabledInteractive?: boolean;
}
/**
* Injection token that can be used to configure the
* default options for all button toggles within an app.
*/
export const MAT_BUTTON_TOGGLE_DEFAULT_OPTIONS = new InjectionToken<MatButtonToggleDefaultOptions>(
'MAT_BUTTON_TOGGLE_DEFAULT_OPTIONS',
{
providedIn: 'root',
factory: MAT_BUTTON_TOGGLE_GROUP_DEFAULT_OPTIONS_FACTORY,
},
);
export function MAT_BUTTON_TOGGLE_GROUP_DEFAULT_OPTIONS_FACTORY(): MatButtonToggleDefaultOptions {
return {
hideSingleSelectionIndicator: false,
hideMultipleSelectionIndicator: false,
disabledInteractive: false,
};
}
/**
* Injection token that can be used to reference instances of `MatButtonToggleGroup`.
* It serves as alternative token to the actual `MatButtonToggleGroup` class which
* could cause unnecessary retention of the class and its component metadata.
*/
export const MAT_BUTTON_TOGGLE_GROUP = new InjectionToken<MatButtonToggleGroup>(
'MatButtonToggleGroup',
);
/**
* Provider Expression that allows mat-button-toggle-group to register as a ControlValueAccessor.
* This allows it to support [(ngModel)].
* @docs-private
*/
export const MAT_BUTTON_TOGGLE_GROUP_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatButtonToggleGroup),
multi: true,
};
// Counter used to generate unique IDs.
let uniqueIdCounter = 0;
/** Change event object emitted by button toggle. */
export class MatButtonToggleChange {
constructor(
/** The button toggle that emits the event. */
public source: MatButtonToggle,
/** The value assigned to the button toggle. */
public value: any,
) {}
}
/** Exclusive selection button toggle group that behaves like a radio-button group. */ | {
"end_byte": 3786,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.ts"
} |
components/src/material/button-toggle/button-toggle.ts_3787_12255 | @Directive({
selector: 'mat-button-toggle-group',
providers: [
MAT_BUTTON_TOGGLE_GROUP_VALUE_ACCESSOR,
{provide: MAT_BUTTON_TOGGLE_GROUP, useExisting: MatButtonToggleGroup},
],
host: {
'class': 'mat-button-toggle-group',
'(keydown)': '_keydown($event)',
'[attr.role]': "multiple ? 'group' : 'radiogroup'",
'[attr.aria-disabled]': 'disabled',
'[class.mat-button-toggle-vertical]': 'vertical',
'[class.mat-button-toggle-group-appearance-standard]': 'appearance === "standard"',
},
exportAs: 'matButtonToggleGroup',
})
export class MatButtonToggleGroup implements ControlValueAccessor, OnInit, AfterContentInit {
private _changeDetector = inject(ChangeDetectorRef);
private _dir = inject(Directionality, {optional: true});
private _multiple = false;
private _disabled = false;
private _disabledInteractive = false;
private _selectionModel: SelectionModel<MatButtonToggle>;
/**
* Reference to the raw value that the consumer tried to assign. The real
* value will exclude any values from this one that don't correspond to a
* toggle. Useful for the cases where the value is assigned before the toggles
* have been initialized or at the same that they're being swapped out.
*/
private _rawValue: any;
/**
* The method to be called in order to update ngModel.
* Now `ngModel` binding is not supported in multiple selection mode.
*/
_controlValueAccessorChangeFn: (value: any) => void = () => {};
/** onTouch function registered via registerOnTouch (ControlValueAccessor). */
_onTouched: () => any = () => {};
/** Child button toggle buttons. */
@ContentChildren(forwardRef(() => MatButtonToggle), {
// Note that this would technically pick up toggles
// from nested groups, but that's not a case that we support.
descendants: true,
})
_buttonToggles: QueryList<MatButtonToggle>;
/** The appearance for all the buttons in the group. */
@Input() appearance: MatButtonToggleAppearance;
/** `name` attribute for the underlying `input` element. */
@Input()
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value;
this._markButtonsForCheck();
}
private _name = `mat-button-toggle-group-${uniqueIdCounter++}`;
/** Whether the toggle group is vertical. */
@Input({transform: booleanAttribute}) vertical: boolean;
/** Value of the toggle group. */
@Input()
get value(): any {
const selected = this._selectionModel ? this._selectionModel.selected : [];
if (this.multiple) {
return selected.map(toggle => toggle.value);
}
return selected[0] ? selected[0].value : undefined;
}
set value(newValue: any) {
this._setSelectionByValue(newValue);
this.valueChange.emit(this.value);
}
/**
* Event that emits whenever the value of the group changes.
* Used to facilitate two-way data binding.
* @docs-private
*/
@Output() readonly valueChange = new EventEmitter<any>();
/** Selected button toggles in the group. */
get selected(): MatButtonToggle | MatButtonToggle[] {
const selected = this._selectionModel ? this._selectionModel.selected : [];
return this.multiple ? selected : selected[0] || null;
}
/** Whether multiple button toggles can be selected. */
@Input({transform: booleanAttribute})
get multiple(): boolean {
return this._multiple;
}
set multiple(value: boolean) {
this._multiple = value;
this._markButtonsForCheck();
}
/** Whether multiple button toggle group is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this._disabled;
}
set disabled(value: boolean) {
this._disabled = value;
this._markButtonsForCheck();
}
/** 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._markButtonsForCheck();
}
/** The layout direction of the toggle button group. */
get dir(): Direction {
return this._dir && this._dir.value === 'rtl' ? 'rtl' : 'ltr';
}
/** Event emitted when the group's value changes. */
@Output() readonly change: EventEmitter<MatButtonToggleChange> =
new EventEmitter<MatButtonToggleChange>();
/** Whether checkmark indicator for single-selection button toggle groups is hidden. */
@Input({transform: booleanAttribute})
get hideSingleSelectionIndicator(): boolean {
return this._hideSingleSelectionIndicator;
}
set hideSingleSelectionIndicator(value: boolean) {
this._hideSingleSelectionIndicator = value;
this._markButtonsForCheck();
}
private _hideSingleSelectionIndicator: boolean;
/** Whether checkmark indicator for multiple-selection button toggle groups is hidden. */
@Input({transform: booleanAttribute})
get hideMultipleSelectionIndicator(): boolean {
return this._hideMultipleSelectionIndicator;
}
set hideMultipleSelectionIndicator(value: boolean) {
this._hideMultipleSelectionIndicator = value;
this._markButtonsForCheck();
}
private _hideMultipleSelectionIndicator: boolean;
constructor(...args: unknown[]);
constructor() {
const defaultOptions = inject<MatButtonToggleDefaultOptions>(
MAT_BUTTON_TOGGLE_DEFAULT_OPTIONS,
{optional: true},
);
this.appearance =
defaultOptions && defaultOptions.appearance ? defaultOptions.appearance : 'standard';
this.hideSingleSelectionIndicator = defaultOptions?.hideSingleSelectionIndicator ?? false;
this.hideMultipleSelectionIndicator = defaultOptions?.hideMultipleSelectionIndicator ?? false;
}
ngOnInit() {
this._selectionModel = new SelectionModel<MatButtonToggle>(this.multiple, undefined, false);
}
ngAfterContentInit() {
this._selectionModel.select(...this._buttonToggles.filter(toggle => toggle.checked));
if (!this.multiple) {
this._initializeTabIndex();
}
}
/**
* Sets the model value. Implemented as part of ControlValueAccessor.
* @param value Value to be set to the model.
*/
writeValue(value: any) {
this.value = value;
this._changeDetector.markForCheck();
}
// Implemented as part of ControlValueAccessor.
registerOnChange(fn: (value: any) => void) {
this._controlValueAccessorChangeFn = fn;
}
// Implemented as part of ControlValueAccessor.
registerOnTouched(fn: any) {
this._onTouched = fn;
}
// Implemented as part of ControlValueAccessor.
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
/** Handle keydown event calling to single-select button toggle. */
protected _keydown(event: KeyboardEvent) {
if (this.multiple || this.disabled) {
return;
}
const target = event.target as HTMLButtonElement;
const buttonId = target.id;
const index = this._buttonToggles.toArray().findIndex(toggle => {
return toggle.buttonId === buttonId;
});
let nextButton: MatButtonToggle | null = null;
switch (event.keyCode) {
case SPACE:
case ENTER:
nextButton = this._buttonToggles.get(index) || null;
break;
case UP_ARROW:
nextButton = this._getNextButton(index, -1);
break;
case LEFT_ARROW:
nextButton = this._getNextButton(index, this.dir === 'ltr' ? -1 : 1);
break;
case DOWN_ARROW:
nextButton = this._getNextButton(index, 1);
break;
case RIGHT_ARROW:
nextButton = this._getNextButton(index, this.dir === 'ltr' ? 1 : -1);
break;
default:
return;
}
if (nextButton) {
event.preventDefault();
nextButton._onButtonClick();
nextButton.focus();
}
}
/** Dispatch change event with current selection and group value. */
_emitChangeEvent(toggle: MatButtonToggle): void {
const event = new MatButtonToggleChange(toggle, this.value);
this._rawValue = event.value;
this._controlValueAccessorChangeFn(event.value);
this.change.emit(event);
}
/**
* Syncs a button toggle's selected state with the model value.
* @param toggle Toggle to be synced.
* @param select Whether the toggle should be selected.
* @param isUserInput Whether the change was a result of a user interaction.
* @param deferEvents Whether to defer emitting the change events.
*/ | {
"end_byte": 12255,
"start_byte": 3787,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.ts"
} |
components/src/material/button-toggle/button-toggle.ts_12258_17058 | _syncButtonToggle(
toggle: MatButtonToggle,
select: boolean,
isUserInput = false,
deferEvents = false,
) {
// Deselect the currently-selected toggle, if we're in single-selection
// mode and the button being toggled isn't selected at the moment.
if (!this.multiple && this.selected && !toggle.checked) {
(this.selected as MatButtonToggle).checked = false;
}
if (this._selectionModel) {
if (select) {
this._selectionModel.select(toggle);
} else {
this._selectionModel.deselect(toggle);
}
} else {
deferEvents = true;
}
// We need to defer in some cases in order to avoid "changed after checked errors", however
// the side-effect is that we may end up updating the model value out of sequence in others
// The `deferEvents` flag allows us to decide whether to do it on a case-by-case basis.
if (deferEvents) {
Promise.resolve().then(() => this._updateModelValue(toggle, isUserInput));
} else {
this._updateModelValue(toggle, isUserInput);
}
}
/** Checks whether a button toggle is selected. */
_isSelected(toggle: MatButtonToggle) {
return this._selectionModel && this._selectionModel.isSelected(toggle);
}
/** Determines whether a button toggle should be checked on init. */
_isPrechecked(toggle: MatButtonToggle) {
if (typeof this._rawValue === 'undefined') {
return false;
}
if (this.multiple && Array.isArray(this._rawValue)) {
return this._rawValue.some(value => toggle.value != null && value === toggle.value);
}
return toggle.value === this._rawValue;
}
/** Initializes the tabindex attribute using the radio pattern. */
private _initializeTabIndex() {
this._buttonToggles.forEach(toggle => {
toggle.tabIndex = -1;
});
if (this.selected) {
(this.selected as MatButtonToggle).tabIndex = 0;
} else {
for (let i = 0; i < this._buttonToggles.length; i++) {
const toggle = this._buttonToggles.get(i)!;
if (!toggle.disabled) {
toggle.tabIndex = 0;
break;
}
}
}
this._markButtonsForCheck();
}
/** Obtain the subsequent toggle to which the focus shifts. */
private _getNextButton(startIndex: number, offset: number): MatButtonToggle | null {
const items = this._buttonToggles;
for (let i = 1; i <= items.length; i++) {
const index = (startIndex + offset * i + items.length) % items.length;
const item = items.get(index);
if (item && !item.disabled) {
return item;
}
}
return null;
}
/** Updates the selection state of the toggles in the group based on a value. */
private _setSelectionByValue(value: any | any[]) {
this._rawValue = value;
if (!this._buttonToggles) {
return;
}
if (this.multiple && value) {
if (!Array.isArray(value) && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('Value must be an array in multiple-selection mode.');
}
this._clearSelection();
value.forEach((currentValue: any) => this._selectValue(currentValue));
} else {
this._clearSelection();
this._selectValue(value);
}
}
/** Clears the selected toggles. */
private _clearSelection() {
this._selectionModel.clear();
this._buttonToggles.forEach(toggle => {
toggle.checked = false;
// If the button toggle is in single select mode, initialize the tabIndex.
if (!this.multiple) {
toggle.tabIndex = -1;
}
});
}
/** Selects a value if there's a toggle that corresponds to it. */
private _selectValue(value: any) {
const correspondingOption = this._buttonToggles.find(toggle => {
return toggle.value != null && toggle.value === value;
});
if (correspondingOption) {
correspondingOption.checked = true;
this._selectionModel.select(correspondingOption);
if (!this.multiple) {
// If the button toggle is in single select mode, reset the tabIndex.
correspondingOption.tabIndex = 0;
}
}
}
/** Syncs up the group's value with the model and emits the change event. */
private _updateModelValue(toggle: MatButtonToggle, isUserInput: boolean) {
// Only emit the change event for user input.
if (isUserInput) {
this._emitChangeEvent(toggle);
}
// Note: we emit this one no matter whether it was a user interaction, because
// it is used by Angular to sync up the two-way data binding.
this.valueChange.emit(this.value);
}
/** Marks all of the child button toggles to be checked. */
private _markButtonsForCheck() {
this._buttonToggles?.forEach(toggle => toggle._markForCheck());
}
}
/** Single button inside of a toggle group. */ | {
"end_byte": 17058,
"start_byte": 12258,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.ts"
} |
components/src/material/button-toggle/button-toggle.ts_17059_25216 | @Component({
selector: 'mat-button-toggle',
templateUrl: 'button-toggle.html',
styleUrl: 'button-toggle.css',
encapsulation: ViewEncapsulation.None,
exportAs: 'matButtonToggle',
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'[class.mat-button-toggle-standalone]': '!buttonToggleGroup',
'[class.mat-button-toggle-checked]': 'checked',
'[class.mat-button-toggle-disabled]': 'disabled',
'[class.mat-button-toggle-disabled-interactive]': 'disabledInteractive',
'[class.mat-button-toggle-appearance-standard]': 'appearance === "standard"',
'class': 'mat-button-toggle',
'[attr.aria-label]': 'null',
'[attr.aria-labelledby]': 'null',
'[attr.id]': 'id',
'[attr.name]': 'null',
'(focus)': 'focus()',
'role': 'presentation',
},
imports: [MatRipple, MatPseudoCheckbox],
})
export class MatButtonToggle implements OnInit, AfterViewInit, OnDestroy {
private _changeDetectorRef = inject(ChangeDetectorRef);
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _focusMonitor = inject(FocusMonitor);
private _checked = false;
/**
* Attached to the aria-label attribute of the host element. In most cases, aria-labelledby will
* take precedence so this may be omitted.
*/
@Input('aria-label') ariaLabel: string;
/**
* Users can specify the `aria-labelledby` attribute which will be forwarded to the input element
*/
@Input('aria-labelledby') ariaLabelledby: string | null = null;
/** Underlying native `button` element. */
@ViewChild('button') _buttonElement: ElementRef<HTMLButtonElement>;
/** The parent button toggle group (exclusive selection). Optional. */
buttonToggleGroup: MatButtonToggleGroup;
/** Unique ID for the underlying `button` element. */
get buttonId(): string {
return `${this.id}-button`;
}
/** The unique ID for this button toggle. */
@Input() id: string;
/** HTML's 'name' attribute used to group radios for unique selection. */
@Input() name: string;
/** MatButtonToggleGroup reads this to assign its own value. */
@Input() value: any;
/** Tabindex of the toggle. */
@Input()
get tabIndex(): number | null {
return this._tabIndex;
}
set tabIndex(value: number | null) {
this._tabIndex = value;
this._markForCheck();
}
private _tabIndex: number | null;
/** Whether ripples are disabled on the button toggle. */
@Input({transform: booleanAttribute}) disableRipple: boolean;
/** The appearance style of the button. */
@Input()
get appearance(): MatButtonToggleAppearance {
return this.buttonToggleGroup ? this.buttonToggleGroup.appearance : this._appearance;
}
set appearance(value: MatButtonToggleAppearance) {
this._appearance = value;
}
private _appearance: MatButtonToggleAppearance;
/** Whether the button is checked. */
@Input({transform: booleanAttribute})
get checked(): boolean {
return this.buttonToggleGroup ? this.buttonToggleGroup._isSelected(this) : this._checked;
}
set checked(value: boolean) {
if (value !== this._checked) {
this._checked = value;
if (this.buttonToggleGroup) {
this.buttonToggleGroup._syncButtonToggle(this, this._checked);
}
this._changeDetectorRef.markForCheck();
}
}
/** Whether the button is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this._disabled || (this.buttonToggleGroup && this.buttonToggleGroup.disabled);
}
set disabled(value: boolean) {
this._disabled = value;
}
private _disabled: boolean = false;
/** Whether the button should remain interactive when it is disabled. */
@Input({transform: booleanAttribute})
get disabledInteractive(): boolean {
return (
this._disabledInteractive ||
(this.buttonToggleGroup !== null && this.buttonToggleGroup.disabledInteractive)
);
}
set disabledInteractive(value: boolean) {
this._disabledInteractive = value;
}
private _disabledInteractive: boolean;
/** Event emitted when the group value changes. */
@Output() readonly change: EventEmitter<MatButtonToggleChange> =
new EventEmitter<MatButtonToggleChange>();
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
const toggleGroup = inject<MatButtonToggleGroup>(MAT_BUTTON_TOGGLE_GROUP, {optional: true})!;
const defaultTabIndex = inject(new HostAttributeToken('tabindex'), {optional: true});
const defaultOptions = inject<MatButtonToggleDefaultOptions>(
MAT_BUTTON_TOGGLE_DEFAULT_OPTIONS,
{optional: true},
);
const parsedTabIndex = Number(defaultTabIndex);
this.tabIndex = parsedTabIndex || parsedTabIndex === 0 ? parsedTabIndex : null;
this.buttonToggleGroup = toggleGroup;
this.appearance =
defaultOptions && defaultOptions.appearance ? defaultOptions.appearance : 'standard';
this.disabledInteractive = defaultOptions?.disabledInteractive ?? false;
}
ngOnInit() {
const group = this.buttonToggleGroup;
this.id = this.id || `mat-button-toggle-${uniqueIdCounter++}`;
if (group) {
if (group._isPrechecked(this)) {
this.checked = true;
} else if (group._isSelected(this) !== this._checked) {
// As side effect of the circular dependency between the toggle group and the button,
// we may end up in a state where the button is supposed to be checked on init, but it
// isn't, because the checked value was assigned too early. This can happen when Ivy
// assigns the static input value before the `ngOnInit` has run.
group._syncButtonToggle(this, this._checked);
}
}
}
ngAfterViewInit() {
this._focusMonitor.monitor(this._elementRef, true);
}
ngOnDestroy() {
const group = this.buttonToggleGroup;
this._focusMonitor.stopMonitoring(this._elementRef);
// Remove the toggle from the selection once it's destroyed. Needs to happen
// on the next tick in order to avoid "changed after checked" errors.
if (group && group._isSelected(this)) {
group._syncButtonToggle(this, false, false, true);
}
}
/** Focuses the button. */
focus(options?: FocusOptions): void {
this._buttonElement.nativeElement.focus(options);
}
/** Checks the button toggle due to an interaction with the underlying native button. */
_onButtonClick() {
if (this.disabled) {
return;
}
const newChecked = this.isSingleSelector() ? true : !this._checked;
if (newChecked !== this._checked) {
this._checked = newChecked;
if (this.buttonToggleGroup) {
this.buttonToggleGroup._syncButtonToggle(this, this._checked, true);
this.buttonToggleGroup._onTouched();
}
}
if (this.isSingleSelector()) {
const focusable = this.buttonToggleGroup._buttonToggles.find(toggle => {
return toggle.tabIndex === 0;
});
// Modify the tabindex attribute of the last focusable button toggle to -1.
if (focusable) {
focusable.tabIndex = -1;
}
// Modify the tabindex attribute of the presently selected button toggle to 0.
this.tabIndex = 0;
}
// Emit a change event when it's the single selector
this.change.emit(new MatButtonToggleChange(this, this.value));
}
/**
* Marks the button toggle as needing checking for change detection.
* This method is exposed because the parent button toggle group will directly
* update bound properties of the radio button.
*/
_markForCheck() {
// When the group value changes, the button will not be notified.
// Use `markForCheck` to explicit update button toggle's status.
this._changeDetectorRef.markForCheck();
}
/** Gets the name that should be assigned to the inner DOM node. */
_getButtonName(): string | null {
if (this.isSingleSelector()) {
return this.buttonToggleGroup.name;
}
return this.name || null;
}
/** Whether the toggle is in single selection mode. */
isSingleSelector(): boolean {
return this.buttonToggleGroup && !this.buttonToggleGroup.multiple;
}
} | {
"end_byte": 25216,
"start_byte": 17059,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle.ts"
} |
components/src/material/button-toggle/button-toggle-module.ts_0_597 | /**
* @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 {MatButtonToggle, MatButtonToggleGroup} from './button-toggle';
@NgModule({
imports: [MatCommonModule, MatRippleModule, MatButtonToggleGroup, MatButtonToggle],
exports: [MatCommonModule, MatButtonToggleGroup, MatButtonToggle],
})
export class MatButtonToggleModule {}
| {
"end_byte": 597,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/button-toggle-module.ts"
} |
components/src/material/button-toggle/testing/button-toggle-group-harness-filters.ts_0_525 | /**
* @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';
/** Criteria that can be used to filter a list of `MatButtonToggleGroupHarness` instances. */
export interface ButtonToggleGroupHarnessFilters extends BaseHarnessFilters {
/** Only find instances which match the given disabled state. */
disabled?: boolean;
}
| {
"end_byte": 525,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/testing/button-toggle-group-harness-filters.ts"
} |
components/src/material/button-toggle/testing/button-toggle-group-harness.ts_0_2484 | /**
* @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, HarnessPredicate} from '@angular/cdk/testing';
import {MatButtonToggleAppearance} from '@angular/material/button-toggle';
import {ButtonToggleGroupHarnessFilters} from './button-toggle-group-harness-filters';
import {ButtonToggleHarnessFilters} from './button-toggle-harness-filters';
import {MatButtonToggleHarness} from './button-toggle-harness';
/** Harness for interacting with a standard mat-button-toggle in tests. */
export class MatButtonToggleGroupHarness extends ComponentHarness {
/** The selector for the host element of a `MatButton` instance. */
static hostSelector = '.mat-button-toggle-group';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatButtonToggleGroupHarness`
* that meets certain criteria.
* @param options Options for filtering which button toggle instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(
options: ButtonToggleGroupHarnessFilters = {},
): HarnessPredicate<MatButtonToggleGroupHarness> {
return new HarnessPredicate(MatButtonToggleGroupHarness, options).addOption(
'disabled',
options.disabled,
async (harness, disabled) => {
return (await harness.isDisabled()) === disabled;
},
);
}
/**
* Gets the button toggles that are inside the group.
* @param filter Optionally filters which toggles are included.
*/
async getToggles(filter: ButtonToggleHarnessFilters = {}): Promise<MatButtonToggleHarness[]> {
return this.locatorForAll(MatButtonToggleHarness.with(filter))();
}
/** Gets whether the button toggle group is disabled. */
async isDisabled(): Promise<boolean> {
return (await (await this.host()).getAttribute('aria-disabled')) === 'true';
}
/** Gets whether the button toggle group is laid out vertically. */
async isVertical(): Promise<boolean> {
return (await this.host()).hasClass('mat-button-toggle-vertical');
}
/** Gets the appearance that the group is using. */
async getAppearance(): Promise<MatButtonToggleAppearance> {
const host = await this.host();
const className = 'mat-button-toggle-group-appearance-standard';
return (await host.hasClass(className)) ? 'standard' : 'legacy';
}
}
| {
"end_byte": 2484,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/testing/button-toggle-group-harness.ts"
} |
components/src/material/button-toggle/testing/button-toggle-harness.ts_0_4489 | /**
* @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, HarnessPredicate, parallel} from '@angular/cdk/testing';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {MatButtonToggleAppearance} from '@angular/material/button-toggle';
import {ButtonToggleHarnessFilters} from './button-toggle-harness-filters';
/** Harness for interacting with a standard mat-button-toggle in tests. */
export class MatButtonToggleHarness extends ComponentHarness {
/** The selector for the host element of a `MatButton` instance. */
static hostSelector = '.mat-button-toggle';
private _label = this.locatorFor('.mat-button-toggle-label-content');
private _button = this.locatorFor('.mat-button-toggle-button');
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatButtonToggleHarness` that meets
* certain criteria.
* @param options Options for filtering which button toggle instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: ButtonToggleHarnessFilters = {}): HarnessPredicate<MatButtonToggleHarness> {
return new HarnessPredicate(MatButtonToggleHarness, options)
.addOption('text', options.text, (harness, text) =>
HarnessPredicate.stringMatches(harness.getText(), text),
)
.addOption('name', options.name, (harness, name) =>
HarnessPredicate.stringMatches(harness.getName(), name),
)
.addOption(
'checked',
options.checked,
async (harness, checked) => (await harness.isChecked()) === checked,
)
.addOption('disabled', options.disabled, async (harness, disabled) => {
return (await harness.isDisabled()) === disabled;
});
}
/** Gets a boolean promise indicating if the button toggle is checked. */
async isChecked(): Promise<boolean> {
const button = await this._button();
const [checked, pressed] = await parallel(() => [
button.getAttribute('aria-checked'),
button.getAttribute('aria-pressed'),
]);
return coerceBooleanProperty(checked) || coerceBooleanProperty(pressed);
}
/** Gets a boolean promise indicating if the button toggle is disabled. */
async isDisabled(): Promise<boolean> {
const host = await this.host();
return host.hasClass('mat-button-toggle-disabled');
}
/** Gets a promise for the button toggle's name. */
async getName(): Promise<string | null> {
return (await this._button()).getAttribute('name');
}
/** Gets a promise for the button toggle's aria-label. */
async getAriaLabel(): Promise<string | null> {
return (await this._button()).getAttribute('aria-label');
}
/** Gets a promise for the button toggles's aria-labelledby. */
async getAriaLabelledby(): Promise<string | null> {
return (await this._button()).getAttribute('aria-labelledby');
}
/** Gets a promise for the button toggle's text. */
async getText(): Promise<string> {
return (await this._label()).text();
}
/** Gets the appearance that the button toggle is using. */
async getAppearance(): Promise<MatButtonToggleAppearance> {
const host = await this.host();
const className = 'mat-button-toggle-appearance-standard';
return (await host.hasClass(className)) ? 'standard' : 'legacy';
}
/** Focuses the toggle. */
async focus(): Promise<void> {
return (await this._button()).focus();
}
/** Blurs the toggle. */
async blur(): Promise<void> {
return (await this._button()).blur();
}
/** Whether the toggle is focused. */
async isFocused(): Promise<boolean> {
return (await this._button()).isFocused();
}
/** Toggle the checked state of the buttons toggle. */
async toggle(): Promise<void> {
return (await this._button()).click();
}
/**
* Puts the button toggle in a checked state by toggling it if it's
* currently unchecked, or doing nothing if it is already checked.
*/
async check(): Promise<void> {
if (!(await this.isChecked())) {
await this.toggle();
}
}
/**
* Puts the button toggle in an unchecked state by toggling it if it's
* currently checked, or doing nothing if it's already unchecked.
*/
async uncheck(): Promise<void> {
if (await this.isChecked()) {
await this.toggle();
}
}
}
| {
"end_byte": 4489,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/button-toggle/testing/button-toggle-harness.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.