_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material/sort/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/sort/index.ts"
} |
components/src/material/sort/sort.md_0_2919 | The `matSort` and `mat-sort-header` are used, respectively, to add sorting state and display
to tabular data.
<!-- example(sort-overview) -->
### Adding sort to table headers
To add sorting behavior and styling to a set of table headers, add the `<mat-sort-header>` component
to each header and provide an `id` that will identify it. These headers should be contained within a
parent element with the `matSort` directive, which will emit a `matSortChange` event when the user
triggers sorting on the header.
Users can trigger the sort header through a mouse click or keyboard action. When this happens, the
`matSort` will emit a `matSortChange` event that contains the ID of the header triggered and the
direction to sort (`asc` or `desc`).
#### Changing the sort order
By default, a sort header starts its sorting at `asc` and then `desc`. Triggering the sort header
after `desc` will remove sorting.
To reverse the sort order for all headers, set the `matSortStart` to `desc` on the `matSort`
directive. To reverse the order only for a specific header, set the `start` input only on the header
instead.
To prevent the user from clearing the sort state from an already sorted column, set
`matSortDisableClear` to `true` on the `matSort` to affect all headers, or set `disableClear` to
`true` on a specific header.
#### Disabling sorting
If you want to prevent the user from changing the sorting order of any column, you can use the
`matSortDisabled` binding on the `mat-sort`, or the `disabled` on a single `mat-sort-header`.
#### Using sort with the mat-table
When used on a `mat-table` header, it is not required to set a `mat-sort-header` id on because
by default it will use the id of the column.
<!-- example(table-sorting) -->
### Accessibility
When you apply `MatSortHeader` to a header cell element, the component wraps the content of the
header cell inside a button. The text content of the header cell then becomes the accessible
label for the sort button. However, the header cell text typically describes the column and does
not indicate that interacting with the control performs a sorting action. To clearly communicate
that the header performs sorting, always use the `sortActionDescription` input to provide a
description for the button element, such as "Sort by last name".
`MatSortHeader` applies the `aria-sort` attribute to communicate the active sort state to
assistive technology. However, most screen readers do not announce changes to the value of
`aria-sort`, meaning that screen reader users do not receive feedback that sorting occurred. To
remedy this, use the `matSortChange` event on the `MatSort` directive to announce state
updates with the `LiveAnnouncer` service from `@angular/cdk/a11y`.
If your application contains many tables and sort headers, consider creating a custom
directives to consistently apply `sortActionDescription` and announce sort state changes.
| {
"end_byte": 2919,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/sort/sort.md"
} |
components/src/material/sort/testing/sort-harness.ts_0_1514 | /**
* @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 {SortHarnessFilters, SortHeaderHarnessFilters} from './sort-harness-filters';
import {MatSortHeaderHarness} from './sort-header-harness';
/** Harness for interacting with a standard `mat-sort` in tests. */
export class MatSortHarness extends ComponentHarness {
static hostSelector = '.mat-sort';
/**
* Gets a `HarnessPredicate` that can be used to search for a `mat-sort` with specific attributes.
* @param options Options for narrowing the search.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: SortHarnessFilters = {}): HarnessPredicate<MatSortHarness> {
return new HarnessPredicate(MatSortHarness, options);
}
/** Gets all of the sort headers in the `mat-sort`. */
async getSortHeaders(filter: SortHeaderHarnessFilters = {}): Promise<MatSortHeaderHarness[]> {
return this.locatorForAll(MatSortHeaderHarness.with(filter))();
}
/** Gets the selected header in the `mat-sort`. */
async getActiveHeader(): Promise<MatSortHeaderHarness | null> {
const headers = await this.getSortHeaders();
for (let i = 0; i < headers.length; i++) {
if (await headers[i].isActive()) {
return headers[i];
}
}
return null;
}
}
| {
"end_byte": 1514,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/sort/testing/sort-harness.ts"
} |
components/src/material/sort/testing/sort-harness-filters.ts_0_515 | /**
* @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';
import {SortDirection} from '@angular/material/sort';
export interface SortHarnessFilters extends BaseHarnessFilters {}
export interface SortHeaderHarnessFilters extends BaseHarnessFilters {
label?: string | RegExp;
sortDirection?: SortDirection;
}
| {
"end_byte": 515,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/sort/testing/sort-harness-filters.ts"
} |
components/src/material/sort/testing/public-api.ts_0_315 | /**
* @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 './sort-harness';
export * from './sort-header-harness';
export * from './sort-harness-filters';
| {
"end_byte": 315,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/sort/testing/public-api.ts"
} |
components/src/material/sort/testing/sort-header-harness.ts_0_2240 | /**
* @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 {SortDirection} from '@angular/material/sort';
import {SortHeaderHarnessFilters} from './sort-harness-filters';
/** Harness for interacting with a standard Angular Material sort header in tests. */
export class MatSortHeaderHarness extends ComponentHarness {
static hostSelector = '.mat-sort-header';
private _container = this.locatorFor('.mat-sort-header-container');
/**
* Gets a `HarnessPredicate` that can be used to
* search for a sort header with specific attributes.
*/
static with(options: SortHeaderHarnessFilters = {}): HarnessPredicate<MatSortHeaderHarness> {
return new HarnessPredicate(MatSortHeaderHarness, options)
.addOption('label', options.label, (harness, label) =>
HarnessPredicate.stringMatches(harness.getLabel(), label),
)
.addOption('sortDirection', options.sortDirection, (harness, sortDirection) => {
return HarnessPredicate.stringMatches(harness.getSortDirection(), sortDirection);
});
}
/** Gets the label of the sort header. */
async getLabel(): Promise<string> {
return (await this._container()).text();
}
/** Gets the sorting direction of the header. */
async getSortDirection(): Promise<SortDirection> {
const host = await this.host();
const ariaSort = await host.getAttribute('aria-sort');
if (ariaSort === 'ascending') {
return 'asc';
} else if (ariaSort === 'descending') {
return 'desc';
}
return '';
}
/** Gets whether the sort header is currently being sorted by. */
async isActive(): Promise<boolean> {
return !!(await this.getSortDirection());
}
/** Whether the sort header is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).hasClass('mat-sort-header-disabled');
}
/** Clicks the header to change its sorting direction. Only works if the header is enabled. */
async click(): Promise<void> {
return (await this.host()).click();
}
}
| {
"end_byte": 2240,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/sort/testing/sort-header-harness.ts"
} |
components/src/material/sort/testing/BUILD.bazel_0_750 | 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/sort",
],
)
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/sort",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 750,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/sort/testing/BUILD.bazel"
} |
components/src/material/sort/testing/sort-harness.spec.ts_0_5820 | import {Component, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {MatSortModule, Sort} from '@angular/material/sort';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatSortHarness} from './sort-harness';
describe('MatSortHarness', () => {
let fixture: ComponentFixture<SortHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatSortModule, NoopAnimationsModule, SortHarnessTest],
});
fixture = TestBed.createComponent(SortHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should load harness for mat-sort', async () => {
const sorts = await loader.getAllHarnesses(MatSortHarness);
expect(sorts.length).toBe(1);
});
it('should load the harnesses for all the headers in a mat-sort', async () => {
const sort = await loader.getHarness(MatSortHarness);
const headers = await sort.getSortHeaders();
expect(headers.length).toBe(5);
});
it('should be able to filter headers by their label text', async () => {
const sort = await loader.getHarness(MatSortHarness);
const headers = await sort.getSortHeaders({label: 'Carbs'});
expect(headers.length).toBe(1);
expect(await headers[0].getLabel()).toBe('Carbs');
});
it('should be able to filter headers by their labels via a regex', async () => {
const sort = await loader.getHarness(MatSortHarness);
const headers = await sort.getSortHeaders({label: /^C/});
const labels = await parallel(() => headers.map(header => header.getLabel()));
expect(headers.length).toBe(2);
expect(labels).toEqual(['Calories', 'Carbs']);
});
it('should be able to filter headers by their sorted state', async () => {
const sort = await loader.getHarness(MatSortHarness);
let headers = await sort.getSortHeaders({sortDirection: ''});
expect(headers.length).toBe(5);
await headers[0].click();
headers = await sort.getSortHeaders({sortDirection: 'asc'});
expect(headers.length).toBe(1);
});
it('should be able to get the label of a header', async () => {
const sort = await loader.getHarness(MatSortHarness);
const headers = await sort.getSortHeaders();
const labels = await parallel(() => headers.map(header => header.getLabel()));
expect(labels).toEqual(['Dessert', 'Calories', 'Fat', 'Carbs', 'Protein']);
});
it('should get the disabled state of a header', async () => {
const sort = await loader.getHarness(MatSortHarness);
const thirdHeader = (await sort.getSortHeaders())[2];
expect(await thirdHeader.isDisabled()).toBe(false);
fixture.componentInstance.disableThirdHeader.set(true);
fixture.detectChanges();
expect(await thirdHeader.isDisabled()).toBe(true);
});
it('should get the active state of a header', async () => {
const sort = await loader.getHarness(MatSortHarness);
const secondHeader = (await sort.getSortHeaders())[1];
expect(await secondHeader.isActive()).toBe(false);
await secondHeader.click();
expect(await secondHeader.isActive()).toBe(true);
});
it('should get the sorte direction of a header', async () => {
const sort = await loader.getHarness(MatSortHarness);
const secondHeader = (await sort.getSortHeaders())[1];
expect(await secondHeader.getSortDirection()).toBe('');
await secondHeader.click();
expect(await secondHeader.getSortDirection()).toBe('asc');
await secondHeader.click();
expect(await secondHeader.getSortDirection()).toBe('desc');
});
it('should get the active header', async () => {
const sort = await loader.getHarness(MatSortHarness);
const fifthHeader = (await sort.getSortHeaders())[4];
expect(await sort.getActiveHeader()).toBeNull();
await fifthHeader.click();
const activeHeader = await sort.getActiveHeader();
expect(activeHeader).toBeTruthy();
expect(await activeHeader!.getLabel()).toBe('Protein');
});
});
@Component({
template: `
<table matSort (matSortChange)="sortData($event)">
<tr>
<th mat-sort-header="name">Dessert</th>
<th mat-sort-header="calories">Calories</th>
<th mat-sort-header="fat" [disabled]="disableThirdHeader()">Fat</th>
<th mat-sort-header="carbs">Carbs</th>
<th mat-sort-header="protein">Protein</th>
</tr>
@for (dessert of sortedData; track dessert) {
<tr>
<td>{{dessert.name}}</td>
<td>{{dessert.calories}}</td>
<td>{{dessert.fat}}</td>
<td>{{dessert.carbs}}</td>
<td>{{dessert.protein}}</td>
</tr>
}
</table>
`,
standalone: true,
imports: [MatSortModule],
})
class SortHarnessTest {
disableThirdHeader = signal(false);
desserts = [
{name: 'Frozen yogurt', calories: 159, fat: 6, carbs: 24, protein: 4},
{name: 'Ice cream sandwich', calories: 237, fat: 9, carbs: 37, protein: 4},
{name: 'Eclair', calories: 262, fat: 16, carbs: 24, protein: 6},
{name: 'Cupcake', calories: 305, fat: 4, carbs: 67, protein: 4},
{name: 'Gingerbread', calories: 356, fat: 16, carbs: 49, protein: 4},
];
sortedData = this.desserts.slice();
sortData(sort: Sort) {
const data = this.desserts.slice();
if (!sort.active || sort.direction === '') {
this.sortedData = data;
} else {
this.sortedData = data.sort((a, b) => {
const aValue = (a as any)[sort.active];
const bValue = (b as any)[sort.active];
return (aValue < bValue ? -1 : 1) * (sort.direction === 'asc' ? 1 : -1);
});
}
}
}
| {
"end_byte": 5820,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/sort/testing/sort-harness.spec.ts"
} |
components/src/material/sort/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/sort/testing/index.ts"
} |
components/src/material/chips/chip-grid.ts_0_2539 | /**
* @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 {DOWN_ARROW, hasModifierKey, TAB, UP_ARROW} from '@angular/cdk/keycodes';
import {
AfterContentInit,
AfterViewInit,
booleanAttribute,
ChangeDetectionStrategy,
Component,
ContentChildren,
DoCheck,
EventEmitter,
Input,
OnDestroy,
Output,
QueryList,
ViewEncapsulation,
inject,
} from '@angular/core';
import {
ControlValueAccessor,
FormGroupDirective,
NgControl,
NgForm,
Validators,
} from '@angular/forms';
import {_ErrorStateTracker, ErrorStateMatcher} from '@angular/material/core';
import {MatFormFieldControl} from '@angular/material/form-field';
import {merge, Observable, Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {MatChipEvent} from './chip';
import {MatChipRow} from './chip-row';
import {MatChipSet} from './chip-set';
import {MatChipTextControl} from './chip-text-control';
/** Change event object that is emitted when the chip grid value has changed. */
export class MatChipGridChange {
constructor(
/** Chip grid that emitted the event. */
public source: MatChipGrid,
/** Value of the chip grid when the event was emitted. */
public value: any,
) {}
}
/**
* An extension of the MatChipSet component used with MatChipRow chips and
* the matChipInputFor directive.
*/
@Component({
selector: 'mat-chip-grid',
template: `
<div class="mdc-evolution-chip-set__chips" role="presentation">
<ng-content></ng-content>
</div>
`,
styleUrl: 'chip-set.css',
host: {
'class': 'mat-mdc-chip-set mat-mdc-chip-grid mdc-evolution-chip-set',
'[attr.role]': 'role',
'[attr.tabindex]': '(disabled || (_chips && _chips.length === 0)) ? -1 : tabIndex',
'[attr.aria-disabled]': 'disabled.toString()',
'[attr.aria-invalid]': 'errorState',
'[class.mat-mdc-chip-list-disabled]': 'disabled',
'[class.mat-mdc-chip-list-invalid]': 'errorState',
'[class.mat-mdc-chip-list-required]': 'required',
'(focus)': 'focus()',
'(blur)': '_blur()',
},
providers: [{provide: MatFormFieldControl, useExisting: MatChipGrid}],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MatChipGrid
extends MatChipSet
implements
AfterContentInit,
AfterViewInit,
ControlValueAccessor,
DoCheck,
MatFormFieldControl<any>,
OnDestroy | {
"end_byte": 2539,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-grid.ts"
} |
components/src/material/chips/chip-grid.ts_2540_10607 | {
ngControl = inject(NgControl, {optional: true, self: true})!;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
readonly controlType: string = 'mat-chip-grid';
/** The chip input to add more chips */
protected _chipInput: MatChipTextControl;
protected override _defaultRole = 'grid';
private _errorStateTracker: _ErrorStateTracker;
/**
* List of element ids to propagate to the chipInput's aria-describedby attribute.
*/
private _ariaDescribedbyIds: string[] = [];
/**
* Function when touched. Set as part of ControlValueAccessor implementation.
* @docs-private
*/
_onTouched = () => {};
/**
* Function when changed. Set as part of ControlValueAccessor implementation.
* @docs-private
*/
_onChange: (value: any) => void = () => {};
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input({transform: booleanAttribute})
override get disabled(): boolean {
return this.ngControl ? !!this.ngControl.disabled : this._disabled;
}
override set disabled(value: boolean) {
this._disabled = value;
this._syncChipsState();
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
get id(): string {
return this._chipInput.id;
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
override get empty(): boolean {
return (
(!this._chipInput || this._chipInput.empty) && (!this._chips || this._chips.length === 0)
);
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input()
get placeholder(): string {
return this._chipInput ? this._chipInput.placeholder : this._placeholder;
}
set placeholder(value: string) {
this._placeholder = value;
this.stateChanges.next();
}
protected _placeholder: string;
/** Whether any chips or the matChipInput inside of this chip-grid has focus. */
override get focused(): boolean {
return this._chipInput.focused || this._hasFocusedChip();
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input({transform: booleanAttribute})
get required(): boolean {
return this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false;
}
set required(value: boolean) {
this._required = value;
this.stateChanges.next();
}
protected _required: boolean | undefined;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
get shouldLabelFloat(): boolean {
return !this.empty || this.focused;
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input()
get value(): any {
return this._value;
}
set value(value: any) {
this._value = value;
}
protected _value: any[] = [];
/** An object used to control when error messages are shown. */
@Input()
get errorStateMatcher() {
return this._errorStateTracker.matcher;
}
set errorStateMatcher(value: ErrorStateMatcher) {
this._errorStateTracker.matcher = value;
}
/** Combined stream of all of the child chips' blur events. */
get chipBlurChanges(): Observable<MatChipEvent> {
return this._getChipStream(chip => chip._onBlur);
}
/** Emits when the chip grid value has been changed by the user. */
@Output() readonly change: EventEmitter<MatChipGridChange> =
new EventEmitter<MatChipGridChange>();
/**
* Emits whenever the raw value of the chip-grid changes. This is here primarily
* to facilitate the two-way binding for the `value` input.
* @docs-private
*/
@Output() readonly valueChange: EventEmitter<any> = new EventEmitter<any>();
@ContentChildren(MatChipRow, {
// We need to use `descendants: true`, because Ivy will no longer match
// indirect descendants if it's left as false.
descendants: true,
})
// We need an initializer here to avoid a TS error. The value will be set in `ngAfterViewInit`.
override _chips: QueryList<MatChipRow> = undefined!;
/**
* Emits whenever the component state changes and should cause the parent
* form-field to update. Implemented as part of `MatFormFieldControl`.
* @docs-private
*/
readonly stateChanges = new Subject<void>();
/** Whether the chip grid is in an error state. */
get errorState() {
return this._errorStateTracker.errorState;
}
set errorState(value: boolean) {
this._errorStateTracker.errorState = value;
}
constructor(...args: unknown[]);
constructor() {
super();
const parentForm = inject(NgForm, {optional: true});
const parentFormGroup = inject(FormGroupDirective, {optional: true});
const defaultErrorStateMatcher = inject(ErrorStateMatcher);
if (this.ngControl) {
this.ngControl.valueAccessor = this;
}
this._errorStateTracker = new _ErrorStateTracker(
defaultErrorStateMatcher,
this.ngControl,
parentFormGroup,
parentForm,
this.stateChanges,
);
}
ngAfterContentInit() {
this.chipBlurChanges.pipe(takeUntil(this._destroyed)).subscribe(() => {
this._blur();
this.stateChanges.next();
});
merge(this.chipFocusChanges, this._chips.changes)
.pipe(takeUntil(this._destroyed))
.subscribe(() => this.stateChanges.next());
}
override ngAfterViewInit() {
super.ngAfterViewInit();
if (!this._chipInput && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('mat-chip-grid must be used in combination with matChipInputFor.');
}
}
ngDoCheck() {
if (this.ngControl) {
// We need to re-evaluate this on every change detection cycle, because there are some
// error triggers that we can't subscribe to (e.g. parent form submissions). This means
// that whatever logic is in here has to be super lean or we risk destroying the performance.
this.updateErrorState();
}
}
override ngOnDestroy() {
super.ngOnDestroy();
this.stateChanges.complete();
}
/** Associates an HTML input element with this chip grid. */
registerInput(inputElement: MatChipTextControl): void {
this._chipInput = inputElement;
this._chipInput.setDescribedByIds(this._ariaDescribedbyIds);
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
onContainerClick(event: MouseEvent) {
if (!this.disabled && !this._originatesFromChip(event)) {
this.focus();
}
}
/**
* Focuses the first chip in this chip grid, or the associated input when there
* are no eligible chips.
*/
override focus(): void {
if (this.disabled || this._chipInput.focused) {
return;
}
if (!this._chips.length || this._chips.first.disabled) {
// Delay until the next tick, because this can cause a "changed after checked"
// error if the input does something on focus (e.g. opens an autocomplete).
Promise.resolve().then(() => this._chipInput.focus());
} else {
const activeItem = this._keyManager.activeItem;
if (activeItem) {
activeItem.focus();
} else {
this._keyManager.setFirstItemActive();
}
}
this.stateChanges.next();
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
setDescribedByIds(ids: string[]) {
// We must keep this up to date to handle the case where ids are set
// before the chip input is registered.
this._ariaDescribedbyIds = ids;
this._chipInput?.setDescribedByIds(ids);
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
writeValue(value: any): void {
// The user is responsible for creating the child chips, so we just store the value.
this._value = value;
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
registerOnTouched(fn: () => void): void {
this._onTouched = fn;
} | {
"end_byte": 10607,
"start_byte": 2540,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-grid.ts"
} |
components/src/material/chips/chip-grid.ts_10611_14494 | /**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this.stateChanges.next();
}
/** Refreshes the error state of the chip grid. */
updateErrorState() {
this._errorStateTracker.updateErrorState();
}
/** When blurred, mark the field as touched when focus moved outside the chip grid. */
_blur() {
if (!this.disabled) {
// Check whether the focus moved to chip input.
// If the focus is not moved to chip input, mark the field as touched. If the focus moved
// to chip input, do nothing.
// Timeout is needed to wait for the focus() event trigger on chip input.
setTimeout(() => {
if (!this.focused) {
this._propagateChanges();
this._markAsTouched();
}
});
}
}
/**
* Removes the `tabindex` from the chip grid and resets it back afterwards, allowing the
* user to tab out of it. This prevents the grid from capturing focus and redirecting
* it back to the first chip, creating a focus trap, if it user tries to tab away.
*/
protected override _allowFocusEscape() {
if (!this._chipInput.focused) {
super._allowFocusEscape();
}
}
/** Handles custom keyboard events. */
override _handleKeydown(event: KeyboardEvent) {
const keyCode = event.keyCode;
const activeItem = this._keyManager.activeItem;
if (keyCode === TAB) {
if (
this._chipInput.focused &&
hasModifierKey(event, 'shiftKey') &&
this._chips.length &&
!this._chips.last.disabled
) {
event.preventDefault();
if (activeItem) {
this._keyManager.setActiveItem(activeItem);
} else {
this._focusLastChip();
}
} else {
// Use the super method here since it doesn't check for the input
// focused state. This allows focus to escape if there's only one
// disabled chip left in the list.
super._allowFocusEscape();
}
} else if (!this._chipInput.focused) {
// The up and down arrows are supposed to navigate between the individual rows in the grid.
// We do this by filtering the actions down to the ones that have the same `_isPrimary`
// flag as the active action and moving focus between them ourseles instead of delegating
// to the key manager. For more information, see #29359 and:
// https://www.w3.org/WAI/ARIA/apg/patterns/grid/examples/layout-grids/#ex2_label
if ((keyCode === UP_ARROW || keyCode === DOWN_ARROW) && activeItem) {
const eligibleActions = this._chipActions.filter(
action => action._isPrimary === activeItem._isPrimary && !this._skipPredicate(action),
);
const currentIndex = eligibleActions.indexOf(activeItem);
const delta = event.keyCode === UP_ARROW ? -1 : 1;
event.preventDefault();
if (currentIndex > -1 && this._isValidIndex(currentIndex + delta)) {
this._keyManager.setActiveItem(eligibleActions[currentIndex + delta]);
}
} else {
super._handleKeydown(event);
}
}
this.stateChanges.next();
}
_focusLastChip() {
if (this._chips.length) {
this._chips.last.focus();
}
}
/** Emits change event to set the model value. */
private _propagateChanges(): void {
const valueToEmit = this._chips.length ? this._chips.toArray().map(chip => chip.value) : [];
this._value = valueToEmit;
this.change.emit(new MatChipGridChange(this, valueToEmit));
this.valueChange.emit(valueToEmit);
this._onChange(valueToEmit);
this._changeDetectorRef.markForCheck();
}
/** Mark the field as touched */
private _markAsTouched() {
this._onTouched();
this._changeDetectorRef.markForCheck();
this.stateChanges.next();
}
} | {
"end_byte": 14494,
"start_byte": 10611,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-grid.ts"
} |
components/src/material/chips/chip-action.ts_0_3617 | /**
* @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,
Input,
booleanAttribute,
numberAttribute,
inject,
} from '@angular/core';
import {ENTER, SPACE} from '@angular/cdk/keycodes';
import {MAT_CHIP} from './tokens';
import {_CdkPrivateStyleLoader} from '@angular/cdk/private';
import {_StructuralStylesLoader} from '@angular/material/core';
/**
* Section within a chip.
* @docs-private
*/
@Directive({
selector: '[matChipAction]',
host: {
'class': 'mdc-evolution-chip__action mat-mdc-chip-action',
'[class.mdc-evolution-chip__action--primary]': '_isPrimary',
'[class.mdc-evolution-chip__action--presentational]': '!isInteractive',
'[class.mdc-evolution-chip__action--trailing]': '!_isPrimary',
'[attr.tabindex]': '_getTabindex()',
'[attr.disabled]': '_getDisabledAttribute()',
'[attr.aria-disabled]': 'disabled',
'(click)': '_handleClick($event)',
'(keydown)': '_handleKeydown($event)',
},
})
export class MatChipAction {
_elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
protected _parentChip = inject<{
_handlePrimaryActionInteraction(): void;
remove(): void;
disabled: boolean;
_isEditing?: boolean;
}>(MAT_CHIP);
/** Whether the action is interactive. */
@Input() isInteractive = true;
/** Whether this is the primary action in the chip. */
_isPrimary = true;
/** Whether the action is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this._disabled || this._parentChip?.disabled || false;
}
set disabled(value: boolean) {
this._disabled = value;
}
private _disabled = false;
/** Tab index of the action. */
@Input({
transform: (value: unknown) => (value == null ? -1 : numberAttribute(value)),
})
tabIndex: number = -1;
/**
* Private API to allow focusing this chip when it is disabled.
*/
@Input()
private _allowFocusWhenDisabled = false;
/**
* Determine the value of the disabled attribute for this chip action.
*/
protected _getDisabledAttribute(): string | null {
// When this chip action is disabled and focusing disabled chips is not permitted, return empty
// string to indicate that disabled attribute should be included.
return this.disabled && !this._allowFocusWhenDisabled ? '' : null;
}
/**
* Determine the value of the tabindex attribute for this chip action.
*/
protected _getTabindex(): string | null {
return (this.disabled && !this._allowFocusWhenDisabled) || !this.isInteractive
? null
: this.tabIndex.toString();
}
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
if (this._elementRef.nativeElement.nodeName === 'BUTTON') {
this._elementRef.nativeElement.setAttribute('type', 'button');
}
}
focus() {
this._elementRef.nativeElement.focus();
}
_handleClick(event: MouseEvent) {
if (!this.disabled && this.isInteractive && this._isPrimary) {
event.preventDefault();
this._parentChip._handlePrimaryActionInteraction();
}
}
_handleKeydown(event: KeyboardEvent) {
if (
(event.keyCode === ENTER || event.keyCode === SPACE) &&
!this.disabled &&
this.isInteractive &&
this._isPrimary &&
!this._parentChip._isEditing
) {
event.preventDefault();
this._parentChip._handlePrimaryActionInteraction();
}
}
}
| {
"end_byte": 3617,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-action.ts"
} |
components/src/material/chips/_chips-theme.scss_0_6371 | @use 'sass:color';
@use '../core/tokens/m2/mdc/chip' as tokens-mdc-chip;
@use '../core/tokens/m2/mat/chip' as tokens-mat-chip;
@use '../core/tokens/token-utils';
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/typography/typography';
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-chips.
/// @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 {
.mat-mdc-standard-chip {
@include token-utils.create-token-values(
tokens-mdc-chip.$prefix,
tokens-mdc-chip.get-unthemable-tokens()
);
@include token-utils.create-token-values(
tokens-mat-chip.$prefix,
tokens-mat-chip.get-unthemable-tokens()
);
}
}
}
/// Outputs color theme styles for the mat-chips.
/// @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 selected chip: 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 {
.mat-mdc-standard-chip {
@include token-utils.create-token-values(
tokens-mdc-chip.$prefix,
tokens-mdc-chip.get-color-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-chip.$prefix,
tokens-mat-chip.get-color-tokens($theme)
);
&.mat-mdc-chip-selected,
&.mat-mdc-chip-highlighted {
&.mat-primary {
@include token-utils.create-token-values(
tokens-mdc-chip.$prefix,
tokens-mdc-chip.get-color-tokens($theme, primary)
);
@include token-utils.create-token-values(
tokens-mat-chip.$prefix,
tokens-mat-chip.get-color-tokens($theme, primary)
);
}
&.mat-accent {
@include token-utils.create-token-values(
tokens-mdc-chip.$prefix,
tokens-mdc-chip.get-color-tokens($theme, accent)
);
@include token-utils.create-token-values(
tokens-mat-chip.$prefix,
tokens-mat-chip.get-color-tokens($theme, accent)
);
}
&.mat-warn {
@include token-utils.create-token-values(
tokens-mdc-chip.$prefix,
tokens-mdc-chip.get-color-tokens($theme, warn)
);
@include token-utils.create-token-values(
tokens-mat-chip.$prefix,
tokens-mat-chip.get-color-tokens($theme, warn)
);
}
}
}
}
}
/// Outputs typography theme styles for the mat-chips.
/// @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 {
.mat-mdc-standard-chip {
@include token-utils.create-token-values(
tokens-mdc-chip.$prefix,
tokens-mdc-chip.get-typography-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-chip.$prefix,
tokens-mat-chip.get-typography-tokens($theme)
);
}
}
}
/// Outputs density theme styles for the mat-chips.
/// @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 {
.mat-mdc-chip.mat-mdc-standard-chip {
@include token-utils.create-token-values(
tokens-mdc-chip.$prefix,
tokens-mdc-chip.get-density-tokens($theme)
);
@include token-utils.create-token-values(
tokens-mat-chip.$prefix,
tokens-mat-chip.get-density-tokens($theme)
);
}
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mdc-chip.$prefix,
tokens: tokens-mdc-chip.get-token-slots(),
),
(
namespace: tokens-mat-chip.$prefix,
tokens: tokens-mat-chip.get-token-slots(),
),
);
}
/// Outputs the CSS variable values for the given tokens.
/// @param {Map} $tokens The token values to emit.
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
/// Outputs all (base, color, typography, and density) theme styles for the mat-chips.
/// @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 selected chip: 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-chips') {
@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-chip-tokens: token-utils.get-tokens-for($tokens, tokens-mdc-chip.$prefix, $options...);
$mat-chip-tokens: token-utils.get-tokens-for($tokens, tokens-mat-chip.$prefix, $options...);
@include token-utils.create-token-values(tokens-mdc-chip.$prefix, $mdc-chip-tokens);
@include token-utils.create-token-values(tokens-mat-chip.$prefix, $mat-chip-tokens);
}
| {
"end_byte": 6371,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/_chips-theme.scss"
} |
components/src/material/chips/chip-listbox.ts_0_2681 | /**
* @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 {
AfterContentInit,
booleanAttribute,
ChangeDetectionStrategy,
Component,
ContentChildren,
EventEmitter,
forwardRef,
inject,
Input,
OnDestroy,
Output,
QueryList,
ViewEncapsulation,
} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {Observable} from 'rxjs';
import {startWith, takeUntil} from 'rxjs/operators';
import {TAB} from '@angular/cdk/keycodes';
import {MatChip, MatChipEvent} from './chip';
import {MatChipOption, MatChipSelectionChange} from './chip-option';
import {MatChipSet} from './chip-set';
import {MatChipAction} from './chip-action';
import {MAT_CHIPS_DEFAULT_OPTIONS} from './tokens';
/** Change event object that is emitted when the chip listbox value has changed. */
export class MatChipListboxChange {
constructor(
/** Chip listbox that emitted the event. */
public source: MatChipListbox,
/** Value of the chip listbox when the event was emitted. */
public value: any,
) {}
}
/**
* Provider Expression that allows mat-chip-listbox to register as a ControlValueAccessor.
* This allows it to support [(ngModel)].
* @docs-private
*/
export const MAT_CHIP_LISTBOX_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MatChipListbox),
multi: true,
};
/**
* An extension of the MatChipSet component that supports chip selection.
* Used with MatChipOption chips.
*/
@Component({
selector: 'mat-chip-listbox',
template: `
<div class="mdc-evolution-chip-set__chips" role="presentation">
<ng-content></ng-content>
</div>
`,
styleUrl: 'chip-set.css',
host: {
'class': 'mdc-evolution-chip-set mat-mdc-chip-listbox',
'[attr.role]': 'role',
'[tabIndex]': '(disabled || empty) ? -1 : tabIndex',
// TODO: replace this binding with use of AriaDescriber
'[attr.aria-describedby]': '_ariaDescribedby || null',
'[attr.aria-required]': 'role ? required : null',
'[attr.aria-disabled]': 'disabled.toString()',
'[attr.aria-multiselectable]': 'multiple',
'[attr.aria-orientation]': 'ariaOrientation',
'[class.mat-mdc-chip-list-disabled]': 'disabled',
'[class.mat-mdc-chip-list-required]': 'required',
'(focus)': 'focus()',
'(blur)': '_blur()',
'(keydown)': '_keydown($event)',
},
providers: [MAT_CHIP_LISTBOX_CONTROL_VALUE_ACCESSOR],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export | {
"end_byte": 2681,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-listbox.ts"
} |
components/src/material/chips/chip-listbox.ts_2682_10579 | class MatChipListbox
extends MatChipSet
implements AfterContentInit, OnDestroy, ControlValueAccessor
{
/**
* Function when touched. Set as part of ControlValueAccessor implementation.
* @docs-private
*/
_onTouched = () => {};
/**
* Function when changed. Set as part of ControlValueAccessor implementation.
* @docs-private
*/
_onChange: (value: any) => void = () => {};
// TODO: MDC uses `grid` here
protected override _defaultRole = 'listbox';
/** Value that was assigned before the listbox was initialized. */
private _pendingInitialValue: any;
/** Default chip options. */
private _defaultOptions = inject(MAT_CHIPS_DEFAULT_OPTIONS, {optional: true});
/** Whether the user should be allowed to select multiple chips. */
@Input({transform: booleanAttribute})
get multiple(): boolean {
return this._multiple;
}
set multiple(value: boolean) {
this._multiple = value;
this._syncListboxProperties();
}
private _multiple: boolean = false;
/** The array of selected chips inside the chip listbox. */
get selected(): MatChipOption[] | MatChipOption {
const selectedChips = this._chips.toArray().filter(chip => chip.selected);
return this.multiple ? selectedChips : selectedChips[0];
}
/** Orientation of the chip list. */
@Input('aria-orientation') ariaOrientation: 'horizontal' | 'vertical' = 'horizontal';
/**
* Whether or not this chip listbox is selectable.
*
* When a chip listbox is not selectable, the selected states for all
* the chips inside the chip listbox are always ignored.
*/
@Input({transform: booleanAttribute})
get selectable(): boolean {
return this._selectable;
}
set selectable(value: boolean) {
this._selectable = value;
this._syncListboxProperties();
}
protected _selectable: boolean = true;
/**
* A function to compare the option values with the selected values. The first argument
* is a value from an option. The second is a value from the selection. A boolean
* should be returned.
*/
@Input() compareWith: (o1: any, o2: any) => boolean = (o1: any, o2: any) => o1 === o2;
/** Whether this chip listbox is required. */
@Input({transform: booleanAttribute})
required: boolean = false;
/** Whether checkmark indicator for single-selection options is hidden. */
@Input({transform: booleanAttribute})
get hideSingleSelectionIndicator(): boolean {
return this._hideSingleSelectionIndicator;
}
set hideSingleSelectionIndicator(value: boolean) {
this._hideSingleSelectionIndicator = value;
this._syncListboxProperties();
}
private _hideSingleSelectionIndicator: boolean =
this._defaultOptions?.hideSingleSelectionIndicator ?? false;
/** Combined stream of all of the child chips' selection change events. */
get chipSelectionChanges(): Observable<MatChipSelectionChange> {
return this._getChipStream<MatChipSelectionChange, MatChipOption>(chip => chip.selectionChange);
}
/** Combined stream of all of the child chips' blur events. */
get chipBlurChanges(): Observable<MatChipEvent> {
return this._getChipStream(chip => chip._onBlur);
}
/** The value of the listbox, which is the combined value of the selected chips. */
@Input()
get value(): any {
return this._value;
}
set value(value: any) {
this.writeValue(value);
this._value = value;
}
protected _value: any;
/** Event emitted when the selected chip listbox value has been changed by the user. */
@Output() readonly change: EventEmitter<MatChipListboxChange> =
new EventEmitter<MatChipListboxChange>();
@ContentChildren(MatChipOption, {
// We need to use `descendants: true`, because Ivy will no longer match
// indirect descendants if it's left as false.
descendants: true,
})
// We need an initializer here to avoid a TS error. The value will be set in `ngAfterViewInit`.
override _chips: QueryList<MatChipOption> = undefined!;
ngAfterContentInit() {
if (this._pendingInitialValue !== undefined) {
Promise.resolve().then(() => {
this._setSelectionByValue(this._pendingInitialValue, false);
this._pendingInitialValue = undefined;
});
}
this._chips.changes.pipe(startWith(null), takeUntil(this._destroyed)).subscribe(() => {
// Update listbox selectable/multiple properties on chips
this._syncListboxProperties();
});
this.chipBlurChanges.pipe(takeUntil(this._destroyed)).subscribe(() => this._blur());
this.chipSelectionChanges.pipe(takeUntil(this._destroyed)).subscribe(event => {
if (!this.multiple) {
this._chips.forEach(chip => {
if (chip !== event.source) {
chip._setSelectedState(false, false, false);
}
});
}
if (event.isUserInput) {
this._propagateChanges();
}
});
}
/**
* Focuses the first selected chip in this chip listbox, or the first non-disabled chip when there
* are no selected chips.
*/
override focus(): void {
if (this.disabled) {
return;
}
const firstSelectedChip = this._getFirstSelectedChip();
if (firstSelectedChip && !firstSelectedChip.disabled) {
firstSelectedChip.focus();
} else if (this._chips.length > 0) {
this._keyManager.setFirstItemActive();
} else {
this._elementRef.nativeElement.focus();
}
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
writeValue(value: any): void {
if (this._chips) {
this._setSelectionByValue(value, false);
} else if (value != null) {
this._pendingInitialValue = value;
}
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
registerOnTouched(fn: () => void): void {
this._onTouched = fn;
}
/**
* Implemented as part of ControlValueAccessor.
* @docs-private
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
/** Selects all chips with value. */
_setSelectionByValue(value: any, isUserInput: boolean = true) {
this._clearSelection();
if (Array.isArray(value)) {
value.forEach(currentValue => this._selectValue(currentValue, isUserInput));
} else {
this._selectValue(value, isUserInput);
}
}
/** When blurred, marks the field as touched when focus moved outside the chip listbox. */
_blur() {
if (!this.disabled) {
// Wait to see if focus moves to an individual chip.
setTimeout(() => {
if (!this.focused) {
this._markAsTouched();
}
});
}
}
_keydown(event: KeyboardEvent) {
if (event.keyCode === TAB) {
super._allowFocusEscape();
}
}
/** Marks the field as touched */
private _markAsTouched() {
this._onTouched();
this._changeDetectorRef.markForCheck();
}
/** Emits change event to set the model value. */
private _propagateChanges(): void {
let valueToEmit: any = null;
if (Array.isArray(this.selected)) {
valueToEmit = this.selected.map(chip => chip.value);
} else {
valueToEmit = this.selected ? this.selected.value : undefined;
}
this._value = valueToEmit;
this.change.emit(new MatChipListboxChange(this, valueToEmit));
this._onChange(valueToEmit);
this._changeDetectorRef.markForCheck();
}
/**
* Deselects every chip in the listbox.
* @param skip Chip that should not be deselected.
*/
private _clearSelection(skip?: MatChip): void {
this._chips.forEach(chip => {
if (chip !== skip) {
chip.deselect();
}
});
}
/**
* Finds and selects the chip based on its value.
* @returns Chip that has the corresponding value.
*/ | {
"end_byte": 10579,
"start_byte": 2682,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-listbox.ts"
} |
components/src/material/chips/chip-listbox.ts_10582_12761 | private _selectValue(value: any, isUserInput: boolean): MatChip | undefined {
const correspondingChip = this._chips.find(chip => {
return chip.value != null && this.compareWith(chip.value, value);
});
if (correspondingChip) {
isUserInput ? correspondingChip.selectViaInteraction() : correspondingChip.select();
}
return correspondingChip;
}
/** Syncs the chip-listbox selection state with the individual chips. */
private _syncListboxProperties() {
if (this._chips) {
// Defer setting the value in order to avoid the "Expression
// has changed after it was checked" errors from Angular.
Promise.resolve().then(() => {
this._chips.forEach(chip => {
chip._chipListMultiple = this.multiple;
chip.chipListSelectable = this._selectable;
chip._chipListHideSingleSelectionIndicator = this.hideSingleSelectionIndicator;
chip._changeDetectorRef.markForCheck();
});
});
}
}
/** Returns the first selected chip in this listbox, or undefined if no chips are selected. */
private _getFirstSelectedChip(): MatChipOption | undefined {
if (Array.isArray(this.selected)) {
return this.selected.length ? this.selected[0] : undefined;
} else {
return this.selected;
}
}
/**
* Determines if key manager should avoid putting a given chip action in the tab index. Skip
* non-interactive actions since the user can't do anything with them.
*/
protected override _skipPredicate(action: MatChipAction): boolean {
// Override the skip predicate in the base class to avoid skipping disabled chips. Allow
// disabled chip options to receive focus to align with WAI ARIA recommendation. Normally WAI
// ARIA's instructions are to exclude disabled items from the tab order, but it makes a few
// exceptions for compound widgets.
//
// From [Developing a Keyboard Interface](
// https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/):
// "For the following composite widget elements, keep them focusable when disabled: Options in a
// Listbox..."
return !action.isInteractive;
}
} | {
"end_byte": 12761,
"start_byte": 10582,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-listbox.ts"
} |
components/src/material/chips/chip-set.scss_0_1182 | // Ensures that the internal chip container spans the entire outer container width, if the
// outer container width is customized. This is used by some wrapper components in g3.
.mat-mdc-chip-set {
display: flex;
&:focus {
outline: none;
}
.mdc-evolution-chip-set__chips {
min-width: 100%;
margin-left: -8px;
margin-right: 0;
}
.mdc-evolution-chip {
margin: 4px 0 4px 8px;
}
[dir='rtl'] & {
.mdc-evolution-chip-set__chips {
margin-left: 0;
margin-right: -8px;
}
.mdc-evolution-chip {
margin-left: 0;
margin-right: 8px;
}
}
}
.mdc-evolution-chip-set__chips {
display: flex;
flex-flow: wrap;
min-width: 0;
}
// Angular Material supports vertically-stacked chips, which MDC does not.
.mat-mdc-chip-set-stacked {
flex-direction: column;
align-items: flex-start;
.mat-mdc-chip {
width: 100%;
}
.mdc-evolution-chip__graphic {
flex-grow: 0;
}
.mdc-evolution-chip__action--primary {
flex-basis: 100%;
justify-content: start;
}
}
input.mat-mdc-chip-input {
flex: 1 0 150px;
margin-left: 8px;
[dir='rtl'] & {
margin-left: 0;
margin-right: 8px;
}
}
| {
"end_byte": 1182,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-set.scss"
} |
components/src/material/chips/chip-text-control.ts_0_759 | /**
* @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
*/
/** Interface for a text control that is used to drive interaction with a mat-chip-list. */
export interface MatChipTextControl {
/** Unique identifier for the text control. */
id: string;
/** The text control's placeholder text. */
placeholder: string;
/** Whether the text control has browser focus. */
focused: boolean;
/** Whether the text control is empty. */
empty: boolean;
/** Focuses the text control. */
focus(): void;
/** Sets the list of ids the input is described by. */
setDescribedByIds(ids: string[]): void;
}
| {
"end_byte": 759,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-text-control.ts"
} |
components/src/material/chips/chip-option.spec.ts_0_1708 | import {Directionality} from '@angular/cdk/bidi';
import {ENTER, SPACE} from '@angular/cdk/keycodes';
import {dispatchFakeEvent, dispatchKeyboardEvent} from '@angular/cdk/testing/private';
import {Component, DebugElement, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, waitForAsync} from '@angular/core/testing';
import {MAT_RIPPLE_GLOBAL_OPTIONS, RippleGlobalOptions} from '@angular/material/core';
import {By} from '@angular/platform-browser';
import {Subject} from 'rxjs';
import {
MAT_CHIPS_DEFAULT_OPTIONS,
MatChipEvent,
MatChipListbox,
MatChipOption,
MatChipSelectionChange,
MatChipsDefaultOptions,
MatChipsModule,
} from './index';
describe('Option Chips', () => {
let fixture: ComponentFixture<any>;
let chipDebugElement: DebugElement;
let chipNativeElement: HTMLElement;
let primaryAction: HTMLElement;
let chipInstance: MatChipOption;
let globalRippleOptions: RippleGlobalOptions;
let dir = 'ltr';
let hideSingleSelectionIndicator: boolean | undefined;
beforeEach(waitForAsync(() => {
globalRippleOptions = {};
const defaultOptions: MatChipsDefaultOptions = {
separatorKeyCodes: [ENTER, SPACE],
hideSingleSelectionIndicator,
};
TestBed.configureTestingModule({
imports: [MatChipsModule],
providers: [
{provide: MAT_RIPPLE_GLOBAL_OPTIONS, useFactory: () => globalRippleOptions},
{
provide: Directionality,
useFactory: () => ({
value: dir,
change: new Subject(),
}),
},
{provide: MAT_CHIPS_DEFAULT_OPTIONS, useFactory: () => defaultOptions},
],
declarations: [SingleChip],
});
})); | {
"end_byte": 1708,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-option.spec.ts"
} |
components/src/material/chips/chip-option.spec.ts_1712_11434 | describe('MatChipOption', () => {
let testComponent: SingleChip;
beforeEach(() => {
fixture = TestBed.createComponent(SingleChip);
fixture.detectChanges();
chipDebugElement = fixture.debugElement.query(By.directive(MatChipOption))!;
chipNativeElement = chipDebugElement.nativeElement;
chipInstance = chipDebugElement.injector.get<MatChipOption>(MatChipOption);
primaryAction = chipNativeElement.querySelector('.mdc-evolution-chip__action--primary')!;
testComponent = fixture.debugElement.componentInstance;
});
describe('basic behaviors', () => {
it('adds the `mat-chip` class', () => {
expect(chipNativeElement.classList).toContain('mat-mdc-chip');
});
it('emits focus only once for multiple clicks', () => {
let counter = 0;
chipInstance._onFocus.subscribe(() => {
counter++;
});
primaryAction.focus();
primaryAction.focus();
fixture.detectChanges();
expect(counter).toBe(1);
});
it('emits destroy on destruction', () => {
spyOn(testComponent, 'chipDestroy').and.callThrough();
// Force a destroy callback
testComponent.shouldShow = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(testComponent.chipDestroy).toHaveBeenCalledTimes(1);
});
it('allows color customization', () => {
expect(chipNativeElement.classList).toContain('mat-primary');
testComponent.color = 'warn';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipNativeElement.classList).not.toContain('mat-primary');
expect(chipNativeElement.classList).toContain('mat-warn');
});
it('allows selection', () => {
spyOn(testComponent, 'chipSelectionChange');
expect(chipNativeElement.classList).not.toContain('mat-mdc-chip-selected');
testComponent.selected = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipNativeElement.classList).toContain('mat-mdc-chip-selected');
expect(testComponent.chipSelectionChange).toHaveBeenCalledWith({
source: chipInstance,
isUserInput: false,
selected: true,
});
});
it('should not prevent the default click action', () => {
const event = dispatchFakeEvent(chipNativeElement, 'click');
fixture.detectChanges();
expect(event.defaultPrevented).toBe(false);
});
it('should not dispatch `selectionChange` event when deselecting a non-selected chip', () => {
chipInstance.deselect();
const spy = jasmine.createSpy('selectionChange spy');
const subscription = chipInstance.selectionChange.subscribe(spy);
chipInstance.deselect();
expect(spy).not.toHaveBeenCalled();
subscription.unsubscribe();
});
it('should not dispatch `selectionChange` event when selecting a selected chip', () => {
chipInstance.select();
const spy = jasmine.createSpy('selectionChange spy');
const subscription = chipInstance.selectionChange.subscribe(spy);
chipInstance.select();
expect(spy).not.toHaveBeenCalled();
subscription.unsubscribe();
});
it(
'should not dispatch `selectionChange` event when selecting a selected chip via ' +
'user interaction',
() => {
chipInstance.select();
const spy = jasmine.createSpy('selectionChange spy');
const subscription = chipInstance.selectionChange.subscribe(spy);
chipInstance.selectViaInteraction();
expect(spy).not.toHaveBeenCalled();
subscription.unsubscribe();
},
);
it('should not dispatch `selectionChange` through setter if the value did not change', () => {
chipInstance.selected = false;
const spy = jasmine.createSpy('selectionChange spy');
const subscription = chipInstance.selectionChange.subscribe(spy);
chipInstance.selected = false;
expect(spy).not.toHaveBeenCalled();
subscription.unsubscribe();
});
it('should be able to disable ripples through ripple global options at runtime', () => {
expect(chipInstance._isRippleDisabled())
.withContext('Expected chip ripples to be enabled.')
.toBe(false);
globalRippleOptions.disabled = true;
expect(chipInstance._isRippleDisabled())
.withContext('Expected chip ripples to be disabled.')
.toBe(true);
});
it('should have the correct role', () => {
expect(chipNativeElement.getAttribute('role')).toBe('presentation');
});
it('should be able to set a custom role', () => {
chipInstance.role = 'button';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipNativeElement.getAttribute('role')).toBe('button');
});
});
describe('keyboard behavior', () => {
describe('when selectable is true', () => {
beforeEach(() => {
testComponent.selectable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
it('should selects/deselects the currently focused chip on SPACE', () => {
const CHIP_SELECTED_EVENT: MatChipSelectionChange = {
source: chipInstance,
isUserInput: true,
selected: true,
};
const CHIP_DESELECTED_EVENT: MatChipSelectionChange = {
source: chipInstance,
isUserInput: true,
selected: false,
};
spyOn(testComponent, 'chipSelectionChange');
// Use the spacebar to select the chip
dispatchKeyboardEvent(primaryAction, 'keydown', SPACE);
fixture.detectChanges();
expect(chipInstance.selected).toBeTruthy();
expect(testComponent.chipSelectionChange).toHaveBeenCalledTimes(1);
expect(testComponent.chipSelectionChange).toHaveBeenCalledWith(CHIP_SELECTED_EVENT);
// Use the spacebar to deselect the chip
dispatchKeyboardEvent(primaryAction, 'keydown', SPACE);
fixture.detectChanges();
expect(chipInstance.selected).toBeFalsy();
expect(testComponent.chipSelectionChange).toHaveBeenCalledTimes(2);
expect(testComponent.chipSelectionChange).toHaveBeenCalledWith(CHIP_DESELECTED_EVENT);
});
it('should have correct aria-selected in single selection mode', () => {
expect(primaryAction.getAttribute('aria-selected')).toBe('false');
testComponent.selected = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(primaryAction.getAttribute('aria-selected')).toBe('true');
});
it('should have the correct aria-selected in multi-selection mode', fakeAsync(() => {
testComponent.chipList.multiple = true;
fixture.changeDetectorRef.markForCheck();
flush();
fixture.detectChanges();
expect(primaryAction.getAttribute('aria-selected')).toBe('false');
testComponent.selected = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(primaryAction.getAttribute('aria-selected')).toBe('true');
}));
it('should disable focus on the checkmark', fakeAsync(() => {
// The checkmark is only shown in multi selection mode.
testComponent.chipList.multiple = true;
fixture.changeDetectorRef.markForCheck();
flush();
fixture.detectChanges();
const checkmark = chipNativeElement.querySelector('.mdc-evolution-chip__checkmark-svg')!;
expect(checkmark.getAttribute('focusable')).toBe('false');
}));
});
describe('when selectable is false', () => {
beforeEach(() => {
testComponent.selectable = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
it('SPACE ignores selection', () => {
spyOn(testComponent, 'chipSelectionChange');
// Use the spacebar to attempt to select the chip
dispatchKeyboardEvent(primaryAction, 'keydown', SPACE);
fixture.detectChanges();
expect(chipInstance.selected).toBe(false);
expect(testComponent.chipSelectionChange).not.toHaveBeenCalled();
});
it('should not have the aria-selected attribute', () => {
expect(primaryAction.hasAttribute('aria-selected')).toBe(false);
});
});
it('should update the aria-disabled for disabled chips', () => {
expect(primaryAction.getAttribute('aria-disabled')).toBe('false');
testComponent.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(primaryAction.getAttribute('aria-disabled')).toBe('true');
});
it('should display checkmark graphic by default', () => {
expect(
fixture.debugElement.injector.get(MAT_CHIPS_DEFAULT_OPTIONS)
?.hideSingleSelectionIndicator,
)
.withContext(
'expected not to have a default value set for `hideSingleSelectionIndicator`',
)
.toBeUndefined();
expect(chipNativeElement.querySelector('.mat-mdc-chip-graphic')).toBeTruthy();
expect(chipNativeElement.classList).toContain('mdc-evolution-chip--with-primary-graphic');
});
}); | {
"end_byte": 11434,
"start_byte": 1712,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-option.spec.ts"
} |
components/src/material/chips/chip-option.spec.ts_11440_15470 | describe('a11y', () => {
it('should apply `ariaLabel` and `ariaDesciption` to the element with option role', () => {
testComponent.ariaLabel = 'option name';
testComponent.ariaDescription = 'option description';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const optionElement = fixture.nativeElement.querySelector('[role="option"]') as HTMLElement;
expect(optionElement)
.withContext('expected to find an element with option role')
.toBeTruthy();
expect(optionElement.getAttribute('aria-label')).toMatch(/option name/i);
const optionElementDescribedBy = optionElement!.getAttribute('aria-describedby');
expect(optionElementDescribedBy)
.withContext('expected primary grid cell to have a non-empty aria-describedby attribute')
.toBeTruthy();
const optionElementDescriptions = Array.from(
(fixture.nativeElement as HTMLElement).querySelectorAll(
optionElementDescribedBy!
.split(/\s+/g)
.map(x => `#${x}`)
.join(','),
),
);
const optionElementDescription = optionElementDescriptions
.map(x => x.textContent?.trim())
.join(' ')
.trim();
expect(optionElementDescription).toMatch(/option description/i);
});
it('should display checkmark graphic by default', () => {
expect(chipNativeElement.querySelector('.mat-mdc-chip-graphic')).toBeTruthy();
expect(chipNativeElement.classList).toContain('mdc-evolution-chip--with-primary-graphic');
});
});
describe('with token to hide single-selection checkmark indicator', () => {
beforeAll(() => {
hideSingleSelectionIndicator = true;
});
afterAll(() => {
hideSingleSelectionIndicator = undefined;
});
it('does not display checkmark graphic', () => {
expect(chipNativeElement.querySelector('.mat-mdc-chip-graphic')).toBeNull();
expect(chipNativeElement.classList).not.toContain(
'mdc-evolution-chip--with-primary-graphic',
);
});
it('displays checkmark graphic when avatar is provided', () => {
testComponent.selected = true;
testComponent.avatarLabel = 'A';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipNativeElement.querySelector('.mat-mdc-chip-graphic')).toBeTruthy();
expect(chipNativeElement.classList).toContain('mdc-evolution-chip--with-primary-graphic');
});
});
it('should contain a focus indicator inside the text label', () => {
const label = chipNativeElement.querySelector('.mdc-evolution-chip__text-label');
expect(label?.querySelector('.mat-focus-indicator')).toBeTruthy();
});
});
});
@Component({
template: `
<mat-chip-listbox>
@if (shouldShow) {
<div>
<mat-chip-option [selectable]="selectable"
[color]="color" [selected]="selected" [disabled]="disabled"
(destroyed)="chipDestroy($event)"
(selectionChange)="chipSelectionChange($event)"
[aria-label]="ariaLabel" [aria-description]="ariaDescription">
@if (avatarLabel) {
<span class="avatar" matChipAvatar>{{avatarLabel}}</span>
}
{{name}}
</mat-chip-option>
</div>
}
</mat-chip-listbox>`,
standalone: false,
})
class SingleChip {
@ViewChild(MatChipListbox) chipList: MatChipListbox;
disabled: boolean = false;
name: string = 'Test';
color: string = 'primary';
selected: boolean = false;
selectable: boolean = true;
shouldShow: boolean = true;
ariaLabel: string | null = null;
ariaDescription: string | null = null;
avatarLabel: string | null = null;
chipDestroy: (event?: MatChipEvent) => void = () => {};
chipSelectionChange: (event?: MatChipSelectionChange) => void = () => {};
} | {
"end_byte": 15470,
"start_byte": 11440,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-option.spec.ts"
} |
components/src/material/chips/module.ts_0_1498 | /**
* @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 {ENTER} from '@angular/cdk/keycodes';
import {NgModule} from '@angular/core';
import {ErrorStateMatcher, MatCommonModule, MatRippleModule} from '@angular/material/core';
import {MatChip} from './chip';
import {MAT_CHIPS_DEFAULT_OPTIONS, MatChipsDefaultOptions} from './tokens';
import {MatChipEditInput} from './chip-edit-input';
import {MatChipGrid} from './chip-grid';
import {MatChipAvatar, MatChipRemove, MatChipTrailingIcon} from './chip-icons';
import {MatChipInput} from './chip-input';
import {MatChipListbox} from './chip-listbox';
import {MatChipRow} from './chip-row';
import {MatChipOption} from './chip-option';
import {MatChipSet} from './chip-set';
import {MatChipAction} from './chip-action';
const CHIP_DECLARATIONS = [
MatChip,
MatChipAvatar,
MatChipEditInput,
MatChipGrid,
MatChipInput,
MatChipListbox,
MatChipOption,
MatChipRemove,
MatChipRow,
MatChipSet,
MatChipTrailingIcon,
];
@NgModule({
imports: [MatCommonModule, MatRippleModule, MatChipAction, CHIP_DECLARATIONS],
exports: [MatCommonModule, CHIP_DECLARATIONS],
providers: [
ErrorStateMatcher,
{
provide: MAT_CHIPS_DEFAULT_OPTIONS,
useValue: {
separatorKeyCodes: [ENTER],
} as MatChipsDefaultOptions,
},
],
})
export class MatChipsModule {}
| {
"end_byte": 1498,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/module.ts"
} |
components/src/material/chips/chip-input.spec.ts_0_9176 | import {Directionality} from '@angular/cdk/bidi';
import {COMMA, ENTER, TAB} from '@angular/cdk/keycodes';
import {PlatformModule} from '@angular/cdk/platform';
import {
createKeyboardEvent,
dispatchKeyboardEvent,
dispatchEvent,
} from '@angular/cdk/testing/private';
import {Component, DebugElement, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, waitForAsync} from '@angular/core/testing';
import {MatFormFieldModule} from '@angular/material/form-field';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {Subject} from 'rxjs';
import {
MAT_CHIPS_DEFAULT_OPTIONS,
MatChipGrid,
MatChipInput,
MatChipInputEvent,
MatChipsDefaultOptions,
MatChipsModule,
} from './index';
describe('MatChipInput', () => {
let fixture: ComponentFixture<any>;
let testChipInput: TestChipInput;
let inputDebugElement: DebugElement;
let inputNativeElement: HTMLElement;
let chipInputDirective: MatChipInput;
let dir = 'ltr';
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [PlatformModule, MatChipsModule, MatFormFieldModule, NoopAnimationsModule],
providers: [
{
provide: Directionality,
useFactory: () => {
return {
value: dir.toLowerCase(),
change: new Subject(),
};
},
},
],
declarations: [TestChipInput],
});
}));
beforeEach(waitForAsync(() => {
fixture = TestBed.createComponent(TestChipInput);
testChipInput = fixture.debugElement.componentInstance;
fixture.detectChanges();
inputDebugElement = fixture.debugElement.query(By.directive(MatChipInput))!;
chipInputDirective = inputDebugElement.injector.get<MatChipInput>(MatChipInput);
inputNativeElement = inputDebugElement.nativeElement;
}));
describe('basic behavior', () => {
it('emits the (chipEnd) on enter keyup', () => {
spyOn(testChipInput, 'add');
dispatchKeyboardEvent(inputNativeElement, 'keydown', ENTER);
expect(testChipInput.add).toHaveBeenCalled();
});
it('should have a default id', () => {
expect(inputNativeElement.getAttribute('id')).toBeTruthy();
});
it('should allow binding to the `placeholder` input', () => {
expect(inputNativeElement.hasAttribute('placeholder')).toBe(false);
testChipInput.placeholder = 'bound placeholder';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputNativeElement.getAttribute('placeholder')).toBe('bound placeholder');
});
it('should become disabled if the list is disabled', () => {
expect(inputNativeElement.hasAttribute('disabled')).toBe(false);
expect(chipInputDirective.disabled).toBe(false);
fixture.componentInstance.chipGridInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputNativeElement.getAttribute('disabled')).toBe('true');
expect(chipInputDirective.disabled).toBe(true);
});
it('should be aria-required if the list is required', () => {
expect(inputNativeElement.hasAttribute('aria-required')).toBe(false);
fixture.componentInstance.required = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputNativeElement.getAttribute('aria-required')).toBe('true');
});
it('should be required if the list is required', () => {
expect(inputNativeElement.hasAttribute('required')).toBe(false);
fixture.componentInstance.required = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputNativeElement.getAttribute('required')).toBe('true');
});
it('should allow focus to escape when tabbing forwards', fakeAsync(() => {
const gridElement: HTMLElement = fixture.nativeElement.querySelector('mat-chip-grid');
expect(gridElement.getAttribute('tabindex')).toBe('0');
dispatchKeyboardEvent(gridElement, 'keydown', TAB);
fixture.detectChanges();
expect(gridElement.getAttribute('tabindex'))
.withContext('Expected tabIndex to be set to -1 temporarily.')
.toBe('-1');
flush();
fixture.detectChanges();
expect(gridElement.getAttribute('tabindex'))
.withContext('Expected tabIndex to be reset back to 0')
.toBe('0');
}));
it('should set input styling classes', () => {
expect(inputNativeElement.classList).toContain('mat-mdc-input-element');
expect(inputNativeElement.classList).toContain('mat-mdc-form-field-input-control');
expect(inputNativeElement.classList).toContain('mat-mdc-chip-input');
expect(inputNativeElement.classList).toContain('mdc-text-field__input');
});
});
describe('[addOnBlur]', () => {
it('allows (chipEnd) when true', () => {
spyOn(testChipInput, 'add');
testChipInput.addOnBlur = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
chipInputDirective._blur();
expect(testChipInput.add).toHaveBeenCalled();
});
it('disallows (chipEnd) when false', () => {
spyOn(testChipInput, 'add');
testChipInput.addOnBlur = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
chipInputDirective._blur();
expect(testChipInput.add).not.toHaveBeenCalled();
});
});
describe('[separatorKeyCodes]', () => {
it('does not emit (chipEnd) when a non-separator key is pressed', () => {
spyOn(testChipInput, 'add');
chipInputDirective.separatorKeyCodes = [COMMA];
fixture.detectChanges();
dispatchKeyboardEvent(inputNativeElement, 'keydown', ENTER);
expect(testChipInput.add).not.toHaveBeenCalled();
});
it('emits (chipEnd) when a custom separator keys is pressed', () => {
spyOn(testChipInput, 'add');
chipInputDirective.separatorKeyCodes = [COMMA];
fixture.detectChanges();
dispatchKeyboardEvent(inputNativeElement, 'keydown', COMMA);
expect(testChipInput.add).toHaveBeenCalled();
});
it('emits accepts the custom separator keys in a Set', () => {
spyOn(testChipInput, 'add');
chipInputDirective.separatorKeyCodes = new Set([COMMA]);
fixture.detectChanges();
dispatchKeyboardEvent(inputNativeElement, 'keydown', COMMA);
expect(testChipInput.add).toHaveBeenCalled();
});
it('emits (chipEnd) when the separator keys are configured globally', () => {
fixture.destroy();
TestBed.resetTestingModule().configureTestingModule({
imports: [MatChipsModule, MatFormFieldModule, PlatformModule, NoopAnimationsModule],
declarations: [TestChipInput],
providers: [
{
provide: MAT_CHIPS_DEFAULT_OPTIONS,
useValue: {separatorKeyCodes: [COMMA]} as MatChipsDefaultOptions,
},
],
});
fixture = TestBed.createComponent(TestChipInput);
testChipInput = fixture.debugElement.componentInstance;
fixture.detectChanges();
inputDebugElement = fixture.debugElement.query(By.directive(MatChipInput))!;
chipInputDirective = inputDebugElement.injector.get<MatChipInput>(MatChipInput);
inputNativeElement = inputDebugElement.nativeElement;
spyOn(testChipInput, 'add');
fixture.detectChanges();
dispatchKeyboardEvent(inputNativeElement, 'keydown', COMMA);
expect(testChipInput.add).toHaveBeenCalled();
});
it('should not emit the chipEnd event if a separator is pressed with a modifier key', () => {
spyOn(testChipInput, 'add');
chipInputDirective.separatorKeyCodes = [ENTER];
fixture.detectChanges();
dispatchKeyboardEvent(inputNativeElement, 'keydown', ENTER, undefined, {shift: true});
expect(testChipInput.add).not.toHaveBeenCalled();
});
it('should set aria-describedby correctly when a non-empty list of ids is passed to setDescribedByIds', fakeAsync(() => {
const ids = ['a', 'b', 'c'];
testChipInput.chipGridInstance.setDescribedByIds(ids);
flush();
fixture.detectChanges();
expect(inputNativeElement.getAttribute('aria-describedby')).toEqual('a b c');
}));
it('should set aria-describedby correctly when an empty list of ids is passed to setDescribedByIds', fakeAsync(() => {
const ids: string[] = [];
testChipInput.chipGridInstance.setDescribedByIds(ids);
flush();
fixture.detectChanges();
expect(inputNativeElement.getAttribute('aria-describedby')).toBeNull();
}));
it('should not emit chipEnd if the key is repeated', () => {
spyOn(testChipInput, 'add');
chipInputDirective.separatorKeyCodes = [COMMA];
fixture.detectChanges();
const event = createKeyboardEvent('keydown', COMMA);
Object.defineProperty(event, 'repeat', {get: () => true});
dispatchEvent(inputNativeElement, event);
fixture.detectChanges();
expect(testChipInput.add).not.toHaveBeenCalled();
});
});
}); | {
"end_byte": 9176,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-input.spec.ts"
} |
components/src/material/chips/chip-input.spec.ts_9178_9781 | @Component({
template: `
<mat-form-field>
<mat-chip-grid #chipGrid [required]="required">
<mat-chip-row>Hello</mat-chip-row>
<input [matChipInputFor]="chipGrid"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)"
[placeholder]="placeholder" />
</mat-chip-grid>
</mat-form-field>
`,
standalone: false,
})
class TestChipInput {
@ViewChild(MatChipGrid) chipGridInstance: MatChipGrid;
addOnBlur: boolean = false;
placeholder = '';
required = false;
add(_: MatChipInputEvent) {}
} | {
"end_byte": 9781,
"start_byte": 9178,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-input.spec.ts"
} |
components/src/material/chips/chip-option.ts_0_7425 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
Input,
Output,
ViewEncapsulation,
OnInit,
inject,
booleanAttribute,
} from '@angular/core';
import {MatChip} from './chip';
import {MAT_CHIP, MAT_CHIPS_DEFAULT_OPTIONS} from './tokens';
import {MatChipAction} from './chip-action';
/** Event object emitted by MatChipOption when selected or deselected. */
export class MatChipSelectionChange {
constructor(
/** Reference to the chip that emitted the event. */
public source: MatChipOption,
/** Whether the chip that emitted the event is selected. */
public selected: boolean,
/** Whether the selection change was a result of a user interaction. */
public isUserInput = false,
) {}
}
/**
* An extension of the MatChip component that supports chip selection. Used with MatChipListbox.
*
* Unlike other chips, the user can focus on disabled chip options inside a MatChipListbox. The
* user cannot click disabled chips.
*/
@Component({
selector: 'mat-basic-chip-option, [mat-basic-chip-option], mat-chip-option, [mat-chip-option]',
templateUrl: 'chip-option.html',
styleUrl: 'chip.css',
host: {
'class': 'mat-mdc-chip mat-mdc-chip-option',
'[class.mdc-evolution-chip]': '!_isBasicChip',
'[class.mdc-evolution-chip--filter]': '!_isBasicChip',
'[class.mdc-evolution-chip--selectable]': '!_isBasicChip',
'[class.mat-mdc-chip-selected]': 'selected',
'[class.mat-mdc-chip-multiple]': '_chipListMultiple',
'[class.mat-mdc-chip-disabled]': 'disabled',
'[class.mat-mdc-chip-with-avatar]': 'leadingIcon',
'[class.mdc-evolution-chip--disabled]': 'disabled',
'[class.mdc-evolution-chip--selected]': 'selected',
// This class enables the transition on the checkmark. Usually MDC adds it when selection
// starts and removes it once the animation is finished. We don't need to go through all
// the trouble, because we only care about the selection animation. MDC needs to do it,
// because they also have an exit animation that we don't care about.
'[class.mdc-evolution-chip--selecting]': '!_animationsDisabled',
'[class.mdc-evolution-chip--with-trailing-action]': '_hasTrailingIcon()',
'[class.mdc-evolution-chip--with-primary-icon]': 'leadingIcon',
'[class.mdc-evolution-chip--with-primary-graphic]': '_hasLeadingGraphic()',
'[class.mdc-evolution-chip--with-avatar]': 'leadingIcon',
'[class.mat-mdc-chip-highlighted]': 'highlighted',
'[class.mat-mdc-chip-with-trailing-icon]': '_hasTrailingIcon()',
'[attr.tabindex]': 'null',
'[attr.aria-label]': 'null',
'[attr.aria-description]': 'null',
'[attr.role]': 'role',
'[id]': 'id',
},
providers: [
{provide: MatChip, useExisting: MatChipOption},
{provide: MAT_CHIP, useExisting: MatChipOption},
],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatChipAction],
})
export class MatChipOption extends MatChip implements OnInit {
/** Default chip options. */
private _defaultOptions = inject(MAT_CHIPS_DEFAULT_OPTIONS, {optional: true});
/** Whether the chip list is selectable. */
chipListSelectable: boolean = true;
/** Whether the chip list is in multi-selection mode. */
_chipListMultiple: boolean = false;
/** Whether the chip list hides single-selection indicator. */
_chipListHideSingleSelectionIndicator: boolean =
this._defaultOptions?.hideSingleSelectionIndicator ?? false;
/**
* Whether or not the chip is selectable.
*
* When a chip is not selectable, changes to its selected state are always
* ignored. By default an option chip is selectable, and it becomes
* non-selectable if its parent chip list is not selectable.
*/
@Input({transform: booleanAttribute})
get selectable(): boolean {
return this._selectable && this.chipListSelectable;
}
set selectable(value: boolean) {
this._selectable = value;
this._changeDetectorRef.markForCheck();
}
protected _selectable: boolean = true;
/** Whether the chip is selected. */
@Input({transform: booleanAttribute})
get selected(): boolean {
return this._selected;
}
set selected(value: boolean) {
this._setSelectedState(value, false, true);
}
private _selected = false;
/**
* The ARIA selected applied to the chip. Conforms to WAI ARIA best practices for listbox
* interaction patterns.
*
* From [WAI ARIA Listbox authoring practices guide](
* https://www.w3.org/WAI/ARIA/apg/patterns/listbox/):
* "If any options are selected, each selected option has either aria-selected or aria-checked
* set to true. All options that are selectable but not selected have either aria-selected or
* aria-checked set to false."
*
* Set `aria-selected="false"` on not-selected listbox options that are selectable to fix
* VoiceOver reading every option as "selected" (#25736).
*/
get ariaSelected(): string | null {
return this.selectable ? this.selected.toString() : null;
}
/** The unstyled chip selector for this component. */
protected override basicChipAttrName = 'mat-basic-chip-option';
/** Emitted when the chip is selected or deselected. */
@Output() readonly selectionChange: EventEmitter<MatChipSelectionChange> =
new EventEmitter<MatChipSelectionChange>();
override ngOnInit() {
super.ngOnInit();
this.role = 'presentation';
}
/** Selects the chip. */
select(): void {
this._setSelectedState(true, false, true);
}
/** Deselects the chip. */
deselect(): void {
this._setSelectedState(false, false, true);
}
/** Selects this chip and emits userInputSelection event */
selectViaInteraction(): void {
this._setSelectedState(true, true, true);
}
/** Toggles the current selected state of this chip. */
toggleSelected(isUserInput: boolean = false): boolean {
this._setSelectedState(!this.selected, isUserInput, true);
return this.selected;
}
override _handlePrimaryActionInteraction() {
if (!this.disabled) {
// Interacting with the primary action implies that the chip already has focus, however
// there's a bug in Safari where focus ends up lingering on the previous chip (see #27544).
// We work around it by explicitly focusing the primary action of the current chip.
this.focus();
if (this.selectable) {
this.toggleSelected(true);
}
}
}
_hasLeadingGraphic() {
if (this.leadingIcon) {
return true;
}
// The checkmark graphic communicates selected state for both single-select and multi-select.
// Include checkmark in single-select to fix a11y issue where selected state is communicated
// visually only using color (#25886).
return !this._chipListHideSingleSelectionIndicator || this._chipListMultiple;
}
_setSelectedState(isSelected: boolean, isUserInput: boolean, emitEvent: boolean) {
if (isSelected !== this.selected) {
this._selected = isSelected;
if (emitEvent) {
this.selectionChange.emit({
source: this,
isUserInput,
selected: this.selected,
});
}
this._changeDetectorRef.markForCheck();
}
}
}
| {
"end_byte": 7425,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-option.ts"
} |
components/src/material/chips/chip-icons.ts_0_2568 | /**
* @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 {ENTER, SPACE} from '@angular/cdk/keycodes';
import {Directive} from '@angular/core';
import {MatChipAction} from './chip-action';
import {MAT_CHIP_AVATAR, MAT_CHIP_REMOVE, MAT_CHIP_TRAILING_ICON} from './tokens';
/** Avatar image within a chip. */
@Directive({
selector: 'mat-chip-avatar, [matChipAvatar]',
host: {
'class': 'mat-mdc-chip-avatar mdc-evolution-chip__icon mdc-evolution-chip__icon--primary',
'role': 'img',
},
providers: [{provide: MAT_CHIP_AVATAR, useExisting: MatChipAvatar}],
})
export class MatChipAvatar {}
/** Non-interactive trailing icon in a chip. */
@Directive({
selector: 'mat-chip-trailing-icon, [matChipTrailingIcon]',
host: {
'class':
'mat-mdc-chip-trailing-icon mdc-evolution-chip__icon mdc-evolution-chip__icon--trailing',
'aria-hidden': 'true',
},
providers: [{provide: MAT_CHIP_TRAILING_ICON, useExisting: MatChipTrailingIcon}],
})
export class MatChipTrailingIcon extends MatChipAction {
/**
* MDC considers all trailing actions as a remove icon,
* but we support non-interactive trailing icons.
*/
override isInteractive = false;
override _isPrimary = false;
}
/**
* Directive to remove the parent chip when the trailing icon is clicked or
* when the ENTER key is pressed on it.
*
* Recommended for use with the Material Design "cancel" icon
* available at https://material.io/icons/#ic_cancel.
*
* Example:
*
* ```
* <mat-chip>
* <mat-icon matChipRemove>cancel</mat-icon>
* </mat-chip>
* ```
*/
@Directive({
selector: '[matChipRemove]',
host: {
'class':
'mat-mdc-chip-remove mat-mdc-chip-trailing-icon mat-focus-indicator ' +
'mdc-evolution-chip__icon mdc-evolution-chip__icon--trailing',
'role': 'button',
'[attr.aria-hidden]': 'null',
},
providers: [{provide: MAT_CHIP_REMOVE, useExisting: MatChipRemove}],
})
export class MatChipRemove extends MatChipAction {
override _isPrimary = false;
override _handleClick(event: MouseEvent): void {
if (!this.disabled) {
event.stopPropagation();
event.preventDefault();
this._parentChip.remove();
}
}
override _handleKeydown(event: KeyboardEvent) {
if ((event.keyCode === ENTER || event.keyCode === SPACE) && !this.disabled) {
event.stopPropagation();
event.preventDefault();
this._parentChip.remove();
}
}
}
| {
"end_byte": 2568,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-icons.ts"
} |
components/src/material/chips/public-api.ts_0_560 | /**
* @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 './chip';
export * from './chip-option';
export * from './chip-row';
export * from './chip-set';
export * from './chip-listbox';
export * from './chip-grid';
export * from './module';
export * from './chip-input';
export * from './tokens';
export * from './chip-icons';
export * from './chip-text-control';
export * from './chip-edit-input';
| {
"end_byte": 560,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/public-api.ts"
} |
components/src/material/chips/chip-grid.spec.ts_0_8661 | import {animate, style, transition, trigger} from '@angular/animations';
import {Direction, Directionality} from '@angular/cdk/bidi';
import {
BACKSPACE,
DELETE,
DOWN_ARROW,
END,
ENTER,
HOME,
LEFT_ARROW,
RIGHT_ARROW,
SPACE,
TAB,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {
createKeyboardEvent,
dispatchEvent,
dispatchFakeEvent,
dispatchKeyboardEvent,
patchElementFocus,
typeInElement,
} from '@angular/cdk/testing/private';
import {
ChangeDetectorRef,
Component,
DebugElement,
EventEmitter,
QueryList,
Type,
ViewChild,
ViewChildren,
inject,
} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing';
import {FormControl, FormsModule, NgForm, ReactiveFormsModule, Validators} from '@angular/forms';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import {By} from '@angular/platform-browser';
import {BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatChipEvent, MatChipGrid, MatChipInputEvent, MatChipRow, MatChipsModule} from './index';
describe('MatChipGrid', () => {
let chipGridDebugElement: DebugElement;
let chipGridNativeElement: HTMLElement;
let chipGridInstance: MatChipGrid;
let chips: QueryList<MatChipRow>;
let testComponent: StandardChipGrid;
let directionality: {value: Direction; change: EventEmitter<Direction>};
let primaryActions: NodeListOf<HTMLElement>;
const expectNoCellFocused = () => {
expect(Array.from(primaryActions)).not.toContain(document.activeElement as HTMLElement);
};
const expectLastCellFocused = () => {
expect(document.activeElement).toBe(primaryActions[primaryActions.length - 1]);
};
describe('StandardChipGrid', () => {
describe('basic behaviors', () => {
let fixture: ComponentFixture<StandardChipGrid>;
beforeEach(() => {
fixture = createComponent(StandardChipGrid);
});
it('should add the `mat-mdc-chip-set` class', () => {
expect(chipGridNativeElement.classList).toContain('mat-mdc-chip-set');
});
it('should toggle the chips disabled state based on whether it is disabled', () => {
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
chipGridInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(true);
chipGridInstance.disabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
});
it('should disable a chip that is added after the list became disabled', fakeAsync(() => {
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
chipGridInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(true);
fixture.componentInstance.chips.push(5, 6);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(true);
}));
it('should not set a role on the grid when the list is empty', () => {
testComponent.chips = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipGridNativeElement.hasAttribute('role')).toBe(false);
});
it('should be able to set a custom role', () => {
testComponent.role = 'listbox';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipGridNativeElement.getAttribute('role')).toBe('listbox');
});
});
describe('focus behaviors', () => {
let fixture:
| ComponentFixture<StandardChipGrid>
| ComponentFixture<StandardChipGridWithAnimations>;
beforeEach(() => {
fixture = createComponent(StandardChipGrid);
});
it('should focus the first chip on focus', () => {
chipGridInstance.focus();
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[0]);
});
it('should focus the primary action when calling the `focus` method', () => {
chips.last.focus();
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[primaryActions.length - 1]);
});
it('should not be able to become focused when disabled', () => {
expect(chipGridInstance.focused)
.withContext('Expected grid to not be focused.')
.toBe(false);
chipGridInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
chipGridInstance.focus();
fixture.detectChanges();
expect(chipGridInstance.focused)
.withContext('Expected grid to continue not to be focused')
.toBe(false);
});
it('should remove the tabindex from the grid if it is disabled', () => {
expect(chipGridNativeElement.getAttribute('tabindex')).toBe('0');
chipGridInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipGridNativeElement.getAttribute('tabindex')).toBe('-1');
});
describe('on chip destroy', () => {
it('should focus the next item', () => {
const midItem = chips.get(2)!;
// Focus the middle item
midItem.focus();
// Destroy the middle item
testComponent.chips.splice(2, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// It focuses the 4th item
expect(document.activeElement).toBe(primaryActions[3]);
});
it('should focus the previous item', () => {
// Focus the last item
chips.last.focus();
// Destroy the last item
testComponent.chips.pop();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// It focuses the next-to-last item
expect(document.activeElement).toBe(primaryActions[primaryActions.length - 2]);
});
it('should not focus if chip grid is not focused', fakeAsync(() => {
const midItem = chips.get(2)!;
// Focus and blur the middle item
midItem.focus();
(document.activeElement as HTMLElement).blur();
tick();
// Destroy the middle item
testComponent.chips.splice(2, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
// Should not have focus
expect(chipGridNativeElement.contains(document.activeElement)).toBe(false);
}));
it('should focus the grid if the last focused item is removed', () => {
testComponent.chips = [0];
fixture.changeDetectorRef.markForCheck();
spyOn(chipGridInstance, 'focus');
patchElementFocus(chips.last.primaryAction!._elementRef.nativeElement);
chips.last.focus();
testComponent.chips.pop();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipGridInstance.focus).toHaveBeenCalled();
});
it('should move focus to the last chip when the focused chip was deleted inside a component with animations', fakeAsync(() => {
fixture.destroy();
TestBed.resetTestingModule();
fixture = createComponent(StandardChipGridWithAnimations, BrowserAnimationsModule);
patchElementFocus(chips.last.primaryAction!._elementRef.nativeElement);
chips.last.focus();
fixture.detectChanges();
dispatchKeyboardEvent(chips.last._elementRef.nativeElement, 'keydown', BACKSPACE);
fixture.detectChanges();
tick(500);
expect(document.activeElement).toBe(primaryActions[primaryActions.length - 2]);
}));
});
it('should have a focus indicator', () => {
const focusIndicators = chipGridNativeElement.querySelectorAll(
'.mat-mdc-chip-primary-focus-indicator',
);
expect(focusIndicators.length).toBeGreaterThan(0);
expect(focusIndicators.length).toBe(chips.length);
});
}); | {
"end_byte": 8661,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-grid.spec.ts"
} |
components/src/material/chips/chip-grid.spec.ts_8667_17868 | describe('keyboard behavior', () => {
describe('LTR (default)', () => {
let fixture: ComponentFixture<ChipGridWithRemove>;
let trailingActions: NodeListOf<HTMLElement>;
beforeEach(fakeAsync(() => {
fixture = createComponent(ChipGridWithRemove);
flush();
trailingActions = chipGridNativeElement.querySelectorAll(
'.mdc-evolution-chip__action--trailing',
);
}));
it('should focus previous column when press LEFT ARROW', () => {
const lastIndex = primaryActions.length - 1;
// Focus the first column of the last chip in the array
chips.last.focus();
expect(document.activeElement).toBe(primaryActions[lastIndex]);
// Press the LEFT arrow
dispatchKeyboardEvent(primaryActions[lastIndex], 'keydown', LEFT_ARROW);
fixture.detectChanges();
// It focuses the last column of the previous chip
expect(document.activeElement).toBe(trailingActions[lastIndex - 1]);
});
it('should focus next column when press RIGHT ARROW', () => {
// Focus the first column of the first chip in the array
chips.first.focus();
expect(document.activeElement).toBe(primaryActions[0]);
// Press the RIGHT arrow
dispatchKeyboardEvent(primaryActions[0], 'keydown', RIGHT_ARROW);
fixture.detectChanges();
// It focuses the next column of the chip
expect(document.activeElement).toBe(trailingActions[0]);
});
it('should not handle arrow key events from non-chip elements', () => {
const previousActiveElement = document.activeElement;
dispatchKeyboardEvent(chipGridNativeElement, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement)
.withContext('Expected focused item not to have changed.')
.toBe(previousActiveElement);
});
it('should focus primary action in next row when pressing DOWN ARROW on primary action', () => {
chips.first.focus();
expect(document.activeElement).toBe(primaryActions[0]);
dispatchKeyboardEvent(primaryActions[0], 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[1]);
});
it('should focus primary action in previous row when pressing UP ARROW on primary action', () => {
const lastIndex = primaryActions.length - 1;
chips.last.focus();
expect(document.activeElement).toBe(primaryActions[lastIndex]);
dispatchKeyboardEvent(primaryActions[lastIndex], 'keydown', UP_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[lastIndex - 1]);
});
it('should focus(trailing action in next row when pressing DOWN ARROW on(trailing action', () => {
trailingActions[0].focus();
expect(document.activeElement).toBe(trailingActions[0]);
dispatchKeyboardEvent(trailingActions[0], 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(trailingActions[1]);
});
it('should focus trailing action in previous row when pressing UP ARROW on trailing action', () => {
const lastIndex = trailingActions.length - 1;
trailingActions[lastIndex].focus();
expect(document.activeElement).toBe(trailingActions[lastIndex]);
dispatchKeyboardEvent(trailingActions[lastIndex], 'keydown', UP_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(trailingActions[lastIndex - 1]);
});
});
describe('RTL', () => {
let fixture: ComponentFixture<StandardChipGrid>;
beforeEach(() => {
fixture = createComponent(StandardChipGrid, undefined, 'rtl');
});
it('should focus previous column when press RIGHT ARROW', () => {
const lastIndex = primaryActions.length - 1;
// Focus the first column of the last chip in the array
chips.last.focus();
expect(document.activeElement).toBe(primaryActions[lastIndex]);
// Press the RIGHT arrow
dispatchKeyboardEvent(primaryActions[lastIndex], 'keydown', RIGHT_ARROW);
fixture.detectChanges();
// It focuses the last column of the previous chip
expect(document.activeElement).toBe(primaryActions[lastIndex - 1]);
});
it('should focus next column when press LEFT ARROW', () => {
// Focus the first column of the first chip in the array
chips.first.focus();
expect(document.activeElement).toBe(primaryActions[0]);
// Press the LEFT arrow
dispatchKeyboardEvent(primaryActions[0], 'keydown', LEFT_ARROW);
fixture.detectChanges();
// It focuses the next column of the chip
expect(document.activeElement).toBe(primaryActions[1]);
});
it('should allow focus to escape when tabbing away', fakeAsync(() => {
let nativeChips = chipGridNativeElement.querySelectorAll('mat-chip-row');
let firstNativeChip = nativeChips[0] as HTMLElement;
dispatchKeyboardEvent(firstNativeChip, 'keydown', TAB);
expect(chipGridNativeElement.tabIndex)
.withContext('Expected tabIndex to be set to -1 temporarily.')
.toBe(-1);
flush();
expect(chipGridNativeElement.tabIndex)
.withContext('Expected tabIndex to be reset back to 0')
.toBe(0);
}));
it('should use user defined tabIndex', fakeAsync(() => {
chipGridInstance.tabIndex = 4;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipGridNativeElement.tabIndex)
.withContext('Expected tabIndex to be set to user defined value 4.')
.toBe(4);
let nativeChips = chipGridNativeElement.querySelectorAll('mat-chip-row');
let firstNativeChip = nativeChips[0] as HTMLElement;
dispatchKeyboardEvent(firstNativeChip, 'keydown', TAB);
expect(chipGridNativeElement.tabIndex)
.withContext('Expected tabIndex to be set to -1 temporarily.')
.toBe(-1);
flush();
expect(chipGridNativeElement.tabIndex)
.withContext('Expected tabIndex to be reset back to 4')
.toBe(4);
}));
});
describe('keydown behavior', () => {
let fixture: ComponentFixture<StandardChipGrid>;
beforeEach(() => {
fixture = createComponent(StandardChipGrid);
});
it('should account for the direction changing', () => {
chips.first.focus();
expect(document.activeElement).toBe(primaryActions[0]);
dispatchKeyboardEvent(primaryActions[0], 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[1]);
directionality.value = 'rtl';
directionality.change.next('rtl');
fixture.detectChanges();
dispatchKeyboardEvent(primaryActions[1], 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[0]);
});
it('should move focus to the first chip when pressing HOME', () => {
chips.last.focus();
expect(document.activeElement).toBe(primaryActions[4]);
const event = dispatchKeyboardEvent(primaryActions[4], 'keydown', HOME);
fixture.detectChanges();
expect(event.defaultPrevented).toBe(true);
expect(document.activeElement).toBe(primaryActions[0]);
});
it('should move focus to the last chip when pressing END', () => {
chips.first.focus();
expect(document.activeElement).toBe(primaryActions[0]);
const event = dispatchKeyboardEvent(primaryActions[0], 'keydown', END);
fixture.detectChanges();
expect(event.defaultPrevented).toBe(true);
expect(document.activeElement).toBe(primaryActions[4]);
});
it('should ignore all non-tab navigation keyboard events from an editing chip', fakeAsync(() => {
testComponent.editable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
chips.first.focus();
expect(document.activeElement).toBe(primaryActions[0]);
dispatchKeyboardEvent(document.activeElement!, 'keydown', ENTER);
fixture.detectChanges();
flush();
const previousActiveElement = document.activeElement;
const keysToIgnore = [HOME, END, LEFT_ARROW, RIGHT_ARROW];
for (const key of keysToIgnore) {
dispatchKeyboardEvent(document.activeElement!, 'keydown', key);
fixture.detectChanges();
flush();
expect(document.activeElement).toBe(previousActiveElement);
}
}));
});
});
}); | {
"end_byte": 17868,
"start_byte": 8667,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-grid.spec.ts"
} |
components/src/material/chips/chip-grid.spec.ts_17872_21349 | describe('FormFieldChipGrid', () => {
let fixture: ComponentFixture<FormFieldChipGrid>;
beforeEach(() => {
fixture = createComponent(FormFieldChipGrid);
});
describe('keyboard behavior', () => {
it('should maintain focus if the active chip is deleted', () => {
const secondChip = fixture.nativeElement.querySelectorAll('.mat-mdc-chip')[1];
const secondChipAction = secondChip.querySelector('.mdc-evolution-chip__action--primary');
secondChipAction.focus();
fixture.detectChanges();
expect(chipGridInstance._chips.toArray().findIndex(chip => chip._hasFocus())).toBe(1);
dispatchKeyboardEvent(secondChip, 'keydown', DELETE);
fixture.detectChanges();
expect(chipGridInstance._chips.toArray().findIndex(chip => chip._hasFocus())).toBe(1);
});
describe('when the input has focus', () => {
it('should not focus the last chip when press DELETE', () => {
let nativeInput = fixture.nativeElement.querySelector('input');
// Focus the input
nativeInput.focus();
expectNoCellFocused();
// Press the DELETE key
dispatchKeyboardEvent(nativeInput, 'keydown', DELETE);
fixture.detectChanges();
// It doesn't focus the last chip
expectNoCellFocused();
});
it('should focus the last chip when press BACKSPACE', () => {
let nativeInput = fixture.nativeElement.querySelector('input');
// Focus the input
nativeInput.focus();
expectNoCellFocused();
// Press the BACKSPACE key
dispatchKeyboardEvent(nativeInput, 'keydown', BACKSPACE);
fixture.detectChanges();
// It focuses the last chip
expectLastCellFocused();
});
it('should not focus the last chip when pressing BACKSPACE on a non-empty input', () => {
const nativeInput = fixture.nativeElement.querySelector('input');
nativeInput.value = 'hello';
nativeInput.focus();
fixture.detectChanges();
expectNoCellFocused();
dispatchKeyboardEvent(nativeInput, 'keydown', BACKSPACE);
fixture.detectChanges();
expectNoCellFocused();
});
});
});
it('should complete the stateChanges stream on destroy', () => {
const spy = jasmine.createSpy('stateChanges complete');
const subscription = chipGridInstance.stateChanges.subscribe({complete: spy});
fixture.destroy();
expect(spy).toHaveBeenCalled();
subscription.unsubscribe();
});
});
describe('with chip remove', () => {
let fixture: ComponentFixture<ChipGridWithRemove>;
let trailingActions: NodeListOf<HTMLElement>;
beforeEach(fakeAsync(() => {
fixture = createComponent(ChipGridWithRemove);
flush();
trailingActions = chipGridNativeElement.querySelectorAll(
'.mdc-evolution-chip__action--trailing',
);
}));
it('should properly focus next item if chip is removed through click', fakeAsync(() => {
const chip = chips.get(2)!;
chip.focus();
fixture.detectChanges();
// Destroy the third focused chip by dispatching a bubbling click event on the
// associated chip remove element.
trailingActions[2].click();
fixture.detectChanges();
flush();
expect(document.activeElement).toBe(primaryActions[3]);
}));
}); | {
"end_byte": 21349,
"start_byte": 17872,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-grid.spec.ts"
} |
components/src/material/chips/chip-grid.spec.ts_21353_30454 | describe('chip grid with chip input', () => {
let fixture: ComponentFixture<InputChipGrid>;
let nativeChips: HTMLElement[];
let nativeInput: HTMLInputElement;
let nativeChipGrid: HTMLElement;
beforeEach(() => {
fixture = createComponent(InputChipGrid);
nativeChips = fixture.debugElement
.queryAll(By.css('mat-chip-row'))
.map(chip => chip.nativeElement);
nativeChipGrid = fixture.debugElement.query(By.css('mat-chip-grid'))!.nativeElement;
nativeInput = fixture.nativeElement.querySelector('input');
});
it('should take an initial view value with reactive forms', () => {
fixture.componentInstance.control = new FormControl('[pizza-1]');
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.chipGrid.value).toEqual('[pizza-1]');
});
it('should set the view value from the form', () => {
const chipGrid = fixture.componentInstance.chipGrid;
expect(chipGrid.value).withContext('Expect chip grid to have no initial value').toBeFalsy();
fixture.componentInstance.control.setValue('[pizza-1]');
fixture.detectChanges();
expect(chipGrid.value).toEqual('[pizza-1]');
});
it('should update the form value when the view changes', fakeAsync(() => {
expect(fixture.componentInstance.control.value)
.withContext(`Expected the control's value to be empty initially.`)
.toEqual(null);
nativeInput.focus();
typeInElement(nativeInput, '123');
fixture.detectChanges();
dispatchKeyboardEvent(nativeInput, 'keydown', ENTER);
fixture.detectChanges();
flush();
dispatchFakeEvent(nativeInput, 'blur');
flush();
expect(fixture.componentInstance.control.value).toContain('123-8');
}));
it('should clear the value when the control is reset', () => {
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
fixture.componentInstance.control.reset();
fixture.detectChanges();
expect(fixture.componentInstance.chipGrid.value).toEqual(null);
});
it('should set the control to touched when the chip grid is touched', fakeAsync(() => {
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to start off as untouched.')
.toBe(false);
dispatchFakeEvent(nativeChipGrid, 'blur');
tick();
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to be touched.')
.toBe(true);
}));
it('should not set touched when a disabled chip grid is touched', fakeAsync(() => {
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to start off as untouched.')
.toBe(false);
fixture.componentInstance.control.disable();
dispatchFakeEvent(nativeChipGrid, 'blur');
tick();
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to stay untouched.')
.toBe(false);
}));
it("should set the control to dirty when the chip grid's value changes in the DOM", fakeAsync(() => {
expect(fixture.componentInstance.control.dirty)
.withContext(`Expected control to start out pristine.`)
.toEqual(false);
nativeInput.focus();
typeInElement(nativeInput, '123');
fixture.detectChanges();
dispatchKeyboardEvent(nativeInput, 'keydown', ENTER);
fixture.detectChanges();
flush();
dispatchFakeEvent(nativeInput, 'blur');
flush();
expect(fixture.componentInstance.control.dirty)
.withContext(`Expected control to be dirty after value was changed by user.`)
.toEqual(true);
}));
it('should not set the control to dirty when the value changes programmatically', () => {
expect(fixture.componentInstance.control.dirty)
.withContext(`Expected control to start out pristine.`)
.toEqual(false);
fixture.componentInstance.control.setValue('pizza-1');
expect(fixture.componentInstance.control.dirty)
.withContext(`Expected control to stay pristine after programmatic change.`)
.toEqual(false);
});
it('should set an asterisk after the placeholder if the control is required', () => {
let requiredMarker = fixture.debugElement.query(
By.css('.mat-mdc-form-field-required-marker'),
)!;
expect(requiredMarker)
.withContext(`Expected placeholder not to have an asterisk, as control was not required.`)
.toBeNull();
fixture.componentInstance.chipGrid.required = true;
fixture.detectChanges();
requiredMarker = fixture.debugElement.query(By.css('.mat-mdc-form-field-required-marker'))!;
expect(requiredMarker)
.not.withContext(`Expected placeholder to have an asterisk, as control was required.`)
.toBeNull();
});
it('should mark the component as required if the control has a required validator', () => {
fixture.destroy();
fixture = TestBed.createComponent(InputChipGrid);
fixture.componentInstance.control = new FormControl('', [Validators.required]);
fixture.detectChanges();
expect(
fixture.nativeElement.querySelector('.mat-mdc-form-field-required-marker'),
).toBeTruthy();
});
it('should blur the form field when the active chip is blurred', fakeAsync(() => {
const formField: HTMLElement = fixture.nativeElement.querySelector('.mat-mdc-form-field');
const firstAction = nativeChips[0].querySelector('.mat-mdc-chip-action') as HTMLElement;
patchElementFocus(firstAction);
firstAction.focus();
fixture.detectChanges();
expect(formField.classList).toContain('mat-focused');
firstAction.blur();
fixture.detectChanges();
fixture.detectChanges();
fixture.detectChanges();
flush();
expect(formField.classList).not.toContain('mat-focused');
}));
it('should keep focus on the input after adding the first chip', fakeAsync(() => {
const chipEls = Array.from<HTMLElement>(
fixture.nativeElement.querySelectorAll('mat-chip-row'),
).reverse();
// Remove the chips via backspace to simulate the user removing them.
chipEls.forEach(chip => {
chip.focus();
dispatchKeyboardEvent(chip, 'keydown', BACKSPACE);
fixture.detectChanges();
tick();
});
nativeInput.focus();
expect(fixture.componentInstance.foods)
.withContext('Expected all chips to be removed.')
.toEqual([]);
expect(document.activeElement).withContext('Expected input to be focused.').toBe(nativeInput);
typeInElement(nativeInput, '123');
fixture.detectChanges();
dispatchKeyboardEvent(nativeInput, 'keydown', ENTER);
fixture.detectChanges();
tick();
expect(document.activeElement)
.withContext('Expected input to remain focused.')
.toBe(nativeInput);
}));
it('should set aria-invalid if the form field is invalid', fakeAsync(() => {
fixture.componentInstance.control = new FormControl('', [Validators.required]);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const input: HTMLInputElement = fixture.nativeElement.querySelector('input');
expect(input.getAttribute('aria-invalid')).toBe('true');
typeInElement(input, '123');
fixture.detectChanges();
dispatchKeyboardEvent(input, 'keydown', ENTER);
fixture.detectChanges();
flush();
dispatchFakeEvent(input, 'blur');
flush();
fixture.detectChanges();
expect(input.getAttribute('aria-invalid')).toBe('false');
}));
describe('when the input has focus', () => {
beforeEach(() => {
nativeInput.focus();
expectNoCellFocused();
});
it('should not focus the last chip when pressing DELETE', () => {
dispatchKeyboardEvent(nativeInput, 'keydown', DELETE);
expectNoCellFocused();
});
it('should focus the last chip when pressing BACKSPACE when input is empty', () => {
dispatchKeyboardEvent(nativeInput, 'keydown', BACKSPACE);
expectLastCellFocused();
});
it('should not focus the last chip when the BACKSPACE key is being repeated', () => {
// Only now should it focus the last element
const event = createKeyboardEvent('keydown', BACKSPACE);
Object.defineProperty(event, 'repeat', {
get: () => true,
});
dispatchEvent(nativeInput, event);
expectNoCellFocused();
});
it('should focus last chip after pressing BACKSPACE after creating a chip', () => {
// Create a chip
typeInElement(nativeInput, '123');
dispatchKeyboardEvent(nativeInput, 'keydown', ENTER);
expectNoCellFocused();
dispatchKeyboardEvent(nativeInput, 'keydown', BACKSPACE);
expectLastCellFocused();
});
});
}); | {
"end_byte": 30454,
"start_byte": 21353,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-grid.spec.ts"
} |
components/src/material/chips/chip-grid.spec.ts_30458_38928 | describe('error messages', () => {
let fixture: ComponentFixture<ChipGridWithFormErrorMessages>;
let errorTestComponent: ChipGridWithFormErrorMessages;
let containerEl: HTMLElement;
let chipGridEl: HTMLElement;
let inputEl: HTMLElement;
beforeEach(fakeAsync(() => {
fixture = createComponent(ChipGridWithFormErrorMessages);
flush();
fixture.detectChanges();
errorTestComponent = fixture.componentInstance;
containerEl = fixture.debugElement.query(By.css('mat-form-field'))!.nativeElement;
chipGridEl = fixture.debugElement.query(By.css('mat-chip-grid'))!.nativeElement;
inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
}));
it('should not show any errors if the user has not interacted', () => {
expect(errorTestComponent.formControl.untouched)
.withContext('Expected untouched form control')
.toBe(true);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error message')
.toBe(0);
expect(chipGridEl.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to "false".')
.toBe('false');
});
it('should display an error message when the grid is touched and invalid', fakeAsync(() => {
expect(errorTestComponent.formControl.invalid)
.withContext('Expected form control to be invalid')
.toBe(true);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error message')
.toBe(0);
errorTestComponent.formControl.markAsTouched();
fixture.detectChanges();
tick();
expect(containerEl.classList)
.withContext('Expected container to have the invalid CSS class.')
.toContain('mat-form-field-invalid');
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected one error message to have been rendered.')
.toBe(1);
expect(chipGridEl.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to "true".')
.toBe('true');
}));
it('should display an error message when the parent form is submitted', fakeAsync(() => {
expect(errorTestComponent.form.submitted)
.withContext('Expected form not to have been submitted')
.toBe(false);
expect(errorTestComponent.formControl.invalid)
.withContext('Expected form control to be invalid')
.toBe(true);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error message')
.toBe(0);
dispatchFakeEvent(fixture.debugElement.query(By.css('form'))!.nativeElement, 'submit');
flush();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(errorTestComponent.form.submitted)
.withContext('Expected form to have been submitted')
.toBe(true);
expect(containerEl.classList)
.withContext('Expected container to have the invalid CSS class.')
.toContain('mat-form-field-invalid');
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected one error message to have been rendered.')
.toBe(1);
expect(chipGridEl.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to "true".')
.toBe('true');
});
flush();
}));
it('should hide the errors and show the hints once the chip grid becomes valid', fakeAsync(() => {
errorTestComponent.formControl.markAsTouched();
flush();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(containerEl.classList)
.withContext('Expected container to have the invalid CSS class.')
.toContain('mat-form-field-invalid');
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected one error message to have been rendered.')
.toBe(1);
expect(containerEl.querySelectorAll('mat-hint').length)
.withContext('Expected no hints to be shown.')
.toBe(0);
errorTestComponent.formControl.setValue('something');
flush();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(containerEl.classList).not.toContain(
'mat-form-field-invalid',
'Expected container not to have the invalid class when valid.',
);
expect(containerEl.querySelectorAll('mat-error').length)
.withContext('Expected no error messages when the input is valid.')
.toBe(0);
expect(containerEl.querySelectorAll('mat-hint').length)
.withContext('Expected one hint to be shown once the input is valid.')
.toBe(1);
});
flush();
});
}));
it('should set the proper aria-live attribute on the error messages', () => {
errorTestComponent.formControl.markAsTouched();
fixture.detectChanges();
expect(containerEl.querySelector('mat-error')!.getAttribute('aria-live')).toBe('polite');
});
it('sets the aria-describedby on the input to reference errors when in error state', fakeAsync(() => {
let hintId = fixture.debugElement
.query(By.css('.mat-mdc-form-field-hint'))!
.nativeElement.getAttribute('id');
let describedBy = inputEl.getAttribute('aria-describedby');
expect(hintId).withContext('hint should be shown').toBeTruthy();
expect(describedBy).toBe(hintId);
fixture.componentInstance.formControl.markAsTouched();
fixture.detectChanges();
// Flush the describedby timer and detect changes caused by it.
flush();
fixture.detectChanges();
let errorIds = fixture.debugElement
.queryAll(By.css('.mat-mdc-form-field-error'))
.map(el => el.nativeElement.getAttribute('id'))
.join(' ');
let errorDescribedBy = inputEl.getAttribute('aria-describedby');
expect(errorIds).withContext('errors should be shown').toBeTruthy();
expect(errorDescribedBy).toBe(errorIds);
}));
});
function createComponent<T>(
component: Type<T>,
animationsModule:
| Type<NoopAnimationsModule>
| Type<BrowserAnimationsModule> = NoopAnimationsModule,
direction: Direction = 'ltr',
): ComponentFixture<T> {
directionality = {
value: direction,
change: new EventEmitter<Direction>(),
} as Directionality;
TestBed.configureTestingModule({
imports: [
FormsModule,
ReactiveFormsModule,
MatChipsModule,
MatFormFieldModule,
MatInputModule,
animationsModule,
],
providers: [{provide: Directionality, useValue: directionality}],
declarations: [component],
});
const fixture = TestBed.createComponent<T>(component);
fixture.detectChanges();
chipGridDebugElement = fixture.debugElement.query(By.directive(MatChipGrid))!;
chipGridNativeElement = chipGridDebugElement.nativeElement;
chipGridInstance = chipGridDebugElement.componentInstance;
testComponent = fixture.debugElement.componentInstance;
chips = chipGridInstance._chips;
primaryActions = chipGridNativeElement.querySelectorAll<HTMLElement>(
'.mdc-evolution-chip__action--primary',
);
return fixture;
}
});
@Component({
template: `
<mat-chip-grid [tabIndex]="tabIndex" [role]="role" #chipGrid>
@for (i of chips; track i) {
<mat-chip-row [editable]="editable">{{name}} {{i + 1}}</mat-chip-row>
}
</mat-chip-grid>
<input name="test" [matChipInputFor]="chipGrid"/>`,
standalone: false,
})
class StandardChipGrid {
name: string = 'Test';
tabIndex: number = 0;
chips = [0, 1, 2, 3, 4];
editable = false;
role: string | null = null;
}
@Component({
template: `
<mat-form-field>
<mat-label>Add a chip</mat-label>
<mat-chip-grid #chipGrid>
@for (chip of chips; track chip) {
<mat-chip-row (removed)="remove(chip)">{{chip}}</mat-chip-row>
}
</mat-chip-grid>
<input name="test" [matChipInputFor]="chipGrid"/>
</mat-form-field>
`,
standalone: false,
})
class FormFieldChipGrid {
chips = ['Chip 0', 'Chip 1', 'Chip 2'];
remove(chip: string) {
const index = this.chips.indexOf(chip);
if (index > -1) {
this.chips.splice(index, 1);
}
}
} | {
"end_byte": 38928,
"start_byte": 30458,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-grid.spec.ts"
} |
components/src/material/chips/chip-grid.spec.ts_38930_43043 | @Component({
template: `
<mat-form-field>
<mat-label>New food...</mat-label>
<mat-chip-grid #chipGrid placeholder="Food" [formControl]="control">
@for (food of foods; track food) {
<mat-chip-row [value]="food.value" (removed)="remove(food)">
{{ food.viewValue }}
</mat-chip-row>
}
</mat-chip-grid>
<input
[matChipInputFor]="chipGrid"
[matChipInputSeparatorKeyCodes]="separatorKeyCodes"
[matChipInputAddOnBlur]="addOnBlur"
(matChipInputTokenEnd)="add($event)"/>
</mat-form-field>
`,
standalone: false,
})
class InputChipGrid {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos', disabled: true},
{value: 'sandwich-3', viewValue: 'Sandwich'},
{value: 'chips-4', viewValue: 'Chips'},
{value: 'eggs-5', viewValue: 'Eggs'},
{value: 'pasta-6', viewValue: 'Pasta'},
{value: 'sushi-7', viewValue: 'Sushi'},
];
control = new FormControl<string | null>(null);
separatorKeyCodes = [ENTER, SPACE];
addOnBlur: boolean = true;
add(event: MatChipInputEvent): void {
const value = (event.value || '').trim();
// Add our foods
if (value) {
this.foods.push({
value: `${value.toLowerCase()}-${this.foods.length}`,
viewValue: value,
});
}
// Reset the input value
event.chipInput!.clear();
}
remove(food: any): void {
const index = this.foods.indexOf(food);
if (index > -1) {
this.foods.splice(index, 1);
}
}
@ViewChild(MatChipGrid) chipGrid: MatChipGrid;
@ViewChildren(MatChipRow) chips: QueryList<MatChipRow>;
}
@Component({
template: `
<form #form="ngForm" novalidate>
<mat-form-field>
<mat-chip-grid #chipGrid [formControl]="formControl">
@for (food of foods; track food) {
<mat-chip-row [value]="food.value">{{food.viewValue}}</mat-chip-row>
}
</mat-chip-grid>
<input name="test" [matChipInputFor]="chipGrid"/>
<mat-hint>Please select a chip, or type to add a new chip</mat-hint>
<mat-error>Should have value</mat-error>
</mat-form-field>
</form>
`,
standalone: false,
})
class ChipGridWithFormErrorMessages {
foods: any[] = [
{value: 0, viewValue: 'Steak'},
{value: 1, viewValue: 'Pizza'},
{value: 2, viewValue: 'Pasta'},
];
@ViewChildren(MatChipRow) chips: QueryList<MatChipRow>;
@ViewChild('form') form: NgForm;
formControl = new FormControl('', Validators.required);
private readonly _changeDetectorRef = inject(ChangeDetectorRef);
constructor() {
this.formControl.events.pipe(takeUntilDestroyed()).subscribe(() => {
this._changeDetectorRef.markForCheck();
});
}
}
@Component({
template: `
<mat-chip-grid #chipGrid>
@for (i of numbers; track i) {
<mat-chip-row (removed)="remove(i)">{{i}}</mat-chip-row>
}
<input name="test" [matChipInputFor]="chipGrid"/>
</mat-chip-grid>`,
animations: [
// For the case we're testing this animation doesn't
// have to be used anywhere, it just has to be defined.
trigger('dummyAnimation', [
transition(':leave', [style({opacity: 0}), animate('500ms', style({opacity: 1}))]),
]),
],
standalone: false,
})
class StandardChipGridWithAnimations {
numbers = [0, 1, 2, 3, 4];
remove(item: number): void {
const index = this.numbers.indexOf(item);
if (index > -1) {
this.numbers.splice(index, 1);
}
}
}
@Component({
template: `
<mat-form-field>
<mat-chip-grid #chipGrid>
@for (i of chips; track i) {
<mat-chip-row [value]="i" (removed)="removeChip($event)">
Chip {{i + 1}}
<span matChipRemove>Remove</span>
</mat-chip-row>
}
</mat-chip-grid>
<input name="test" [matChipInputFor]="chipGrid"/>
</mat-form-field>
`,
standalone: false,
})
class ChipGridWithRemove {
chips = [0, 1, 2, 3, 4];
removeChip(event: MatChipEvent) {
this.chips.splice(event.chip.value, 1);
}
} | {
"end_byte": 43043,
"start_byte": 38930,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-grid.spec.ts"
} |
components/src/material/chips/chip-option.html_0_1464 | <span class="mat-mdc-chip-focus-overlay"></span>
<span class="mdc-evolution-chip__cell mdc-evolution-chip__cell--primary">
<button
matChipAction
[_allowFocusWhenDisabled]="true"
[attr.aria-selected]="ariaSelected"
[attr.aria-label]="ariaLabel"
[attr.aria-describedby]="_ariaDescriptionId"
role="option">
@if (_hasLeadingGraphic()) {
<span class="mdc-evolution-chip__graphic mat-mdc-chip-graphic">
<ng-content select="mat-chip-avatar, [matChipAvatar]"></ng-content>
<span class="mdc-evolution-chip__checkmark">
<svg
class="mdc-evolution-chip__checkmark-svg"
viewBox="-2 -3 30 30"
focusable="false"
aria-hidden="true">
<path class="mdc-evolution-chip__checkmark-path"
fill="none" stroke="currentColor" d="M1.73,12.91 8.1,19.28 22.79,4.59" />
</svg>
</span>
</span>
}
<span class="mdc-evolution-chip__text-label mat-mdc-chip-action-label">
<ng-content></ng-content>
<span class="mat-mdc-chip-primary-focus-indicator mat-focus-indicator"></span>
</span>
</button>
</span>
@if (_hasTrailingIcon()) {
<span class="mdc-evolution-chip__cell mdc-evolution-chip__cell--trailing">
<ng-content select="mat-chip-trailing-icon,[matChipRemove],[matChipTrailingIcon]"></ng-content>
</span>
}
<span class="cdk-visually-hidden" [id]="_ariaDescriptionId">{{ariaDescription}}</span>
| {
"end_byte": 1464,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-option.html"
} |
components/src/material/chips/README.md_0_96 | Please see the official documentation at https://material.angular.io/components/component/chips
| {
"end_byte": 96,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/README.md"
} |
components/src/material/chips/tokens.ts_0_2074 | /**
* @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 {ENTER} from '@angular/cdk/keycodes';
import {InjectionToken} from '@angular/core';
/** Default options, for the chips module, that can be overridden. */
export interface MatChipsDefaultOptions {
/** The list of key codes that will trigger a chipEnd event. */
separatorKeyCodes: readonly number[] | ReadonlySet<number>;
/** Wheter icon indicators should be hidden for single-selection. */
hideSingleSelectionIndicator?: boolean;
}
/** Injection token to be used to override the default options for the chips module. */
export const MAT_CHIPS_DEFAULT_OPTIONS = new InjectionToken<MatChipsDefaultOptions>(
'mat-chips-default-options',
{
providedIn: 'root',
factory: () => ({
separatorKeyCodes: [ENTER],
}),
},
);
/**
* Injection token that can be used to reference instances of `MatChipAvatar`. It serves as
* alternative token to the actual `MatChipAvatar` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_CHIP_AVATAR = new InjectionToken('MatChipAvatar');
/**
* Injection token that can be used to reference instances of `MatChipTrailingIcon`. It serves as
* alternative token to the actual `MatChipTrailingIcon` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_CHIP_TRAILING_ICON = new InjectionToken('MatChipTrailingIcon');
/**
* Injection token that can be used to reference instances of `MatChipRemove`. It serves as
* alternative token to the actual `MatChipRemove` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_CHIP_REMOVE = new InjectionToken('MatChipRemove');
/**
* Injection token used to avoid a circular dependency between the `MatChip` and `MatChipAction`.
*/
export const MAT_CHIP = new InjectionToken('MatChip');
| {
"end_byte": 2074,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/tokens.ts"
} |
components/src/material/chips/chip-listbox.spec.ts_0_9346 | import {Direction, Directionality} from '@angular/cdk/bidi';
import {END, HOME, LEFT_ARROW, RIGHT_ARROW, SPACE, TAB} from '@angular/cdk/keycodes';
import {
dispatchFakeEvent,
dispatchKeyboardEvent,
patchElementFocus,
} from '@angular/cdk/testing/private';
import {
Component,
DebugElement,
EventEmitter,
QueryList,
Type,
ViewChild,
ViewChildren,
} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing';
import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {By} from '@angular/platform-browser';
import {MatChipListbox, MatChipOption, MatChipsModule} from './index';
describe('MatChipListbox', () => {
let fixture: ComponentFixture<any>;
let chipListboxDebugElement: DebugElement;
let chipListboxNativeElement: HTMLElement;
let chipListboxInstance: MatChipListbox;
let testComponent: StandardChipListbox;
let chips: QueryList<MatChipOption>;
let directionality: {value: Direction; change: EventEmitter<Direction>};
let primaryActions: NodeListOf<HTMLElement>;
describe('StandardChipList', () => {
describe('basic behaviors', () => {
beforeEach(() => {
createComponent(StandardChipListbox);
});
it('should add the `mat-mdc-chip-set` class', () => {
expect(chipListboxNativeElement.classList).toContain('mat-mdc-chip-set');
});
it('should not have the aria-selected attribute when it is not selectable', fakeAsync(() => {
testComponent.selectable = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
const chipsValid = chips
.toArray()
.every(
chip =>
!chip.selectable && !chip._elementRef.nativeElement.hasAttribute('aria-selected'),
);
expect(chipsValid).toBe(true);
}));
it('should toggle the chips disabled state based on whether it is disabled', () => {
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
chipListboxInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(true);
chipListboxInstance.disabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
});
it('should disable a chip that is added after the listbox became disabled', fakeAsync(() => {
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
chipListboxInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(true);
fixture.componentInstance.chips.push(5, 6);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(true);
}));
it('should not set a role on the grid when the list is empty', () => {
testComponent.chips = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipListboxNativeElement.hasAttribute('role')).toBe(false);
});
it('should be able to set a custom role', () => {
testComponent.role = 'grid';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipListboxNativeElement.getAttribute('role')).toBe('grid');
});
it('should not set aria-required when it does not have a role', () => {
testComponent.chips = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipListboxNativeElement.hasAttribute('role')).toBe(false);
expect(chipListboxNativeElement.hasAttribute('aria-required')).toBe(false);
});
it('should toggle the chips disabled state based on whether it is disabled', fakeAsync(() => {
fixture.destroy();
TestBed.resetTestingModule();
const disabledFixture = createComponent(IndividuallyDisabledChipInsideForm);
disabledFixture.detectChanges();
flush();
expect(disabledFixture.componentInstance.chip.disabled).toBe(true);
}));
});
describe('with selected chips', () => {
beforeEach(() => {
fixture = createComponent(SelectedChipListbox);
});
it('should not override chips selected', () => {
const instanceChips = fixture.componentInstance.chips.toArray();
expect(instanceChips[0].selected)
.withContext('Expected first option to be selected.')
.toBe(true);
expect(instanceChips[1].selected)
.withContext('Expected second option to be not selected.')
.toBe(false);
expect(instanceChips[2].selected)
.withContext('Expected third option to be selected.')
.toBe(true);
});
it('should have role listbox', () => {
expect(chipListboxNativeElement.getAttribute('role')).toBe('listbox');
});
it('should not have role when empty', () => {
fixture.componentInstance.foods = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipListboxNativeElement.getAttribute('role'))
.withContext('Expect no role attribute')
.toBeNull();
});
});
describe('focus behaviors', () => {
beforeEach(() => {
createComponent(StandardChipListbox);
});
it('should focus the first chip on focus', () => {
chipListboxInstance.focus();
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[0]);
});
it('should focus the primary action when calling the `focus` method', () => {
chips.last.focus();
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[primaryActions.length - 1]);
});
it('should not be able to become focused when disabled', () => {
expect(chipListboxInstance.focused)
.withContext('Expected listbox to not be focused.')
.toBe(false);
chipListboxInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
chipListboxInstance.focus();
fixture.detectChanges();
expect(chipListboxInstance.focused)
.withContext('Expected listbox to continue not to be focused')
.toBe(false);
});
it('should remove the tabindex from the listbox if it is disabled', () => {
expect(chipListboxNativeElement.getAttribute('tabindex')).toBe('0');
chipListboxInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipListboxNativeElement.getAttribute('tabindex')).toBe('-1');
});
describe('on chip destroy', () => {
it('should focus the next item', () => {
const midItem = chips.get(2)!;
// Focus the middle item
patchElementFocus(midItem.primaryAction!._elementRef.nativeElement);
midItem.focus();
// Destroy the middle item
testComponent.chips.splice(2, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// It focuses the 4th item
expect(document.activeElement).toBe(primaryActions[3]);
});
it('should focus the previous item', () => {
// Focus the last item
patchElementFocus(chips.last.primaryAction!._elementRef.nativeElement);
chips.last.focus();
// Destroy the last item
testComponent.chips.pop();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// It focuses the next-to-last item
expect(document.activeElement).toBe(primaryActions[primaryActions.length - 2]);
});
it('should not focus if chip listbox is not focused', fakeAsync(() => {
const midItem = chips.get(2)!;
// Focus and blur the middle item
midItem.focus();
(document.activeElement as HTMLElement).blur();
tick();
// Destroy the middle item
testComponent.chips.splice(2, 1);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
// Should not have focus
expect(chipListboxNativeElement.contains(document.activeElement)).toBe(false);
}));
it('should focus the listbox if the last focused item is removed', fakeAsync(() => {
testComponent.chips = [0];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
spyOn(chipListboxInstance, 'focus');
patchElementFocus(chips.last.primaryAction!._elementRef.nativeElement);
chips.last.focus();
testComponent.chips.pop();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipListboxInstance.focus).toHaveBeenCalled();
}));
});
}); | {
"end_byte": 9346,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-listbox.spec.ts"
} |
components/src/material/chips/chip-listbox.spec.ts_9352_15031 | describe('keyboard behavior', () => {
describe('LTR (default)', () => {
beforeEach(() => {
createComponent(StandardChipListbox);
});
it('should focus previous item when press LEFT ARROW', () => {
const lastIndex = primaryActions.length - 1;
// Focus the last item in the array
chips.last.focus();
expect(document.activeElement).toBe(primaryActions[lastIndex]);
// Press the LEFT arrow
dispatchKeyboardEvent(primaryActions[lastIndex], 'keydown', LEFT_ARROW);
fixture.detectChanges();
// It focuses the next-to-last item
expect(document.activeElement).toBe(primaryActions[lastIndex - 1]);
});
it('should focus next item when press RIGHT ARROW', () => {
// Focus the last item in the array
chips.first.focus();
expect(document.activeElement).toBe(primaryActions[0]);
// Press the RIGHT arrow
dispatchKeyboardEvent(primaryActions[0], 'keydown', RIGHT_ARROW);
fixture.detectChanges();
// It focuses the next-to-last item
expect(document.activeElement).toBe(primaryActions[1]);
});
it('should not handle arrow key events from non-chip elements', () => {
const previousActiveElement = document.activeElement;
dispatchKeyboardEvent(chipListboxNativeElement, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement)
.withContext('Expected focused item not to have changed.')
.toBe(previousActiveElement);
});
it('should focus the first item when pressing HOME', () => {
const lastAction = primaryActions[primaryActions.length - 1];
chips.last.focus();
expect(document.activeElement).toBe(lastAction);
const event = dispatchKeyboardEvent(lastAction, 'keydown', HOME);
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[0]);
expect(event.defaultPrevented).toBe(true);
});
it('should focus the last item when pressing END', () => {
chips.first.focus();
expect(document.activeElement).toBe(primaryActions[0]);
const event = dispatchKeyboardEvent(primaryActions[0], 'keydown', END);
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[primaryActions.length - 1]);
expect(event.defaultPrevented).toBe(true);
});
});
describe('RTL', () => {
beforeEach(() => {
createComponent(StandardChipListbox, 'rtl');
});
it('should focus previous item when press RIGHT ARROW', () => {
const lastIndex = primaryActions.length - 1;
// Focus the last item in the array
chips.last.focus();
expect(document.activeElement).toBe(primaryActions[lastIndex]);
// Press the RIGHT arrow
dispatchKeyboardEvent(primaryActions[lastIndex], 'keydown', RIGHT_ARROW);
fixture.detectChanges();
// It focuses the next-to-last item
expect(document.activeElement).toBe(primaryActions[lastIndex - 1]);
});
it('should focus next item when press LEFT ARROW', () => {
// Focus the last item in the array
chips.first.focus();
expect(document.activeElement).toBe(primaryActions[0]);
// Press the LEFT arrow
dispatchKeyboardEvent(primaryActions[0], 'keydown', LEFT_ARROW);
fixture.detectChanges();
// It focuses the next-to-last item
expect(document.activeElement).toBe(primaryActions[1]);
});
it('should allow focus to escape when tabbing away', fakeAsync(() => {
dispatchKeyboardEvent(chipListboxNativeElement, 'keydown', TAB);
expect(chipListboxNativeElement.tabIndex)
.withContext('Expected tabIndex to be set to -1 temporarily.')
.toBe(-1);
flush();
expect(chipListboxNativeElement.tabIndex)
.withContext('Expected tabIndex to be reset back to 0')
.toBe(0);
}));
it('should use user defined tabIndex', fakeAsync(() => {
chipListboxInstance.tabIndex = 4;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipListboxNativeElement.tabIndex)
.withContext('Expected tabIndex to be set to user defined value 4.')
.toBe(4);
dispatchKeyboardEvent(chipListboxNativeElement, 'keydown', TAB);
expect(chipListboxNativeElement.tabIndex)
.withContext('Expected tabIndex to be set to -1 temporarily.')
.toBe(-1);
flush();
expect(chipListboxNativeElement.tabIndex)
.withContext('Expected tabIndex to be reset back to 4')
.toBe(4);
}));
});
it('should account for the direction changing', () => {
createComponent(StandardChipListbox);
chips.first.focus();
expect(document.activeElement).toBe(primaryActions[0]);
dispatchKeyboardEvent(primaryActions[0], 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[1]);
directionality.value = 'rtl';
directionality.change.next('rtl');
fixture.detectChanges();
dispatchKeyboardEvent(primaryActions[1], 'keydown', RIGHT_ARROW);
fixture.detectChanges();
expect(document.activeElement).toBe(primaryActions[0]);
});
}); | {
"end_byte": 15031,
"start_byte": 9352,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-listbox.spec.ts"
} |
components/src/material/chips/chip-listbox.spec.ts_15037_21496 | describe('selection logic', () => {
it('should remove selection if chip has been removed', fakeAsync(() => {
fixture = createComponent(BasicChipListbox);
const instanceChips = fixture.componentInstance.chips;
const chipListbox = fixture.componentInstance.chipListbox;
dispatchKeyboardEvent(primaryActions[0], 'keydown', SPACE);
fixture.detectChanges();
expect(instanceChips.first.selected)
.withContext('Expected first option to be selected.')
.toBe(true);
expect(chipListbox.selected)
.withContext('Expected first option to be selected.')
.toBe(chips.first);
fixture.componentInstance.foods = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(chipListbox.selected)
.withContext('Expected selection to be removed when option no longer exists.')
.toBe(undefined);
}));
it('should select an option that was added after initialization', () => {
fixture = createComponent(BasicChipListbox);
fixture.componentInstance.foods.push({viewValue: 'Potatoes', value: 'potatoes-8'});
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
primaryActions = chipListboxNativeElement.querySelectorAll<HTMLElement>(
'.mdc-evolution-chip__action--primary',
);
dispatchKeyboardEvent(primaryActions[8], 'keydown', SPACE);
fixture.detectChanges();
expect(fixture.componentInstance.chipListbox.value)
.withContext('Expect value contain the value of the last option')
.toContain('potatoes-8');
expect(fixture.componentInstance.chips.last.selected)
.withContext('Expect last option selected')
.toBeTruthy();
});
it('should not select disabled chips', () => {
fixture = createComponent(BasicChipListbox);
const array = chips.toArray();
dispatchKeyboardEvent(primaryActions[2], 'keydown', SPACE);
fixture.detectChanges();
expect(fixture.componentInstance.chipListbox.value)
.withContext('Expect value to be undefined')
.toBeUndefined();
expect(array[2].selected).withContext('Expect disabled chip not selected').toBeFalsy();
expect(fixture.componentInstance.chipListbox.selected)
.withContext('Expect no selected chips')
.toBeUndefined();
});
it('should not select when is not selectable', fakeAsync(() => {
const falsyFixture = createComponent(FalsyBasicChipListbox);
falsyFixture.detectChanges();
tick();
falsyFixture.detectChanges();
const chipListboxElement = falsyFixture.debugElement.query(By.directive(MatChipListbox))!;
const _chips = chipListboxElement.componentInstance._chips;
const nativeChips = (
chipListboxElement.nativeElement as HTMLElement
).querySelectorAll<HTMLElement>('.mdc-evolution-chip__action--primary');
expect(_chips.first.selected)
.withContext('Expected first option not to be selected')
.toBe(false);
dispatchKeyboardEvent(nativeChips[0], 'keydown', SPACE);
falsyFixture.detectChanges();
flush();
expect(_chips.first.selected)
.withContext('Expected first option not to be selected.')
.toBe(false);
}));
it('should set `aria-selected` based on the selection state in single selection mode', fakeAsync(() => {
const getAriaSelected = () =>
Array.from(primaryActions).map(action => action.getAttribute('aria-selected'));
fixture = createComponent(BasicChipListbox);
// Use a shorter list so we can keep the assertions smaller
fixture.componentInstance.foods = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
];
fixture.componentInstance.selectable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
primaryActions = chipListboxNativeElement.querySelectorAll<HTMLElement>(
'.mdc-evolution-chip__action--primary',
);
expect(getAriaSelected()).toEqual(['false', 'false', 'false']);
primaryActions[1].click();
fixture.detectChanges();
flush();
expect(getAriaSelected()).toEqual(['false', 'true', 'false']);
primaryActions[2].click();
fixture.detectChanges();
flush();
expect(getAriaSelected()).toEqual(['false', 'false', 'true']);
primaryActions[0].click();
fixture.detectChanges();
flush();
expect(getAriaSelected()).toEqual(['true', 'false', 'false']);
}));
it('should set `aria-selected` based on the selection state in multi-selection mode', fakeAsync(() => {
const getAriaSelected = () =>
Array.from(primaryActions).map(action => action.getAttribute('aria-selected'));
fixture = createComponent(MultiSelectionChipListbox);
fixture.detectChanges();
// Use a shorter list so we can keep the assertions smaller
fixture.componentInstance.foods = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
];
fixture.componentInstance.selectable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
primaryActions = chipListboxNativeElement.querySelectorAll<HTMLElement>(
'.mdc-evolution-chip__action--primary',
);
expect(getAriaSelected()).toEqual(['false', 'false', 'false']);
primaryActions[1].click();
fixture.detectChanges();
flush();
expect(getAriaSelected()).toEqual(['false', 'true', 'false']);
primaryActions[2].click();
fixture.detectChanges();
flush();
expect(getAriaSelected()).toEqual(['false', 'true', 'true']);
primaryActions[0].click();
fixture.detectChanges();
flush();
expect(getAriaSelected()).toEqual(['true', 'true', 'true']);
primaryActions[1].click();
fixture.detectChanges();
flush();
expect(getAriaSelected()).toEqual(['true', 'false', 'true']);
}));
}); | {
"end_byte": 21496,
"start_byte": 15037,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-listbox.spec.ts"
} |
components/src/material/chips/chip-listbox.spec.ts_21502_31553 | describe('chip list with chip input', () => {
describe('single selection', () => {
beforeEach(() => {
fixture = createComponent(BasicChipListbox);
});
it('should take an initial view value with reactive forms', fakeAsync(() => {
fixture.componentInstance.control = new FormControl('pizza-1');
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
const array = chips.toArray();
expect(array[1].selected).withContext('Expect pizza-1 chip to be selected').toBeTruthy();
dispatchKeyboardEvent(primaryActions[1], 'keydown', SPACE);
fixture.detectChanges();
flush();
expect(array[1].selected)
.withContext('Expect chip to be not selected after toggle selected')
.toBeFalsy();
}));
it('should set the view value from the form', () => {
const chipListbox = fixture.componentInstance.chipListbox;
const array = chips.toArray();
expect(chipListbox.value)
.withContext('Expect chip listbox to have no initial value')
.toBeFalsy();
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
expect(array[1].selected).withContext('Expect chip to be selected').toBeTruthy();
});
it('should update the form value when the view changes', fakeAsync(() => {
expect(fixture.componentInstance.control.value)
.withContext(`Expected the control's value to be empty initially.`)
.toEqual(null);
dispatchKeyboardEvent(primaryActions[0], 'keydown', SPACE);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.value)
.withContext(`Expected control's value to be set to the new option.`)
.toEqual('steak-0');
}));
it('should clear the selection when a nonexistent option value is selected', () => {
const array = chips.toArray();
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
expect(array[1].selected)
.withContext(`Expected chip with the value to be selected.`)
.toBeTruthy();
fixture.componentInstance.control.setValue('gibberish');
fixture.detectChanges();
expect(array[1].selected)
.withContext(`Expected chip with the old value not to be selected.`)
.toBeFalsy();
});
it('should clear the selection when the control is reset', () => {
const array = chips.toArray();
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
fixture.componentInstance.control.reset();
fixture.detectChanges();
expect(array[1].selected)
.withContext(`Expected chip with the old value not to be selected.`)
.toBeFalsy();
});
it('should set the control to touched when the chip listbox is touched', fakeAsync(() => {
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to start off as untouched.')
.toBe(false);
const nativeChipListbox = fixture.debugElement.query(
By.css('mat-chip-listbox'),
)!.nativeElement;
dispatchFakeEvent(nativeChipListbox, 'blur');
tick();
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to be touched.')
.toBe(true);
}));
it('should not set touched when a disabled chip listbox is touched', fakeAsync(() => {
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to start off as untouched.')
.toBe(false);
fixture.componentInstance.control.disable();
const nativeChipListbox = fixture.debugElement.query(
By.css('mat-chip-listbox'),
)!.nativeElement;
dispatchFakeEvent(nativeChipListbox, 'blur');
tick();
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to stay untouched.')
.toBe(false);
}));
it("should set the control to dirty when the chip listbox's value changes in the DOM", () => {
expect(fixture.componentInstance.control.dirty)
.withContext(`Expected control to start out pristine.`)
.toEqual(false);
dispatchKeyboardEvent(primaryActions[1], 'keydown', SPACE);
fixture.detectChanges();
expect(fixture.componentInstance.control.dirty)
.withContext(`Expected control to be dirty after value was changed by user.`)
.toEqual(true);
});
it('should not set the control to dirty when the value changes programmatically', () => {
expect(fixture.componentInstance.control.dirty)
.withContext(`Expected control to start out pristine.`)
.toEqual(false);
fixture.componentInstance.control.setValue('pizza-1');
expect(fixture.componentInstance.control.dirty)
.withContext(`Expected control to stay pristine after programmatic change.`)
.toEqual(false);
});
it('should be able to programmatically select a falsy option', () => {
fixture.destroy();
TestBed.resetTestingModule();
const falsyFixture = createComponent(FalsyValueChipListbox);
falsyFixture.componentInstance.control.setValue([0]);
falsyFixture.detectChanges();
falsyFixture.detectChanges();
expect(falsyFixture.componentInstance.chips.first.selected)
.withContext('Expected first option to be selected')
.toBe(true);
});
it('should not focus the active chip when the value is set programmatically', () => {
const chipArray = fixture.componentInstance.chips.toArray();
spyOn(chipArray[4], 'focus').and.callThrough();
fixture.componentInstance.control.setValue('chips-4');
fixture.detectChanges();
expect(chipArray[4].focus).not.toHaveBeenCalled();
});
});
describe('multiple selection', () => {
it('should take an initial view value with reactive forms', fakeAsync(() => {
fixture = createComponent(MultiSelectionChipListbox, undefined, initFixture => {
initFixture.componentInstance.control = new FormControl(['pizza-1', 'pasta-6']);
initFixture.componentInstance.selectable = true;
});
fixture.detectChanges();
flush();
const array = fixture.componentInstance.chips.toArray();
expect(array[1].selected).withContext('Expect pizza-1 chip to be selected').toBe(true);
expect(array[6].selected).withContext('Expect pasta-6 chip to be selected').toBe(true);
dispatchKeyboardEvent(primaryActions[1], 'keydown', SPACE);
fixture.detectChanges();
flush();
expect(array[1].selected)
.withContext('Expect pizza-1 chip to no longer be selected')
.toBe(false);
expect(array[6].selected)
.withContext('Expect pasta-6 chip to remain selected')
.toBe(true);
}));
it('should set the view value from the form', () => {
fixture = createComponent(MultiSelectionChipListbox);
const chipListbox = fixture.componentInstance.chipListbox;
const array = fixture.componentInstance.chips.toArray();
expect(chipListbox.value)
.withContext('Expect chip listbox to have no initial value')
.toBeFalsy();
fixture.componentInstance.control.setValue(['pizza-1']);
fixture.detectChanges();
expect(array[1].selected).withContext('Expect chip to be selected').toBeTruthy();
});
it('should update the form value when the view changes', () => {
fixture = createComponent(MultiSelectionChipListbox);
expect(fixture.componentInstance.control.value)
.withContext(`Expected the control's value to be empty initially.`)
.toEqual(null);
dispatchKeyboardEvent(primaryActions[0], 'keydown', SPACE);
fixture.detectChanges();
expect(fixture.componentInstance.control.value)
.withContext(`Expected control's value to be set to the new option.`)
.toEqual(['steak-0']);
});
it('should clear the selection when a nonexistent option value is selected', () => {
fixture = createComponent(MultiSelectionChipListbox);
chips = fixture.componentInstance.chips;
const array = fixture.componentInstance.chips.toArray();
fixture.componentInstance.control.setValue(['pizza-1']);
fixture.detectChanges();
expect(array[1].selected)
.withContext(`Expected chip with the value to be selected.`)
.toBeTruthy();
fixture.componentInstance.control.setValue(['gibberish']);
fixture.detectChanges();
expect(array[1].selected)
.withContext(`Expected chip with the old value not to be selected.`)
.toBeFalsy();
});
it('should clear the selection when the control is reset', () => {
fixture = createComponent(MultiSelectionChipListbox);
const array = fixture.componentInstance.chips.toArray();
fixture.componentInstance.control.setValue(['pizza-1']);
fixture.detectChanges();
fixture.componentInstance.control.reset();
fixture.detectChanges();
expect(array[1].selected)
.withContext(`Expected chip with the old value not to be selected.`)
.toBeFalsy();
});
});
});
}); | {
"end_byte": 31553,
"start_byte": 21502,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-listbox.spec.ts"
} |
components/src/material/chips/chip-listbox.spec.ts_31557_37985 | function createComponent<T>(
component: Type<T>,
direction: Direction = 'ltr',
beforeInitialChangeDetection?: (fixture: ComponentFixture<T>) => void,
): ComponentFixture<T> {
directionality = {
value: direction,
change: new EventEmitter(),
};
TestBed.configureTestingModule({
imports: [FormsModule, ReactiveFormsModule, MatChipsModule],
providers: [{provide: Directionality, useValue: directionality}],
declarations: [component],
});
fixture = TestBed.createComponent<T>(component);
beforeInitialChangeDetection?.(fixture);
fixture.detectChanges();
chipListboxDebugElement = fixture.debugElement.query(By.directive(MatChipListbox))!;
chipListboxNativeElement = chipListboxDebugElement.nativeElement;
chipListboxInstance = chipListboxDebugElement.componentInstance;
testComponent = fixture.debugElement.componentInstance;
chips = chipListboxInstance._chips;
primaryActions = chipListboxNativeElement.querySelectorAll<HTMLElement>(
'.mdc-evolution-chip__action--primary',
);
return fixture;
}
});
@Component({
template: `
<mat-chip-listbox [tabIndex]="tabIndex" [selectable]="selectable" [role]="role">
@for (i of chips; track i) {
<mat-chip-option (select)="chipSelect(i)" (deselect)="chipDeselect(i)">
{{name}} {{i + 1}}
</mat-chip-option>
}
</mat-chip-listbox>`,
standalone: false,
})
class StandardChipListbox {
name: string = 'Test';
selectable: boolean = true;
chipSelect: (index?: number) => void = () => {};
chipDeselect: (index?: number) => void = () => {};
tabIndex: number = 0;
chips = [0, 1, 2, 3, 4];
role: string | null = null;
}
@Component({
template: `
<mat-chip-listbox [formControl]="control" [required]="isRequired"
[tabIndex]="tabIndexOverride" [selectable]="selectable">
@for (food of foods; track food) {
<mat-chip-option [value]="food.value" [disabled]="food.disabled">
{{ food.viewValue }}
</mat-chip-option>
}
</mat-chip-listbox>
`,
standalone: false,
})
class BasicChipListbox {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos', disabled: true},
{value: 'sandwich-3', viewValue: 'Sandwich'},
{value: 'chips-4', viewValue: 'Chips'},
{value: 'eggs-5', viewValue: 'Eggs'},
{value: 'pasta-6', viewValue: 'Pasta'},
{value: 'sushi-7', viewValue: 'Sushi'},
];
control = new FormControl<string | null>(null);
isRequired: boolean;
tabIndexOverride: number;
selectable: boolean;
@ViewChild(MatChipListbox) chipListbox: MatChipListbox;
@ViewChildren(MatChipOption) chips: QueryList<MatChipOption>;
}
@Component({
template: `
<mat-chip-listbox [multiple]="true" [formControl]="control"
[required]="isRequired"
[tabIndex]="tabIndexOverride" [selectable]="selectable">
@for (food of foods; track food) {
<mat-chip-option [value]="food.value" [disabled]="food.disabled">
{{ food.viewValue }}
</mat-chip-option>
}
</mat-chip-listbox>
`,
standalone: false,
})
class MultiSelectionChipListbox {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos', disabled: true},
{value: 'sandwich-3', viewValue: 'Sandwich'},
{value: 'chips-4', viewValue: 'Chips'},
{value: 'eggs-5', viewValue: 'Eggs'},
{value: 'pasta-6', viewValue: 'Pasta'},
{value: 'sushi-7', viewValue: 'Sushi'},
];
control = new FormControl<string[] | null>(null);
isRequired: boolean;
tabIndexOverride: number;
selectable: boolean;
@ViewChild(MatChipListbox) chipListbox: MatChipListbox;
@ViewChildren(MatChipOption) chips: QueryList<MatChipOption>;
}
@Component({
template: `
<mat-chip-listbox [formControl]="control">
@for (food of foods; track food) {
<mat-chip-option [value]="food.value">{{ food.viewValue }}</mat-chip-option>
}
</mat-chip-listbox>
`,
standalone: false,
})
class FalsyValueChipListbox {
foods: any[] = [
{value: 0, viewValue: 'Steak'},
{value: 1, viewValue: 'Pizza'},
];
control = new FormControl([] as number[]);
@ViewChildren(MatChipOption) chips: QueryList<MatChipOption>;
}
@Component({
template: `
<mat-chip-listbox>
@for (food of foods; track food) {
<mat-chip-option [value]="food.value" [selected]="food.selected">
{{ food.viewValue }}
</mat-chip-option>
}
</mat-chip-listbox>
`,
standalone: false,
})
class SelectedChipListbox {
foods: any[] = [
{value: 0, viewValue: 'Steak', selected: true},
{value: 1, viewValue: 'Pizza', selected: false},
{value: 2, viewValue: 'Pasta', selected: true},
];
@ViewChildren(MatChipOption) chips: QueryList<MatChipOption>;
}
@Component({
template: `
<mat-chip-listbox [formControl]="control" [required]="isRequired"
[tabIndex]="tabIndexOverride" [selectable]="selectable">
@for (food of foods; track food) {
<mat-chip-option [value]="food.value" [disabled]="food.disabled">
{{ food.viewValue }}
</mat-chip-option>
}
</mat-chip-listbox>
`,
standalone: false,
})
class FalsyBasicChipListbox {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos', disabled: true},
{value: 'sandwich-3', viewValue: 'Sandwich'},
{value: 'chips-4', viewValue: 'Chips'},
{value: 'eggs-5', viewValue: 'Eggs'},
{value: 'pasta-6', viewValue: 'Pasta'},
{value: 'sushi-7', viewValue: 'Sushi'},
];
control = new FormControl<string | null>(null);
isRequired: boolean;
tabIndexOverride: number;
selectable: boolean = false;
@ViewChild(MatChipListbox) chipListbox: MatChipListbox;
@ViewChildren(MatChipOption) chips: QueryList<MatChipOption>;
}
// Based on #29783.
@Component({
template: `
<form>
<mat-chip-listbox name="test" [ngModel]="null">
<mat-chip-option value="1" disabled>Hello</mat-chip-option>
</mat-chip-listbox>
</form>
`,
standalone: false,
})
class IndividuallyDisabledChipInsideForm {
@ViewChild(MatChipOption) chip: MatChipOption;
} | {
"end_byte": 37985,
"start_byte": 31557,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-listbox.spec.ts"
} |
components/src/material/chips/chip.scss_0_6718 | @use '@angular/cdk';
@use '../core/style/layout-common';
@use '../core/focus-indicators/private' as focus-indicators-private;
@use '../core/tokens/m2/mdc/chip' as tokens-mdc-chip;
@use '../core/tokens/m2/mat/chip' as tokens-mat-chip;
@use '../core/style/vendor-prefixes';
@use '../core/tokens/token-utils';
$_checkmark-size: 20px;
$_trailing-icon-size: 18px;
$_action-padding: 12px;
$_graphic-padding: 6px;
$_trailing-action-padding: 8px;
$_avatar-leading-padding: 4px;
$_avatar-trailing-padding: 8px;
.mdc-evolution-chip,
.mdc-evolution-chip__cell,
.mdc-evolution-chip__action {
display: inline-flex;
align-items: center;
}
.mdc-evolution-chip {
position: relative;
max-width: 100%;
}
.mdc-evolution-chip__cell,
.mdc-evolution-chip__action {
height: 100%;
}
.mdc-evolution-chip__cell--primary {
// Ensures that the trailing icon is pushed to the end if the chip has a set width.
flex-basis: 100%;
overflow-x: hidden;
}
.mdc-evolution-chip__cell--trailing {
flex: 1 0 auto;
}
.mdc-evolution-chip__action {
align-items: center;
background: none;
border: none;
box-sizing: content-box;
cursor: pointer;
display: inline-flex;
justify-content: center;
outline: none;
padding: 0;
text-decoration: none;
color: inherit;
}
.mdc-evolution-chip__action--presentational {
cursor: auto;
}
.mdc-evolution-chip--disabled,
.mdc-evolution-chip__action:disabled {
pointer-events: none;
}
.mdc-evolution-chip__action--primary {
// This element can be placed on a `button` node which usually has some user agent styles.
// Reset the font so that the typography from the root element can propagate down.
font: inherit;
letter-spacing: inherit;
white-space: inherit;
overflow-x: hidden;
@include token-utils.use-tokens(tokens-mdc-chip.$prefix, tokens-mdc-chip.get-token-slots()) {
.mat-mdc-standard-chip &::before {
@include token-utils.create-token-slot(border-width, outline-width);
@include token-utils.create-token-slot(border-radius, container-shape-radius);
box-sizing: border-box;
content: '';
height: 100%;
left: 0;
position: absolute;
pointer-events: none;
top: 0;
width: 100%;
z-index: 1;
border-style: solid;
}
.mat-mdc-standard-chip & {
padding-left: $_action-padding;
padding-right: $_action-padding;
}
.mat-mdc-standard-chip.mdc-evolution-chip--with-primary-graphic & {
padding-left: 0;
padding-right: $_action-padding;
}
[dir='rtl'] .mat-mdc-standard-chip.mdc-evolution-chip--with-primary-graphic & {
padding-left: $_action-padding;
padding-right: 0;
}
.mat-mdc-standard-chip:not(.mdc-evolution-chip--disabled) &::before {
@include token-utils.create-token-slot(border-color, outline-color);
}
&:not(.mdc-evolution-chip__action--presentational):not(.mdc-ripple-upgraded):focus::before {
@include token-utils.create-token-slot(border-color, focus-outline-color);
}
.mat-mdc-standard-chip.mdc-evolution-chip--disabled &::before {
@include token-utils.create-token-slot(border-color, disabled-outline-color);
}
.mat-mdc-standard-chip.mdc-evolution-chip--selected &::before {
@include token-utils.create-token-slot(border-width, flat-selected-outline-width);
}
}
// Keeps basic listbox chips looking consistent with the other variations. Listbox chips don't
// inherit the font size, because they wrap the label in a `button` that has user agent styles.
.mat-mdc-basic-chip & {
font: inherit;
}
// Moved out into variables, because the selectors are too long.
$with-graphic: '.mdc-evolution-chip--with-primary-graphic';
$with-trailing: '.mdc-evolution-chip--with-trailing-action';
.mat-mdc-standard-chip#{$with-trailing} & {
padding-left: $_action-padding;
padding-right: 0;
}
[dir='rtl'] .mat-mdc-standard-chip#{$with-trailing} & {
padding-left: 0;
padding-right: $_action-padding;
}
.mat-mdc-standard-chip#{$with-graphic}#{$with-trailing} & {
padding-left: 0;
padding-right: 0;
}
[dir='rtl'] .mat-mdc-standard-chip#{$with-graphic}#{$with-trailing} & {
padding-left: 0;
padding-right: 0;
}
.mdc-evolution-chip--with-avatar#{$with-graphic} & {
padding-left: 0;
padding-right: $_action-padding;
}
[dir='rtl'] .mdc-evolution-chip--with-avatar#{$with-graphic} & {
padding-left: $_action-padding;
padding-right: 0;
}
.mdc-evolution-chip--with-avatar#{$with-graphic}#{$with-trailing} & {
padding-left: 0;
padding-right: 0;
}
[dir='rtl'] .mdc-evolution-chip--with-avatar#{$with-graphic}#{$with-trailing} & {
padding-left: 0;
padding-right: 0;
}
}
.mdc-evolution-chip__action--trailing {
position: relative;
overflow: visible;
@include token-utils.use-tokens(tokens-mdc-chip.$prefix, tokens-mdc-chip.get-token-slots()) {
.mat-mdc-standard-chip:not(.mdc-evolution-chip--disabled) & {
@include token-utils.create-token-slot(color, with-trailing-icon-trailing-icon-color);
}
.mat-mdc-standard-chip.mdc-evolution-chip--disabled & {
@include token-utils.create-token-slot(color,
with-trailing-icon-disabled-trailing-icon-color);
}
}
// Moved out into variables, because the selectors are too long.
$with-graphic: '.mdc-evolution-chip--with-primary-graphic';
$with-trailing: '.mdc-evolution-chip--with-trailing-action';
.mat-mdc-standard-chip#{$with-trailing} & {
padding-left: $_trailing-action-padding;
padding-right: $_trailing-action-padding;
}
.mat-mdc-standard-chip#{$with-graphic}#{$with-trailing} & {
padding-left: $_trailing-action-padding;
padding-right: $_trailing-action-padding;
}
.mdc-evolution-chip--with-avatar#{$with-graphic}#{$with-trailing} & {
padding-left: $_avatar-trailing-padding;
padding-right: $_avatar-trailing-padding;
}
[dir='rtl'] .mdc-evolution-chip--with-avatar#{$with-graphic}#{$with-trailing} & {
padding-left: $_avatar-trailing-padding;
padding-right: $_avatar-trailing-padding;
}
}
.mdc-evolution-chip__text-label {
@include vendor-prefixes.user-select(none);
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
@include token-utils.use-tokens(tokens-mdc-chip.$prefix, tokens-mdc-chip.get-token-slots()) {
.mat-mdc-standard-chip & {
@include token-utils.create-token-slot(font-family, label-text-font);
@include token-utils.create-token-slot(line-height, label-text-line-height);
@include token-utils.create-token-slot(font-size, label-text-size);
@include token-utils.create-token-slot(font-weight, label-text-weight);
@include token-utils | {
"end_byte": 6718,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip.scss"
} |
components/src/material/chips/chip.scss_6718_14167 | .create-token-slot(letter-spacing, label-text-tracking);
}
.mat-mdc-standard-chip:not(.mdc-evolution-chip--disabled) & {
@include token-utils.create-token-slot(color, label-text-color);
}
.mat-mdc-standard-chip.mdc-evolution-chip--selected:not(.mdc-evolution-chip--disabled) & {
@include token-utils.create-token-slot(color, selected-label-text-color);
}
.mat-mdc-standard-chip.mdc-evolution-chip--disabled &,
.mat-mdc-standard-chip.mdc-evolution-chip--selected.mdc-evolution-chip--disabled & {
@include token-utils.create-token-slot(color, disabled-label-text-color);
}
}
}
.mdc-evolution-chip__graphic {
align-items: center;
display: inline-flex;
justify-content: center;
overflow: hidden;
pointer-events: none;
position: relative;
flex: 1 0 auto;
@include token-utils.use-tokens(tokens-mdc-chip.$prefix, tokens-mdc-chip.get-token-slots()) {
.mat-mdc-standard-chip & {
@include token-utils.create-token-slot(width, with-avatar-avatar-size);
@include token-utils.create-token-slot(height, with-avatar-avatar-size);
@include token-utils.create-token-slot(font-size, with-avatar-avatar-size);
}
}
.mdc-evolution-chip--selecting & {
transition: width 150ms 0ms cubic-bezier(0.4, 0, 0.2, 1);
}
// Moved out into variables, because the selectors are too long.
$with-icon: '.mdc-evolution-chip--with-primary-icon';
$with-graphic: '.mdc-evolution-chip--with-primary-graphic';
$with-trailing: '.mdc-evolution-chip--with-trailing-action';
.mdc-evolution-chip--selectable:not(.mdc-evolution-chip--selected):not(#{$with-icon}) & {
width: 0;
}
.mat-mdc-standard-chip#{$with-graphic} & {
padding-left: $_graphic-padding;
padding-right: $_graphic-padding;
}
.mdc-evolution-chip--with-avatar#{$with-graphic} & {
padding-left: $_avatar-leading-padding;
padding-right: $_avatar-trailing-padding;
}
[dir='rtl'] .mdc-evolution-chip--with-avatar#{$with-graphic} & {
padding-left: $_avatar-trailing-padding;
padding-right: $_avatar-leading-padding;
}
.mat-mdc-standard-chip#{$with-graphic}#{$with-trailing} & {
padding-left: $_graphic-padding;
padding-right: $_graphic-padding;
}
.mdc-evolution-chip--with-avatar#{$with-graphic}#{$with-trailing} & {
padding-left: $_avatar-leading-padding;
padding-right: $_avatar-trailing-padding;
}
[dir='rtl'] .mdc-evolution-chip--with-avatar#{$with-graphic}#{$with-trailing} & {
padding-left: $_avatar-trailing-padding;
padding-right: $_avatar-leading-padding;
}
}
.mdc-evolution-chip__checkmark {
position: absolute;
opacity: 0;
top: 50%;
left: 50%;
height: $_checkmark-size;
width: $_checkmark-size;
@include token-utils.use-tokens(tokens-mdc-chip.$prefix, tokens-mdc-chip.get-token-slots()) {
.mat-mdc-standard-chip:not(.mdc-evolution-chip--disabled) & {
@include token-utils.create-token-slot(color, with-icon-selected-icon-color);
}
.mat-mdc-standard-chip.mdc-evolution-chip--disabled & {
@include token-utils.create-token-slot(color, with-icon-disabled-icon-color);
}
}
.mdc-evolution-chip--selecting & {
transition: transform 150ms 0ms cubic-bezier(0.4, 0, 0.2, 1);
transform: translate(-75%, -50%);
}
.mdc-evolution-chip--selected & {
transform: translate(-50%, -50%);
opacity: 1;
}
}
.mdc-evolution-chip__checkmark-svg {
display: block;
}
.mdc-evolution-chip__checkmark-path {
stroke-width: 2px;
stroke-dasharray: 29.7833385;
stroke-dashoffset: 29.7833385;
stroke: currentColor;
.mdc-evolution-chip--selecting & {
transition: stroke-dashoffset 150ms 45ms cubic-bezier(0.4, 0, 0.2, 1);
}
.mdc-evolution-chip--selected & {
stroke-dashoffset: 0;
}
@include cdk.high-contrast {
// SVG colors won't be changed in high contrast mode and since the checkmark is white
// by default, it'll blend in with the background in black-on-white mode. Override the
// color to ensure that it's visible. We need !important, because the theme styles are
// very specific.
stroke: CanvasText !important;
}
}
.mdc-evolution-chip__icon--trailing {
.mat-mdc-standard-chip & {
height: $_trailing-icon-size;
width: $_trailing-icon-size;
font-size: $_trailing-icon-size;
}
$disabled-icon-opacity: null;
@include token-utils.use-tokens(tokens-mdc-chip.$prefix, tokens-mdc-chip.get-token-slots()) {
$disabled-icon-opacity:
token-utils.get-token-variable(with-trailing-icon-disabled-trailing-icon-opacity);
}
// If the trailing icon is a chip-remove button, we have to factor in the trailing action
// opacity as well as the disabled opacity.
.mdc-evolution-chip--disabled &.mat-mdc-chip-remove {
@include token-utils.use-tokens(tokens-mat-chip.$prefix, tokens-mat-chip.get-token-slots()) {
$action-opacity: token-utils.get-token-variable(trailing-action-opacity);
opacity: calc(#{$action-opacity} * #{$disabled-icon-opacity});
&:focus {
$action-focus-opacity: token-utils.get-token-variable(trailing-action-focus-opacity);
opacity: calc(#{$action-focus-opacity} * #{$disabled-icon-opacity});
}
}
}
}
.mat-mdc-standard-chip {
@include token-utils.use-tokens(tokens-mdc-chip.$prefix, tokens-mdc-chip.get-token-slots()) {
@include token-utils.create-token-slot(border-radius, container-shape-radius);
@include token-utils.create-token-slot(height, container-height);
&:not(.mdc-evolution-chip--disabled) {
@include token-utils.create-token-slot(background-color, elevated-container-color);
}
&.mdc-evolution-chip--disabled {
@include token-utils.create-token-slot(background-color, elevated-disabled-container-color);
}
&.mdc-evolution-chip--selected:not(.mdc-evolution-chip--disabled) {
@include token-utils.create-token-slot(background-color, elevated-selected-container-color);
}
&.mdc-evolution-chip--selected.mdc-evolution-chip--disabled {
@include token-utils.create-token-slot(background-color,
flat-disabled-selected-container-color);
}
}
@include cdk.high-contrast {
outline: solid 1px;
}
}
.mdc-evolution-chip__icon--primary {
@include token-utils.use-tokens(tokens-mdc-chip.$prefix, tokens-mdc-chip.get-token-slots()) {
.mat-mdc-standard-chip & {
@include token-utils.create-token-slot(border-radius, with-avatar-avatar-shape-radius);
@include token-utils.create-token-slot(width, with-icon-icon-size);
@include token-utils.create-token-slot(height, with-icon-icon-size);
@include token-utils.create-token-slot(font-size, with-icon-icon-size);
}
.mdc-evolution-chip--selected & {
opacity: 0;
}
.mat-mdc-standard-chip:not(.mdc-evolution-chip--disabled) & {
@include token-utils.create-token-slot(color, with-icon-icon-color);
}
.mat-mdc-standard-chip.mdc-evolution-chip--disabled & {
@include token-utils.create-token-slot(color, with-icon-disabled-icon-color);
}
}
}
// The highlighted attribute is used to make the chip appear as selected on-demand,
// aside from showing the selected indicator. We achieve this by re-mapping the base
// tokens to the highlighted ones. Note that we only need to do this for the tokens
// that we don't re-implement ourselves below.
// TODO(crisbeto): with some future refactors we may be able to clean this up. | {
"end_byte": 14167,
"start_byte": 6718,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip.scss"
} |
components/src/material/chips/chip.scss_14168_22188 | .mat-mdc-chip-highlighted {
@include token-utils.use-tokens(tokens-mdc-chip.$prefix, tokens-mdc-chip.get-token-slots()) {
$highlighted-remapped-tokens: (
with-icon-icon-color: with-icon-selected-icon-color,
elevated-container-color: elevated-selected-container-color,
label-text-color: selected-label-text-color,
outline-width: flat-selected-outline-width,
);
@each $selected, $base in $highlighted-remapped-tokens {
#{token-utils.get-token-variable-name($selected)}: token-utils.get-token-variable($base);
}
}
}
// Add additional slots for the MDC chip tokens, needed in Angular Material.
@include token-utils.use-tokens(tokens-mdc-chip.$prefix, tokens-mdc-chip.get-token-slots()) {
.mat-mdc-chip-focus-overlay {
@include token-utils.create-token-slot(background, focus-state-layer-color);
.mat-mdc-chip-selected &,
.mat-mdc-chip-highlighted & {
@include token-utils.create-token-slot(background, selected-focus-state-layer-color);
}
.mat-mdc-chip:hover & {
@include token-utils.create-token-slot(background, hover-state-layer-color);
@include token-utils.create-token-slot(opacity, hover-state-layer-opacity);
}
.mat-mdc-chip-selected:hover,
.mat-mdc-chip-highlighted:hover & {
@include token-utils.create-token-slot(background, selected-hover-state-layer-color);
@include token-utils.create-token-slot(opacity, selected-hover-state-layer-opacity);
}
.mat-mdc-chip.cdk-focused & {
@include token-utils.create-token-slot(background, focus-state-layer-color);
@include token-utils.create-token-slot(opacity, focus-state-layer-opacity);
}
.mat-mdc-chip-selected.cdk-focused &,
.mat-mdc-chip-highlighted.cdk-focused & {
@include token-utils.create-token-slot(background, selected-focus-state-layer-color);
@include token-utils.create-token-slot(opacity, selected-focus-state-layer-opacity);
}
}
.mdc-evolution-chip--disabled:not(.mdc-evolution-chip--selected) .mat-mdc-chip-avatar {
@include token-utils.create-token-slot(opacity, with-avatar-disabled-avatar-opacity);
}
.mdc-evolution-chip--disabled .mdc-evolution-chip__icon--trailing {
@include token-utils.create-token-slot(
opacity, with-trailing-icon-disabled-trailing-icon-opacity);
}
.mdc-evolution-chip--disabled.mdc-evolution-chip--selected .mdc-evolution-chip__checkmark {
@include token-utils.create-token-slot(opacity, with-icon-disabled-icon-opacity);
}
}
@include token-utils.use-tokens(tokens-mat-chip.$prefix, tokens-mat-chip.get-token-slots()) {
// Historically, MDC did not support disabled chips, so we needed our own disabled styles.
// Now that MDC supports disabled styles, we should switch to using theirs.
.mat-mdc-standard-chip {
&.mdc-evolution-chip--disabled {
@include token-utils.create-token-slot(opacity, disabled-container-opacity);
}
&.mdc-evolution-chip--selected,
&.mat-mdc-chip-highlighted {
.mdc-evolution-chip__icon--trailing {
@include token-utils.create-token-slot(color, selected-trailing-icon-color);
}
&.mdc-evolution-chip--disabled .mdc-evolution-chip__icon--trailing {
@include token-utils.create-token-slot(color, selected-disabled-trailing-icon-color);
}
}
}
.mat-mdc-chip-remove {
@include token-utils.create-token-slot(opacity, trailing-action-opacity);
&:focus {
@include token-utils.create-token-slot(opacity, trailing-action-focus-opacity);
}
&::after {
@include token-utils.create-token-slot(background-color, trailing-action-state-layer-color);
}
&:hover::after {
@include token-utils.create-token-slot(opacity, trailing-action-hover-state-layer-opacity);
}
&:focus::after {
@include token-utils.create-token-slot(opacity, trailing-action-focus-state-layer-opacity);
}
}
.mat-mdc-chip-selected .mat-mdc-chip-remove::after,
.mat-mdc-chip-highlighted .mat-mdc-chip-remove::after {
@include token-utils.create-token-slot(background-color,
selected-trailing-action-state-layer-color);
}
}
.mat-mdc-standard-chip {
-webkit-tap-highlight-color: transparent;
// MDC sets `overflow: hidden` on these elements in order to truncate the text. This is
// unnecessary since our chips don't truncate their text and it makes it difficult to style
// the strong focus indicators so we need to override it.
.mdc-evolution-chip__cell--primary,
.mdc-evolution-chip__action--primary,
.mat-mdc-chip-action-label {
overflow: visible;
}
// MDC sizes and positions this element using `width`, `height` and `padding`.
// This usually works, but it's common for apps to add `box-sizing: border-box`
// to all elements on the page which can cause the graphic to be clipped.
// Set an explicit `box-sizing` in order to avoid these issues.
.mat-mdc-chip-graphic,
.mat-mdc-chip-trailing-icon {
box-sizing: content-box;
}
&._mat-animation-noopable {
&,
.mdc-evolution-chip__graphic,
.mdc-evolution-chip__checkmark,
.mdc-evolution-chip__checkmark-path {
// MDC listens to `transitionend` events on some of these
// elements so we can't disable the transitions completely.
transition-duration: 1ms;
animation-duration: 1ms;
}
}
}
// MDC's focus and hover indication is handled through their ripple which we currently
// don't use due to size concerns so we have to re-implement it ourselves.
.mat-mdc-chip-focus-overlay {
@include layout-common.fill;
pointer-events: none;
opacity: 0;
border-radius: inherit;
transition: opacity 150ms linear;
._mat-animation-noopable & {
transition: none;
}
.mat-mdc-basic-chip & {
display: none;
}
}
// The ripple container should match the bounds of the entire chip.
.mat-mdc-chip .mat-ripple.mat-mdc-chip-ripple {
@include layout-common.fill;
// Disable pointer events for the ripple container and state overlay because the container
// will overlay the user content and we don't want to disable mouse events on the user content.
// Pointer events can be safely disabled because the ripple trigger element is the host element.
pointer-events: none;
// Inherit the border radius from the parent so that state overlay and ripples don't exceed the
// parent button boundaries.
border-radius: inherit;
}
.mat-mdc-chip-avatar {
// In case an icon or text is used as an avatar.
text-align: center;
line-height: 1;
// Technically the avatar is only supposed to have an image, but we also allow for icons.
// Set the color so the icons inherit the correct color.
color: var(--mdc-chip-with-icon-icon-color, currentColor);
}
// Required for the strong focus indicator to fill the chip.
.mat-mdc-chip {
position: relative;
// `.mat-mdc-chip-action-label` below sets a `z-index: 1` to put the label above the focus
// overlay, but that can also cause it to appear above other elements like sticky columns
// (see #26793). Set an explicit `z-index` to prevent the label from leaking out.
z-index: 0;
}
.mat-mdc-chip-action-label {
// MDC centers the text, but we have a lot of internal customers who have it at the start.
text-align: left;
// Give the text label a higher z-index than the focus overlay to ensure that the focus overlay
// does not affect the color of the text. Material spec requires state layer to not interfere with
// text color.
z-index: 1;
[dir='rtl'] & {
text-align: right;
}
// When a chip has a trailing action, it'll have two focusable elements when navigating with
// the arrow keys: the primary action and the trailing one. If that's the case, we apply
// `position: relative` to the primary action container so that the indicators is only around
// the text label. This allows for it to be distinguished from the indicator on the trailing icon.
.mat-mdc-chip.mdc-evolution-chip--with-trailing-action & {
position: relative;
} | {
"end_byte": 22188,
"start_byte": 14168,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip.scss"
} |
components/src/material/chips/chip.scss_22192_24468 | .mat-mdc-chip-primary-focus-indicator {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
pointer-events: none;
}
// For the chip element, default inset/offset values are necessary to ensure that
// the focus indicator is sufficiently contrastive and renders appropriately.
.mat-focus-indicator::before {
$default-border-width: focus-indicators-private.$default-border-width;
$border-width: var(--mat-focus-indicator-border-width, #{$default-border-width});
$offset: calc(#{$border-width} + 2px);
margin: calc(#{$offset} * -1);
}
}
.mat-mdc-chip-remove {
&::before {
$default-border-width: focus-indicators-private.$default-border-width;
$offset: var(--mat-focus-indicator-border-width, #{$default-border-width});
margin: calc(#{$offset} * -1);
// MDC sets a padding a on the chip button which stretches out the focus indicator.
left: 8px;
right: 8px;
}
// Used as a state overlay.
&::after {
$_touch-target-size: 48px;
$_ripple-size: 24px;
$offset: 3px;
content: '';
display: block;
opacity: 0;
position: absolute;
top: 0 - $offset;
bottom: 0 - $offset;
left: 8px - $offset;
right: 8px - $offset;
border-radius: 50%;
box-sizing: border-box;
padding: calc(($_touch-target-size - $_ripple-size)/2);
margin: calc((($_touch-target-size - $_ripple-size)/2) * -1);
// stylelint-disable material/no-prefixes
background-clip: content-box;
}
.mat-icon {
width: $_trailing-icon-size;
height: $_trailing-icon-size;
font-size: $_trailing-icon-size;
box-sizing: content-box;
}
}
.mat-chip-edit-input {
cursor: text;
display: inline-block;
color: inherit;
outline: 0;
}
// Single-selection chips show their selected state using a background color which won't be visible
// in high contrast mode. This isn't necessary in multi-selection since there's a checkmark.
.mat-mdc-chip-selected:not(.mat-mdc-chip-multiple) {
@include cdk.high-contrast {
outline-width: 3px;
}
}
// The chip has multiple focus targets so we have to put the indicator on
// a separate element, rather than on the focusable element itself.
.mat-mdc-chip-action:focus .mat-focus-indicator::before {
content: '';
} | {
"end_byte": 24468,
"start_byte": 22192,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip.scss"
} |
components/src/material/chips/chips.md_0_8311 | Chips allow users to view information, make selections, filter content, and enter data.
### Static Chips
Chips are always used inside a container. To create chips, start with a `<mat-chip-set>` element. Then, nest `<mat-chip>` elements inside the `<mat-chip-set>`.
<!-- example(chips-overview) -->
By default, `<mat-chip>` renders a chip with Material Design styles applied. For a chip with no styles applied, use `<mat-basic-chip>`.
#### Disabled appearance
Although `<mat-chip>` is not interactive, you can set the `disabled` Input to give it disabled appearance.
```html
<mat-chip disabled>Orange</mat-chip>
```
### Selection Chips
Use `<mat-chip-listbox>` and `<mat-chip-option>` for selecting one or many items from a list. Start with creating a `<mat-chip-listbox>` element. If the user may select more than one option, add the `multiple` attribute. Nest a `<mat-chip-option>` element inside the `<mat-chip-listbox>` for each available option.
#### Disabled `<mat-chip-option>`
Use the `disabled` Input to disable a `<mat-chip-option>`. This gives the `<mat-chip-option>` a disabled appearance and prevents the user from interacting with it.
```html
<mat-chip-option disabled>Orange</mat-chip-option>
```
#### Keyboard Interactions
Users can move through the chips using the arrow keys and select/deselect them with space. Chips also gain focus when clicked, ensuring keyboard navigation starts at the currently focused chip.
### Chips connected to an input field
Use `<mat-chip-grid>` and `<mat-chip-row>` for assisting users with text entry.
Chips are always used inside a container. To create chips connected to an input field, start by creating a `<mat-chip-grid>` as the container. Add an `<input/>` element, and register it to the `<mat-chip-grid>` by passing the `matChipInputFor` Input. Always use an `<input/>` element with `<mat-chip-grid>`. Nest a `<mat-chip-row>` element inside the `<mat-chip-grid>` for each piece of data entered by the user. An example of using chips for text input.
<!-- example(chips-input) -->
### Use with `@angular/forms`
Chips are compatible with `@angular/forms` and supports both `FormsModule`
and `ReactiveFormsModule`.
<!-- example(chips-template-form) -->
<!-- example(chips-reactive-form) -->
#### Disabled `<mat-chip-row>`
Use the `disabled` Input to disable a `<mat-chip-row>`. This gives the `<mat-chip-row>` a disabled appearance and prevents the user from interacting with it.
```html
<mat-chip-row disabled>Orange</mat-chip-row>
```
#### Keyboard Interactions
Users can move through the chips using the arrow keys and select/deselect them with the space. Chips also gain focus when clicked, ensuring keyboard navigation starts at the appropriate chip.
Users can press delete to remove a chip. Pressing delete triggers the `removed` Output on the chip, so be sure to implement `removed` if you require that functionality.
#### Autocomplete
A `<mat-chip-grid>` can be combined with `<mat-autocomplete>` to enable free-form chip input with suggestions.
<!-- example(chips-autocomplete) -->
### Icons
You can add icons to chips to identify entities (like individuals) and provide additional functionality.
#### Adding up to two icons with content projection
You can add two additional icons to an individual chip. A chip has two slots to display icons using content projection. All variants of chips support adding icons including `<mat-chip>`, `<mat-chip-option>`, and `<mat-chip-row>`.
A chip has a front slot for adding an avatar image. To add an avatar, nest an element with `matChipAvatar` attribute inside of `<mat-chip>`.
<!-- example(chips-avatar) -->
You can add an additional icon to the back slot by nesting an element with either the `matChipTrailingIcon` or `matChipRemove` attribute.
#### Remove Button
Sometimes the end user would like the ability to remove a chip. You can provide that functionality using `matChipRemove`. `matChipRemove` renders to the back slot of a chip and triggers the `removed` Output when clicked.
To create a remove button, nest a `<button>` element with `matChipRemove` attribute inside the `<mat-chip-option>`. Be sure to implement the `removed` Output.
```html
<mat-chip-option>
Orange
<button matChipRemove aria-label="Remove orange">
<mat-icon>cancel</mat-icon>
</button>
</mat-chip-option>
```
See the [accessibility](#accessibility) section for best practices on implementing the `removed` Output and creating accessible icons.
### Orientation
By default, chips are displayed horizontally. To stack chips vertically, apply the `mat-mdc-chip-set-stacked` class to `<mat-chip-set>`, `<mat-chip-listbox>` or `<mat-chip-grid>`.
<!-- example(chips-stacked) -->
### Specifying global configuration defaults
Use the `MAT_CHIPS_DEFAULT_OPTIONS` token to specify default options for the chips module.
```html
@NgModule({
providers: [
{
provide: MAT_CHIPS_DEFAULT_OPTIONS,
useValue: {
separatorKeyCodes: [COMMA, SPACE]
}
}
]
})
```
### Interaction Patterns
The chips components support 3 user interaction patterns, each with its own container and chip elements:
#### Listbox
`<mat-chip-listbox>` and `<mat-chip-option>` : These elements implement a listbox accessibility pattern. Use them to present set of user selectable options.
```html
<mat-chip-listbox aria-label="select a shirt size">
<mat-chip-option> Small </mat-chip-option>
<mat-chip-option> Medium </mat-chip-option>
<mat-chip-option> Large </mat-chip-option>
</mat-chip-listbox>
```
#### Text Entry
`<mat-chip-grid>` and `<mat-chip-row>` : These elements implement a grid accessibility pattern. Use them as part of a free form input that allows users to enter text to add chips.
```html
<mat-form-field>
<mat-chip-grid #myChipGrid [(ngModel)]="mySelection"
aria-label="enter sandwich fillings">
@for (filling of fillings; track filling) {
<mat-chip-row (removed)="remove(filling)">
{{filling.name}}
<button matChipRemove>
<mat-icon>cancel</mat-icon>
</button>
</mat-chip-row>
}
<input [matChipInputFor]="myChipGrid"
[matChipInputSeparatorKeyCodes]="separatorKeysCodes"
(matChipInputTokenEnd)="add($event)" />
</mat-chip-grid>
</mat-form-field>
```
#### Static Content
`<mat-chip-set>` and `<mat-chip>` as an unordered list : Present a list of items that are not interactive. This interaction pattern mimics using `ul` and `li` elements. Apply role="list" to the `<mat-list>`. Apply role="listitem" to each `<mat-list-item>`.
```html
<mat-chip-set role="list">
<mat-chip role="listitem"> Sugar </mat-chip>
<mat-chip role="listitem"> Spice </mat-chip>
<mat-chip role="listitem"> Everything Nice </mat-chip>
</mat-chip-set>
```
`<mat-chip-set>` and `<mat-chip>` : These elements do not implement any specific accessibility pattern. Add the appropriate accessibility depending on the context. Note that Angular Material does not intend `<mat-chip>`, `<mat-basic-chip>`, and `<mat-chip-set>` to be interactive.
```html
<mat-chip-set>
<mat-chip> John </mat-chip>
<mat-chip> Paul </mat-chip>
<mat-chip> James </mat-chip>
</mat-chip-set>
```
### Accessibility
The [Interaction Patterns](#interaction-patterns) section describes the three variants of chips available. Choose the chip variant that best matches your use case.
For both MatChipGrid and MatChipListbox, always apply an accessible label to the control via `aria-label` or `aria-labelledby`.
Always apply MatChipRemove to a `<button>` element, never a `<mat-icon>` element.
When using MatChipListbox, never nest other interactive controls inside of the `<mat-chip-option>` element. Nesting controls degrades the experience for assistive technology users.
By default, `MatChipListbox` displays a checkmark to identify selected items. While you can hide the checkmark indicator for single-selection via `hideSingleSelectionIndicator`, this makes the component less accessible by making it harder or impossible for users to visually identify selected items.
When a chip is editable, provide instructions to assistive technology how to edit the chip using a keyboard. One way to accomplish this is adding an `aria-description` attribute with instructions to press enter to edit the chip.
| {
"end_byte": 8311,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chips.md"
} |
components/src/material/chips/chip.html_0_801 | <span class="mat-mdc-chip-focus-overlay"></span>
<span class="mdc-evolution-chip__cell mdc-evolution-chip__cell--primary">
<span matChipAction [isInteractive]="false">
@if (leadingIcon) {
<span class="mdc-evolution-chip__graphic mat-mdc-chip-graphic">
<ng-content select="mat-chip-avatar, [matChipAvatar]"></ng-content>
</span>
}
<span class="mdc-evolution-chip__text-label mat-mdc-chip-action-label">
<ng-content></ng-content>
<span class="mat-mdc-chip-primary-focus-indicator mat-focus-indicator"></span>
</span>
</span>
</span>
@if (_hasTrailingIcon()) {
<span class="mdc-evolution-chip__cell mdc-evolution-chip__cell--trailing">
<ng-content select="mat-chip-trailing-icon,[matChipRemove],[matChipTrailingIcon]"></ng-content>
</span>
}
| {
"end_byte": 801,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip.html"
} |
components/src/material/chips/chip-edit-input.spec.ts_0_1680 | import {Component, DebugElement} from '@angular/core';
import {waitForAsync, TestBed, ComponentFixture} from '@angular/core/testing';
import {MatChipEditInput, MatChipsModule} from './index';
import {By} from '@angular/platform-browser';
describe('MatChipEditInput', () => {
const DEFAULT_INITIAL_VALUE = 'INITIAL_VALUE';
let fixture: ComponentFixture<any>;
let inputDebugElement: DebugElement;
let inputInstance: MatChipEditInput;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, ChipEditInputContainer],
});
fixture = TestBed.createComponent(ChipEditInputContainer);
inputDebugElement = fixture.debugElement.query(By.directive(MatChipEditInput))!;
inputInstance = inputDebugElement.injector.get<MatChipEditInput>(MatChipEditInput);
}));
describe('on initialization', () => {
it('should set the initial input text', () => {
inputInstance.initialize(DEFAULT_INITIAL_VALUE);
expect(inputInstance.getNativeElement().textContent).toEqual(DEFAULT_INITIAL_VALUE);
});
it('should focus the input', () => {
inputInstance.initialize(DEFAULT_INITIAL_VALUE);
expect(document.activeElement).toEqual(inputInstance.getNativeElement());
});
});
it('should update the internal value as it is set', () => {
inputInstance.initialize(DEFAULT_INITIAL_VALUE);
const newValue = 'NEW_VALUE';
inputInstance.setValue(newValue);
expect(inputInstance.getValue()).toEqual(newValue);
});
});
@Component({
template: `<mat-chip><span matChipEditInput></span></mat-chip>`,
standalone: true,
imports: [MatChipsModule],
})
class ChipEditInputContainer {}
| {
"end_byte": 1680,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-edit-input.spec.ts"
} |
components/src/material/chips/chip-edit-input.ts_0_1463 | /**
* @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} from '@angular/core';
import {DOCUMENT} from '@angular/common';
/**
* A directive that makes a span editable and exposes functions to modify and retrieve the
* element's contents.
*/
@Directive({
selector: 'span[matChipEditInput]',
host: {
'class': 'mat-chip-edit-input',
'role': 'textbox',
'tabindex': '-1',
'contenteditable': 'true',
},
})
export class MatChipEditInput {
private readonly _elementRef = inject(ElementRef);
private readonly _document = inject(DOCUMENT);
constructor(...args: unknown[]);
constructor() {}
initialize(initialValue: string) {
this.getNativeElement().focus();
this.setValue(initialValue);
}
getNativeElement(): HTMLElement {
return this._elementRef.nativeElement;
}
setValue(value: string) {
this.getNativeElement().textContent = value;
this._moveCursorToEndOfInput();
}
getValue(): string {
return this.getNativeElement().textContent || '';
}
private _moveCursorToEndOfInput() {
const range = this._document.createRange();
range.selectNodeContents(this.getNativeElement());
range.collapse(false);
const sel = window.getSelection()!;
sel.removeAllRanges();
sel.addRange(range);
}
}
| {
"end_byte": 1463,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-edit-input.ts"
} |
components/src/material/chips/chip.ts_0_2926 | /**
* @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 {BACKSPACE, DELETE} from '@angular/cdk/keycodes';
import {DOCUMENT} from '@angular/common';
import {
ANIMATION_MODULE_TYPE,
AfterContentInit,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
DoCheck,
ElementRef,
EventEmitter,
Injector,
Input,
NgZone,
OnDestroy,
OnInit,
Output,
QueryList,
ViewChild,
ViewEncapsulation,
afterNextRender,
booleanAttribute,
inject,
} from '@angular/core';
import {
_StructuralStylesLoader,
MAT_RIPPLE_GLOBAL_OPTIONS,
MatRippleLoader,
RippleGlobalOptions,
} from '@angular/material/core';
import {Subject, Subscription, merge} from 'rxjs';
import {MatChipAction} from './chip-action';
import {MatChipAvatar, MatChipRemove, MatChipTrailingIcon} from './chip-icons';
import {MAT_CHIP, MAT_CHIP_AVATAR, MAT_CHIP_REMOVE, MAT_CHIP_TRAILING_ICON} from './tokens';
import {_CdkPrivateStyleLoader, _VisuallyHiddenLoader} from '@angular/cdk/private';
let uid = 0;
/** Represents an event fired on an individual `mat-chip`. */
export interface MatChipEvent {
/** The chip the event was fired on. */
chip: MatChip;
}
/**
* Material design styled Chip base component. Used inside the MatChipSet component.
*
* Extended by MatChipOption and MatChipRow for different interaction patterns.
*/
@Component({
selector: 'mat-basic-chip, [mat-basic-chip], mat-chip, [mat-chip]',
exportAs: 'matChip',
templateUrl: 'chip.html',
styleUrl: 'chip.css',
host: {
'class': 'mat-mdc-chip',
'[class]': '"mat-" + (color || "primary")',
'[class.mdc-evolution-chip]': '!_isBasicChip',
'[class.mdc-evolution-chip--disabled]': 'disabled',
'[class.mdc-evolution-chip--with-trailing-action]': '_hasTrailingIcon()',
'[class.mdc-evolution-chip--with-primary-graphic]': 'leadingIcon',
'[class.mdc-evolution-chip--with-primary-icon]': 'leadingIcon',
'[class.mdc-evolution-chip--with-avatar]': 'leadingIcon',
'[class.mat-mdc-chip-with-avatar]': 'leadingIcon',
'[class.mat-mdc-chip-highlighted]': 'highlighted',
'[class.mat-mdc-chip-disabled]': 'disabled',
'[class.mat-mdc-basic-chip]': '_isBasicChip',
'[class.mat-mdc-standard-chip]': '!_isBasicChip',
'[class.mat-mdc-chip-with-trailing-icon]': '_hasTrailingIcon()',
'[class._mat-animation-noopable]': '_animationsDisabled',
'[id]': 'id',
'[attr.role]': 'role',
'[attr.aria-label]': 'ariaLabel',
'(keydown)': '_handleKeydown($event)',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [{provide: MAT_CHIP, useExisting: MatChip}],
imports: [MatChipAction],
})
export | {
"end_byte": 2926,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip.ts"
} |
components/src/material/chips/chip.ts_2927_11037 | class MatChip implements OnInit, AfterViewInit, AfterContentInit, DoCheck, OnDestroy {
_changeDetectorRef = inject(ChangeDetectorRef);
_elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
protected _ngZone = inject(NgZone);
private _focusMonitor = inject(FocusMonitor);
private _globalRippleOptions = inject<RippleGlobalOptions>(MAT_RIPPLE_GLOBAL_OPTIONS, {
optional: true,
});
protected _document = inject(DOCUMENT);
/** Emits when the chip is focused. */
readonly _onFocus = new Subject<MatChipEvent>();
/** Emits when the chip is blurred. */
readonly _onBlur = new Subject<MatChipEvent>();
/** Whether this chip is a basic (unstyled) chip. */
_isBasicChip: boolean;
/** Role for the root of the chip. */
@Input() role: string | null = null;
/** Whether the chip has focus. */
private _hasFocusInternal = false;
/** Whether moving focus into the chip is pending. */
private _pendingFocus: boolean;
/** Subscription to changes in the chip's actions. */
private _actionChanges: Subscription | undefined;
/** Whether animations for the chip are enabled. */
_animationsDisabled: boolean;
/** All avatars present in the chip. */
@ContentChildren(MAT_CHIP_AVATAR, {descendants: true})
protected _allLeadingIcons: QueryList<MatChipAvatar>;
/** All trailing icons present in the chip. */
@ContentChildren(MAT_CHIP_TRAILING_ICON, {descendants: true})
protected _allTrailingIcons: QueryList<MatChipTrailingIcon>;
/** All remove icons present in the chip. */
@ContentChildren(MAT_CHIP_REMOVE, {descendants: true})
protected _allRemoveIcons: QueryList<MatChipRemove>;
_hasFocus() {
return this._hasFocusInternal;
}
/** A unique id for the chip. If none is supplied, it will be auto-generated. */
@Input() id: string = `mat-mdc-chip-${uid++}`;
// TODO(#26104): Consider deprecating and using `_computeAriaAccessibleName` instead.
// `ariaLabel` may be unnecessary, and `_computeAriaAccessibleName` only supports
// datepicker's use case.
/** ARIA label for the content of the chip. */
@Input('aria-label') ariaLabel: string | null = null;
// TODO(#26104): Consider deprecating and using `_computeAriaAccessibleName` instead.
// `ariaDescription` may be unnecessary, and `_computeAriaAccessibleName` only supports
// datepicker's use case.
/** ARIA description for the content of the chip. */
@Input('aria-description') ariaDescription: string | null = null;
/** Id of a span that contains this chip's aria description. */
_ariaDescriptionId = `${this.id}-aria-description`;
/** Whether the chip list is disabled. */
_chipListDisabled: boolean = false;
private _textElement!: HTMLElement;
/**
* The value of the chip. Defaults to the content inside
* the `mat-mdc-chip-action-label` element.
*/
@Input()
get value(): any {
return this._value !== undefined ? this._value : this._textElement.textContent!.trim();
}
set value(value: any) {
this._value = value;
}
protected _value: any;
// TODO: should be typed as `ThemePalette` but internal apps pass in arbitrary strings.
/**
* Theme color of the chip. This API is supported in M2 themes only, it has no
* effect in M3 themes.
*
* For information on applying color variants in M3, see
* https://material.angular.io/guide/theming#using-component-color-variants.
*/
@Input() color?: string | null;
/**
* Determines whether or not the chip displays the remove styling and emits (removed) events.
*/
@Input({transform: booleanAttribute})
removable: boolean = true;
/**
* Colors the chip for emphasis as if it were selected.
*/
@Input({transform: booleanAttribute})
highlighted: boolean = false;
/** Whether the ripple effect is disabled or not. */
@Input({transform: booleanAttribute})
disableRipple: boolean = false;
/** Whether the chip is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this._disabled || this._chipListDisabled;
}
set disabled(value: boolean) {
this._disabled = value;
}
private _disabled = false;
/** Emitted when a chip is to be removed. */
@Output() readonly removed: EventEmitter<MatChipEvent> = new EventEmitter<MatChipEvent>();
/** Emitted when the chip is destroyed. */
@Output() readonly destroyed: EventEmitter<MatChipEvent> = new EventEmitter<MatChipEvent>();
/** The unstyled chip selector for this component. */
protected basicChipAttrName = 'mat-basic-chip';
/** The chip's leading icon. */
@ContentChild(MAT_CHIP_AVATAR) leadingIcon: MatChipAvatar;
/** The chip's trailing icon. */
@ContentChild(MAT_CHIP_TRAILING_ICON) trailingIcon: MatChipTrailingIcon;
/** The chip's trailing remove icon. */
@ContentChild(MAT_CHIP_REMOVE) removeIcon: MatChipRemove;
/** Action receiving the primary set of user interactions. */
@ViewChild(MatChipAction) primaryAction: MatChipAction;
/**
* Handles the lazy creation of the MatChip ripple.
* Used to improve initial load time of large applications.
*/
private _rippleLoader: MatRippleLoader = inject(MatRippleLoader);
protected _injector = inject(Injector);
constructor(...args: unknown[]);
constructor() {
inject(_CdkPrivateStyleLoader).load(_StructuralStylesLoader);
inject(_CdkPrivateStyleLoader).load(_VisuallyHiddenLoader);
const animationMode = inject(ANIMATION_MODULE_TYPE, {optional: true});
this._animationsDisabled = animationMode === 'NoopAnimations';
this._monitorFocus();
this._rippleLoader?.configureRipple(this._elementRef.nativeElement, {
className: 'mat-mdc-chip-ripple',
disabled: this._isRippleDisabled(),
});
}
ngOnInit() {
// This check needs to happen in `ngOnInit` so the overridden value of
// `basicChipAttrName` coming from base classes can be picked up.
const element = this._elementRef.nativeElement;
this._isBasicChip =
element.hasAttribute(this.basicChipAttrName) ||
element.tagName.toLowerCase() === this.basicChipAttrName;
}
ngAfterViewInit() {
this._textElement = this._elementRef.nativeElement.querySelector('.mat-mdc-chip-action-label')!;
if (this._pendingFocus) {
this._pendingFocus = false;
this.focus();
}
}
ngAfterContentInit(): void {
// Since the styling depends on the presence of some
// actions, we have to mark for check on changes.
this._actionChanges = merge(
this._allLeadingIcons.changes,
this._allTrailingIcons.changes,
this._allRemoveIcons.changes,
).subscribe(() => this._changeDetectorRef.markForCheck());
}
ngDoCheck(): void {
this._rippleLoader.setDisabled(this._elementRef.nativeElement, this._isRippleDisabled());
}
ngOnDestroy() {
this._focusMonitor.stopMonitoring(this._elementRef);
this._rippleLoader?.destroyRipple(this._elementRef.nativeElement);
this._actionChanges?.unsubscribe();
this.destroyed.emit({chip: this});
this.destroyed.complete();
}
/**
* Allows for programmatic removal of the chip.
*
* Informs any listeners of the removal request. Does not remove the chip from the DOM.
*/
remove(): void {
if (this.removable) {
this.removed.emit({chip: this});
}
}
/** Whether or not the ripple should be disabled. */
_isRippleDisabled(): boolean {
return (
this.disabled ||
this.disableRipple ||
this._animationsDisabled ||
this._isBasicChip ||
!!this._globalRippleOptions?.disabled
);
}
/** Returns whether the chip has a trailing icon. */
_hasTrailingIcon() {
return !!(this.trailingIcon || this.removeIcon);
}
/** Handles keyboard events on the chip. */
_handleKeydown(event: KeyboardEvent) {
// Ignore backspace events where the user is holding down the key
// so that we don't accidentally remove too many chips.
if ((event.keyCode === BACKSPACE && !event.repeat) || event.keyCode === DELETE) {
event.preventDefault();
this.remove();
}
}
/** Allows for programmatic focusing of the chip. */ | {
"end_byte": 11037,
"start_byte": 2927,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip.ts"
} |
components/src/material/chips/chip.ts_11040_13222 | focus(): void {
if (!this.disabled) {
// If `focus` is called before `ngAfterViewInit`, we won't have access to the primary action.
// This can happen if the consumer tries to focus a chip immediately after it is added.
// Queue the method to be called again on init.
if (this.primaryAction) {
this.primaryAction.focus();
} else {
this._pendingFocus = true;
}
}
}
/** Gets the action that contains a specific target node. */
_getSourceAction(target: Node): MatChipAction | undefined {
return this._getActions().find(action => {
const element = action._elementRef.nativeElement;
return element === target || element.contains(target);
});
}
/** Gets all of the actions within the chip. */
_getActions(): MatChipAction[] {
const result: MatChipAction[] = [];
if (this.primaryAction) {
result.push(this.primaryAction);
}
if (this.removeIcon) {
result.push(this.removeIcon);
}
if (this.trailingIcon) {
result.push(this.trailingIcon);
}
return result;
}
/** Handles interactions with the primary action of the chip. */
_handlePrimaryActionInteraction() {
// Empty here, but is overwritten in child classes.
}
/** Starts the focus monitoring process on the chip. */
private _monitorFocus() {
this._focusMonitor.monitor(this._elementRef, true).subscribe(origin => {
const hasFocus = origin !== null;
if (hasFocus !== this._hasFocusInternal) {
this._hasFocusInternal = hasFocus;
if (hasFocus) {
this._onFocus.next({chip: this});
} else {
// When animations are enabled, Angular may end up removing the chip from the DOM a little
// earlier than usual, causing it to be blurred and throwing off the logic in the chip list
// that moves focus not the next item. To work around the issue, we defer marking the chip
// as not focused until after the next render.
afterNextRender(() => this._ngZone.run(() => this._onBlur.next({chip: this})), {
injector: this._injector,
});
}
}
});
}
} | {
"end_byte": 13222,
"start_byte": 11040,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip.ts"
} |
components/src/material/chips/chip-set.spec.ts_0_4566 | import {Component, DebugElement, QueryList} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, tick, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {MatChip, MatChipSet, MatChipsModule} from './index';
describe('MatChipSet', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, BasicChipSet, IndirectDescendantsChipSet],
});
}));
describe('BasicChipSet', () => {
let fixture: ComponentFixture<any>;
let chipSetDebugElement: DebugElement;
let chipSetNativeElement: HTMLElement;
let chipSetInstance: MatChipSet;
let chips: QueryList<MatChip>;
describe('basic behaviors', () => {
beforeEach(() => {
fixture = TestBed.createComponent(BasicChipSet);
fixture.detectChanges();
chipSetDebugElement = fixture.debugElement.query(By.directive(MatChipSet))!;
chipSetNativeElement = chipSetDebugElement.nativeElement;
chipSetInstance = chipSetDebugElement.componentInstance;
chips = chipSetInstance._chips;
});
it('should add the `mat-mdc-chip-set` class', () => {
expect(chipSetNativeElement.classList).toContain('mat-mdc-chip-set');
});
it('should toggle the chips disabled state based on whether it is disabled', () => {
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
chipSetInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(true);
chipSetInstance.disabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
});
it('should disable a chip that is added after the set became disabled', fakeAsync(() => {
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
chipSetInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(true);
fixture.componentInstance.chips.push(5, 6);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(true);
}));
it('should have role presentation by default', () => {
expect(chipSetNativeElement.getAttribute('role')).toBe('presentation');
});
it('should allow a custom role to be specified', () => {
chipSetInstance.role = 'list';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipSetNativeElement.getAttribute('role')).toBe('list');
});
});
});
it('should sync the disabled state to indirect descendant chips', () => {
const fixture = TestBed.createComponent(IndirectDescendantsChipSet);
fixture.detectChanges();
const chipSetDebugElement = fixture.debugElement.query(By.directive(MatChipSet))!;
const chipSetInstance = chipSetDebugElement.componentInstance;
const chips: QueryList<MatChip> = chipSetInstance._chips;
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
chipSetInstance.disabled = true;
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(true);
chipSetInstance.disabled = false;
fixture.detectChanges();
expect(chips.toArray().every(chip => chip.disabled)).toBe(false);
});
it('should be able to access the `empty` getter before the chips are initialized', () => {
const fixture = TestBed.createComponent(BasicChipSet);
const chipSet = fixture.debugElement.query(By.directive(MatChipSet))!;
expect(chipSet.componentInstance.empty).toBe(true);
});
});
@Component({
template: `
<mat-chip-set>
@for (i of chips; track i) {
<mat-chip>{{name}} {{i + 1}}</mat-chip>
}
</mat-chip-set>
`,
standalone: true,
imports: [MatChipsModule],
})
class BasicChipSet {
name: string = 'Test';
chips = [0, 1, 2, 3, 4];
}
@Component({
template: `
<mat-chip-set>
@if (true) {
@for (i of chips; track i) {
<mat-chip>{{name}} {{i + 1}}</mat-chip>
}
}
</mat-chip-set>
`,
standalone: true,
imports: [MatChipsModule],
})
class IndirectDescendantsChipSet extends BasicChipSet {}
| {
"end_byte": 4566,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-set.spec.ts"
} |
components/src/material/chips/BUILD.bazel_0_2060 | 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 = "chips",
srcs = glob(
["**/*.ts"],
exclude = [
"**/*.spec.ts",
],
),
assets = [
":chip_scss",
":chip_set_scss",
] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/material/core",
"//src/material/form-field",
"@npm//@angular/animations",
"@npm//@angular/core",
"@npm//@angular/forms",
],
)
sass_library(
name = "chips_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "chip_scss",
src = "chip.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "chip_set_scss",
src = "chip-set.scss",
deps = [
"//src/material/core:core_scss_lib",
],
)
ng_test_library(
name = "chips_tests_lib",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":chips",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/keycodes",
"//src/cdk/platform",
"//src/cdk/testing",
"//src/cdk/testing/private",
"//src/material/core",
"//src/material/form-field",
"//src/material/input",
"@npm//@angular/animations",
"@npm//@angular/common",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":chips_tests_lib",
],
)
markdown_to_html(
name = "overview",
srcs = [":chips.md"],
)
extract_tokens(
name = "tokens",
srcs = [":chips_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 2060,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/BUILD.bazel"
} |
components/src/material/chips/chip-row.html_0_1227 | @if (!_isEditing) {
<span class="mat-mdc-chip-focus-overlay"></span>
}
<span class="mdc-evolution-chip__cell mdc-evolution-chip__cell--primary" role="gridcell"
matChipAction
[disabled]="disabled"
[attr.aria-label]="ariaLabel"
[attr.aria-describedby]="_ariaDescriptionId">
@if (leadingIcon) {
<span class="mdc-evolution-chip__graphic mat-mdc-chip-graphic">
<ng-content select="mat-chip-avatar, [matChipAvatar]"></ng-content>
</span>
}
<span class="mdc-evolution-chip__text-label mat-mdc-chip-action-label">
@if (_isEditing) {
@if (contentEditInput) {
<ng-content select="[matChipEditInput]"></ng-content>
} @else {
<span matChipEditInput></span>
}
} @else {
<ng-content></ng-content>
}
<span class="mat-mdc-chip-primary-focus-indicator mat-focus-indicator" aria-hidden="true"></span>
</span>
</span>
@if (_hasTrailingIcon()) {
<span
class="mdc-evolution-chip__cell mdc-evolution-chip__cell--trailing"
role="gridcell">
<ng-content select="mat-chip-trailing-icon,[matChipRemove],[matChipTrailingIcon]"></ng-content>
</span>
}
<span class="cdk-visually-hidden" [id]="_ariaDescriptionId">{{ariaDescription}}</span>
| {
"end_byte": 1227,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-row.html"
} |
components/src/material/chips/chip-input.ts_0_6754 | /**
* @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 {BACKSPACE, hasModifierKey} from '@angular/cdk/keycodes';
import {
Directive,
ElementRef,
EventEmitter,
Input,
OnChanges,
OnDestroy,
Output,
booleanAttribute,
inject,
} from '@angular/core';
import {MatFormField, MAT_FORM_FIELD} from '@angular/material/form-field';
import {MatChipsDefaultOptions, MAT_CHIPS_DEFAULT_OPTIONS} from './tokens';
import {MatChipGrid} from './chip-grid';
import {MatChipTextControl} from './chip-text-control';
/** Represents an input event on a `matChipInput`. */
export interface MatChipInputEvent {
/**
* The native `<input>` element that the event is being fired for.
* @deprecated Use `MatChipInputEvent#chipInput.inputElement` instead.
* @breaking-change 13.0.0 This property will be removed.
*/
input: HTMLInputElement;
/** The value of the input. */
value: string;
/** Reference to the chip input that emitted the event. */
chipInput: MatChipInput;
}
// Increasing integer for generating unique ids.
let nextUniqueId = 0;
/**
* Directive that adds chip-specific behaviors to an input element inside `<mat-form-field>`.
* May be placed inside or outside of a `<mat-chip-grid>`.
*/
@Directive({
selector: 'input[matChipInputFor]',
exportAs: 'matChipInput, matChipInputFor',
host: {
// TODO: eventually we should remove `mat-input-element` from here since it comes from the
// non-MDC version of the input. It's currently being kept for backwards compatibility, because
// the MDC chips were landed initially with it.
'class': 'mat-mdc-chip-input mat-mdc-input-element mdc-text-field__input mat-input-element',
'(keydown)': '_keydown($event)',
'(blur)': '_blur()',
'(focus)': '_focus()',
'(input)': '_onInput()',
'[id]': 'id',
'[attr.disabled]': 'disabled || null',
'[attr.placeholder]': 'placeholder || null',
'[attr.aria-invalid]': '_chipGrid && _chipGrid.ngControl ? _chipGrid.ngControl.invalid : null',
'[attr.aria-required]': '_chipGrid && _chipGrid.required || null',
'[attr.required]': '_chipGrid && _chipGrid.required || null',
},
})
export class MatChipInput implements MatChipTextControl, OnChanges, OnDestroy {
protected _elementRef = inject<ElementRef<HTMLInputElement>>(ElementRef);
/** Whether the control is focused. */
focused: boolean = false;
/** Register input for chip list */
@Input('matChipInputFor')
get chipGrid(): MatChipGrid {
return this._chipGrid;
}
set chipGrid(value: MatChipGrid) {
if (value) {
this._chipGrid = value;
this._chipGrid.registerInput(this);
}
}
private _chipGrid: MatChipGrid;
/**
* Whether or not the chipEnd event will be emitted when the input is blurred.
*/
@Input({alias: 'matChipInputAddOnBlur', transform: booleanAttribute})
addOnBlur: boolean = false;
/**
* The list of key codes that will trigger a chipEnd event.
*
* Defaults to `[ENTER]`.
*/
@Input('matChipInputSeparatorKeyCodes')
separatorKeyCodes: readonly number[] | ReadonlySet<number>;
/** Emitted when a chip is to be added. */
@Output('matChipInputTokenEnd')
readonly chipEnd: EventEmitter<MatChipInputEvent> = new EventEmitter<MatChipInputEvent>();
/** The input's placeholder text. */
@Input() placeholder: string = '';
/** Unique id for the input. */
@Input() id: string = `mat-mdc-chip-list-input-${nextUniqueId++}`;
/** Whether the input is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this._disabled || (this._chipGrid && this._chipGrid.disabled);
}
set disabled(value: boolean) {
this._disabled = value;
}
private _disabled: boolean = false;
/** Whether the input is empty. */
get empty(): boolean {
return !this.inputElement.value;
}
/** The native input element to which this directive is attached. */
readonly inputElement!: HTMLInputElement;
constructor(...args: unknown[]);
constructor() {
const defaultOptions = inject<MatChipsDefaultOptions>(MAT_CHIPS_DEFAULT_OPTIONS);
const formField = inject<MatFormField>(MAT_FORM_FIELD, {optional: true});
this.inputElement = this._elementRef.nativeElement as HTMLInputElement;
this.separatorKeyCodes = defaultOptions.separatorKeyCodes;
if (formField) {
this.inputElement.classList.add('mat-mdc-form-field-input-control');
}
}
ngOnChanges() {
this._chipGrid.stateChanges.next();
}
ngOnDestroy(): void {
this.chipEnd.complete();
}
/** Utility method to make host definition/tests more clear. */
_keydown(event: KeyboardEvent) {
if (this.empty && event.keyCode === BACKSPACE) {
// Ignore events where the user is holding down backspace
// so that we don't accidentally remove too many chips.
if (!event.repeat) {
this._chipGrid._focusLastChip();
}
event.preventDefault();
} else {
this._emitChipEnd(event);
}
}
/** Checks to see if the blur should emit the (chipEnd) event. */
_blur() {
if (this.addOnBlur) {
this._emitChipEnd();
}
this.focused = false;
// Blur the chip list if it is not focused
if (!this._chipGrid.focused) {
this._chipGrid._blur();
}
this._chipGrid.stateChanges.next();
}
_focus() {
this.focused = true;
this._chipGrid.stateChanges.next();
}
/** Checks to see if the (chipEnd) event needs to be emitted. */
_emitChipEnd(event?: KeyboardEvent) {
if (!event || (this._isSeparatorKey(event) && !event.repeat)) {
this.chipEnd.emit({
input: this.inputElement,
value: this.inputElement.value,
chipInput: this,
});
event?.preventDefault();
}
}
_onInput() {
// Let chip list know whenever the value changes.
this._chipGrid.stateChanges.next();
}
/** Focuses the input. */
focus(): void {
this.inputElement.focus();
}
/** Clears the input */
clear(): void {
this.inputElement.value = '';
}
setDescribedByIds(ids: string[]): void {
const element = this._elementRef.nativeElement;
// Set the value directly in the DOM since this binding
// is prone to "changed after checked" errors.
if (ids.length) {
element.setAttribute('aria-describedby', ids.join(' '));
} else {
element.removeAttribute('aria-describedby');
}
}
/** Checks whether a keycode is one of the configured separators. */
private _isSeparatorKey(event: KeyboardEvent) {
return !hasModifierKey(event) && new Set(this.separatorKeyCodes).has(event.keyCode);
}
}
| {
"end_byte": 6754,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-input.ts"
} |
components/src/material/chips/chip-row.spec.ts_0_7926 | import {Directionality} from '@angular/cdk/bidi';
import {BACKSPACE, DELETE, ENTER, SPACE} from '@angular/cdk/keycodes';
import {
createKeyboardEvent,
dispatchEvent,
dispatchFakeEvent,
dispatchKeyboardEvent,
} from '@angular/cdk/testing/private';
import {Component, DebugElement, ElementRef, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {Subject} from 'rxjs';
import {
MatChipEditInput,
MatChipEditedEvent,
MatChipEvent,
MatChipGrid,
MatChipRow,
MatChipsModule,
} from './index';
describe('Row Chips', () => {
let fixture: ComponentFixture<any>;
let chipDebugElement: DebugElement;
let chipNativeElement: HTMLElement;
let chipInstance: MatChipRow;
let dir = 'ltr';
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, SingleChip],
providers: [
{
provide: Directionality,
useFactory: () => ({
value: dir,
change: new Subject(),
}),
},
],
});
}));
describe('MatChipRow', () => {
let testComponent: SingleChip;
beforeEach(() => {
fixture = TestBed.createComponent(SingleChip);
fixture.detectChanges();
chipDebugElement = fixture.debugElement.query(By.directive(MatChipRow))!;
chipNativeElement = chipDebugElement.nativeElement;
chipInstance = chipDebugElement.injector.get<MatChipRow>(MatChipRow);
testComponent = fixture.debugElement.componentInstance;
});
describe('basic behaviors', () => {
it('adds the `mat-mdc-chip` class', () => {
expect(chipNativeElement.classList).toContain('mat-mdc-chip');
});
it('does not add the `mat-basic-chip` class', () => {
expect(chipNativeElement.classList).not.toContain('mat-basic-chip');
});
it('emits destroy on destruction', () => {
spyOn(testComponent, 'chipDestroy').and.callThrough();
// Force a destroy callback
testComponent.shouldShow = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(testComponent.chipDestroy).toHaveBeenCalledTimes(1);
});
it('allows color customization', () => {
expect(chipNativeElement.classList).toContain('mat-primary');
testComponent.color = 'warn';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipNativeElement.classList).not.toContain('mat-primary');
expect(chipNativeElement.classList).toContain('mat-warn');
});
it('allows removal', () => {
spyOn(testComponent, 'chipRemove');
chipInstance.remove();
fixture.detectChanges();
expect(testComponent.chipRemove).toHaveBeenCalledWith({chip: chipInstance});
});
it('should have a tabindex', () => {
expect(chipNativeElement.getAttribute('tabindex')).toBe('-1');
});
it('should have the correct role', () => {
expect(chipNativeElement.getAttribute('role')).toBe('row');
});
it('should be able to set a custom role', () => {
chipInstance.role = 'button';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipNativeElement.getAttribute('role')).toBe('button');
});
});
describe('keyboard behavior', () => {
describe('when removable is true', () => {
beforeEach(() => {
testComponent.removable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
it('DELETE emits the (removed) event', () => {
const DELETE_EVENT = createKeyboardEvent('keydown', DELETE);
spyOn(testComponent, 'chipRemove');
dispatchEvent(chipNativeElement, DELETE_EVENT);
fixture.detectChanges();
expect(testComponent.chipRemove).toHaveBeenCalled();
});
it('BACKSPACE emits the (removed) event', () => {
const BACKSPACE_EVENT = createKeyboardEvent('keydown', BACKSPACE);
spyOn(testComponent, 'chipRemove');
dispatchEvent(chipNativeElement, BACKSPACE_EVENT);
fixture.detectChanges();
expect(testComponent.chipRemove).toHaveBeenCalled();
});
it('should not remove for repeated BACKSPACE event', () => {
const BACKSPACE_EVENT = createKeyboardEvent('keydown', BACKSPACE);
Object.defineProperty(BACKSPACE_EVENT, 'repeat', {
get: () => true,
});
spyOn(testComponent, 'chipRemove');
dispatchEvent(chipNativeElement, BACKSPACE_EVENT);
fixture.detectChanges();
expect(testComponent.chipRemove).not.toHaveBeenCalled();
});
});
describe('when removable is false', () => {
beforeEach(() => {
testComponent.removable = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
it('DELETE does not emit the (removed) event', () => {
const DELETE_EVENT = createKeyboardEvent('keydown', DELETE);
spyOn(testComponent, 'chipRemove');
dispatchEvent(chipNativeElement, DELETE_EVENT);
fixture.detectChanges();
expect(testComponent.chipRemove).not.toHaveBeenCalled();
});
it('BACKSPACE does not emit the (removed) event', () => {
const BACKSPACE_EVENT = createKeyboardEvent('keydown', BACKSPACE);
spyOn(testComponent, 'chipRemove');
// Use the delete to remove the chip
dispatchEvent(chipNativeElement, BACKSPACE_EVENT);
fixture.detectChanges();
expect(testComponent.chipRemove).not.toHaveBeenCalled();
});
});
it('should update the aria-label for disabled chips', () => {
const primaryActionElement = chipNativeElement.querySelector(
'.mdc-evolution-chip__action--primary',
)!;
expect(primaryActionElement.getAttribute('aria-disabled')).toBe('false');
testComponent.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(primaryActionElement.getAttribute('aria-disabled')).toBe('true');
});
describe('focus management', () => {
it('sends focus to first grid cell on root chip focus', () => {
dispatchFakeEvent(chipNativeElement, 'focus');
fixture.detectChanges();
expect(document.activeElement).toHaveClass('mdc-evolution-chip__action--primary');
});
it('emits focus only once for multiple focus() calls', () => {
let counter = 0;
chipInstance._onFocus.subscribe(() => {
counter++;
});
chipInstance.focus();
chipInstance.focus();
fixture.detectChanges();
expect(counter).toBe(1);
});
});
});
describe('editable behavior', () => {
beforeEach(() => {
testComponent.editable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
it('should begin editing on double click', () => {
expect(chipNativeElement.querySelector('.mat-chip-edit-input')).toBeFalsy();
dispatchFakeEvent(chipNativeElement, 'dblclick');
fixture.detectChanges();
expect(chipNativeElement.querySelector('.mat-chip-edit-input')).toBeTruthy();
});
it('should begin editing on ENTER', () => {
expect(chipNativeElement.querySelector('.mat-chip-edit-input')).toBeFalsy();
dispatchKeyboardEvent(chipNativeElement, 'keydown', ENTER);
fixture.detectChanges();
expect(chipNativeElement.querySelector('.mat-chip-edit-input')).toBeTruthy();
});
}); | {
"end_byte": 7926,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-row.spec.ts"
} |
components/src/material/chips/chip-row.spec.ts_7932_15643 | describe('editing behavior', () => {
let editInputInstance: MatChipEditInput;
let primaryAction: HTMLElement;
beforeEach(fakeAsync(() => {
testComponent.editable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchFakeEvent(chipNativeElement, 'dblclick');
fixture.detectChanges();
flush();
spyOn(testComponent, 'chipEdit');
const editInputDebugElement = fixture.debugElement.query(By.directive(MatChipEditInput))!;
editInputInstance = editInputDebugElement.injector.get<MatChipEditInput>(MatChipEditInput);
primaryAction = chipNativeElement.querySelector('.mdc-evolution-chip__action--primary')!;
}));
function keyDownOnPrimaryAction(keyCode: number, key: string) {
const keyDownEvent = createKeyboardEvent('keydown', keyCode, key);
dispatchEvent(primaryAction, keyDownEvent);
fixture.detectChanges();
}
function getEditInput(): HTMLElement {
return chipNativeElement.querySelector('.mat-chip-edit-input')!;
}
it('should set the role of the primary action to gridcell', () => {
testComponent.editable = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(primaryAction.getAttribute('role')).toBe('gridcell');
testComponent.editable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
// Test regression of bug where element is mislabeled as a button role. Element that does not perform its
// action on click event is not a button by ARIA spec (#27106).
expect(primaryAction.getAttribute('role')).toBe('gridcell');
});
it('should not delete the chip on DELETE or BACKSPACE', () => {
spyOn(testComponent, 'chipDestroy');
keyDownOnPrimaryAction(DELETE, 'Delete');
keyDownOnPrimaryAction(BACKSPACE, 'Backspace');
expect(testComponent.chipDestroy).not.toHaveBeenCalled();
});
it('should stop editing on blur', fakeAsync(() => {
chipInstance._onBlur.next();
flush();
expect(testComponent.chipEdit).toHaveBeenCalled();
}));
it('should stop editing on ENTER', fakeAsync(() => {
dispatchKeyboardEvent(getEditInput(), 'keydown', ENTER);
fixture.detectChanges();
flush();
expect(testComponent.chipEdit).toHaveBeenCalled();
}));
it('should emit the new chip value when editing completes', fakeAsync(() => {
const chipValue = 'chip value';
editInputInstance.setValue(chipValue);
dispatchKeyboardEvent(getEditInput(), 'keydown', ENTER);
flush();
const expectedValue = jasmine.objectContaining({value: chipValue});
expect(testComponent.chipEdit).toHaveBeenCalledWith(expectedValue);
}));
it('should use the projected edit input if provided', () => {
expect(editInputInstance.getNativeElement()).toHaveClass('projected-edit-input');
});
it('should use the default edit input if none is projected', () => {
keyDownOnPrimaryAction(ENTER, 'Enter');
testComponent.useCustomEditInput = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchFakeEvent(chipNativeElement, 'dblclick');
fixture.detectChanges();
const editInputDebugElement = fixture.debugElement.query(By.directive(MatChipEditInput))!;
const editInputNoProject =
editInputDebugElement.injector.get<MatChipEditInput>(MatChipEditInput);
expect(editInputNoProject.getNativeElement()).not.toHaveClass('projected-edit-input');
});
it('should focus the chip content if the edit input has focus on completion', fakeAsync(() => {
const chipValue = 'chip value';
editInputInstance.setValue(chipValue);
dispatchKeyboardEvent(getEditInput(), 'keydown', ENTER);
fixture.detectChanges();
flush();
expect(document.activeElement).toBe(primaryAction);
}));
it('should not change focus if another element has focus on completion', fakeAsync(() => {
const chipValue = 'chip value';
editInputInstance.setValue(chipValue);
testComponent.chipInput.nativeElement.focus();
keyDownOnPrimaryAction(ENTER, 'Enter');
flush();
expect(document.activeElement).not.toBe(primaryAction);
}));
it('should not prevent SPACE events when editing', fakeAsync(() => {
const event = dispatchKeyboardEvent(getEditInput(), 'keydown', SPACE);
fixture.detectChanges();
flush();
expect(event.defaultPrevented).toBe(false);
}));
});
describe('a11y', () => {
it('should apply `ariaLabel` and `ariaDesciption` to the primary gridcell', () => {
fixture.componentInstance.ariaLabel = 'chip name';
fixture.componentInstance.ariaDescription = 'chip description';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const primaryGridCell = (fixture.nativeElement as HTMLElement).querySelector(
'[role="gridcell"].mdc-evolution-chip__cell--primary.mat-mdc-chip-action',
);
expect(primaryGridCell)
.withContext('expected to find the grid cell for the primary chip action')
.toBeTruthy();
expect(primaryGridCell!.getAttribute('aria-label')).toMatch(/chip name/i);
const primaryGridCellDescribedBy = primaryGridCell!.getAttribute('aria-describedby');
expect(primaryGridCellDescribedBy)
.withContext('expected primary grid cell to have a non-empty aria-describedby attribute')
.toBeTruthy();
const primaryGridCellDescriptions = Array.from(
(fixture.nativeElement as HTMLElement).querySelectorAll(
primaryGridCellDescribedBy!
.split(/\s+/g)
.map(x => `#${x}`)
.join(','),
),
);
const primaryGridCellDescription = primaryGridCellDescriptions
.map(x => x.textContent?.trim())
.join(' ')
.trim();
expect(primaryGridCellDescription).toMatch(/chip description/i);
});
});
});
});
@Component({
template: `
<mat-chip-grid #chipGrid>
@if (shouldShow) {
<div>
<mat-chip-row [removable]="removable"
[color]="color" [disabled]="disabled" [editable]="editable"
(destroyed)="chipDestroy($event)"
(removed)="chipRemove($event)" (edited)="chipEdit($event)"
[aria-label]="ariaLabel" [aria-description]="ariaDescription">
{{name}}
<button matChipRemove>x</button>
@if (useCustomEditInput) {
<span class="projected-edit-input" matChipEditInput></span>
}
</mat-chip-row>
<input matInput [matChipInputFor]="chipGrid" #chipInput>
</div>
}
</mat-chip-grid>`,
standalone: true,
imports: [MatChipsModule],
})
class SingleChip {
@ViewChild(MatChipGrid) chipList: MatChipGrid;
@ViewChild('chipInput') chipInput: ElementRef;
disabled: boolean = false;
name: string = 'Test';
color: string = 'primary';
removable: boolean = true;
shouldShow: boolean = true;
editable: boolean = false;
useCustomEditInput: boolean = true;
ariaLabel: string | null = null;
ariaDescription: string | null = null;
chipDestroy: (event?: MatChipEvent) => void = () => {};
chipRemove: (event?: MatChipEvent) => void = () => {};
chipEdit: (event?: MatChipEditedEvent) => void = () => {};
} | {
"end_byte": 15643,
"start_byte": 7932,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-row.spec.ts"
} |
components/src/material/chips/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/chips/index.ts"
} |
components/src/material/chips/chip.spec.ts_0_6165 | import {Directionality} from '@angular/cdk/bidi';
import {Component, DebugElement, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {Subject} from 'rxjs';
import {MatChip, MatChipEvent, MatChipSet, MatChipsModule} from './index';
describe('MatChip', () => {
let fixture: ComponentFixture<any>;
let chipDebugElement: DebugElement;
let chipNativeElement: HTMLElement;
let chipInstance: MatChip;
let dir = 'ltr';
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
MatChipsModule,
BasicChip,
SingleChip,
BasicChipWithStaticTabindex,
BasicChipWithBoundTabindex,
],
providers: [
{
provide: Directionality,
useFactory: () => ({
value: dir,
change: new Subject(),
}),
},
],
});
}));
describe('MatBasicChip', () => {
it('adds a class to indicate that it is a basic chip', () => {
fixture = TestBed.createComponent(BasicChip);
fixture.detectChanges();
const chip = fixture.nativeElement.querySelector('mat-basic-chip');
expect(chip.classList).toContain('mat-mdc-basic-chip');
});
it('should be able to set a static tabindex', () => {
fixture = TestBed.createComponent(BasicChipWithStaticTabindex);
fixture.detectChanges();
const chip = fixture.nativeElement.querySelector('mat-basic-chip');
expect(chip.getAttribute('tabindex')).toBe('3');
});
it('should be able to set a dynamic tabindex', () => {
fixture = TestBed.createComponent(BasicChipWithBoundTabindex);
fixture.detectChanges();
const chip = fixture.nativeElement.querySelector('mat-basic-chip');
expect(chip.getAttribute('tabindex')).toBe('12');
fixture.componentInstance.tabindex = 15;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chip.getAttribute('tabindex')).toBe('15');
});
});
describe('MatChip', () => {
let testComponent: SingleChip;
let primaryAction: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(SingleChip);
fixture.detectChanges();
chipDebugElement = fixture.debugElement.query(By.directive(MatChip))!;
chipNativeElement = chipDebugElement.nativeElement;
chipInstance = chipDebugElement.injector.get<MatChip>(MatChip);
testComponent = fixture.debugElement.componentInstance;
primaryAction = chipNativeElement.querySelector('.mdc-evolution-chip__action--primary')!;
});
it('adds the `mat-chip` class', () => {
expect(chipNativeElement.classList).toContain('mat-mdc-chip');
});
it('does not add the `mat-basic-chip` class', () => {
expect(chipNativeElement.classList).not.toContain('mat-mdc-basic-chip');
});
it('emits destroy on destruction', () => {
spyOn(testComponent, 'chipDestroy').and.callThrough();
// Force a destroy callback
testComponent.shouldShow = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(testComponent.chipDestroy).toHaveBeenCalledTimes(1);
});
it('allows color customization', () => {
expect(chipNativeElement.classList).toContain('mat-primary');
testComponent.color = 'warn';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipNativeElement.classList).not.toContain('mat-primary');
expect(chipNativeElement.classList).toContain('mat-warn');
});
it('allows removal', () => {
spyOn(testComponent, 'chipRemove');
chipInstance.remove();
fixture.detectChanges();
expect(testComponent.chipRemove).toHaveBeenCalledWith({chip: chipInstance});
});
it('should make disabled chips non-focusable', () => {
testComponent.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(primaryAction.hasAttribute('tabindex')).toBe(false);
});
it('should return the chip text if value is undefined', () => {
expect(chipInstance.value.trim()).toBe(fixture.componentInstance.name);
});
it('should return the chip value if defined', () => {
fixture.componentInstance.value = 123;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipInstance.value).toBe(123);
});
it('should return the chip value if set to null', () => {
fixture.componentInstance.value = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(chipInstance.value).toBeNull();
});
});
});
@Component({
template: `
<mat-chip-set>
@if (shouldShow) {
<div>
<mat-chip [removable]="removable"
[color]="color" [disabled]="disabled"
(destroyed)="chipDestroy($event)"
(removed)="chipRemove($event)" [value]="value" [disableRipple]="rippleDisabled">
{{name}}
</mat-chip>
</div>
}
</mat-chip-set>`,
standalone: true,
imports: [MatChipsModule],
})
class SingleChip {
@ViewChild(MatChipSet) chipList: MatChipSet;
disabled: boolean = false;
name: string = 'Test';
color: string = 'primary';
removable: boolean = true;
shouldShow: boolean = true;
value: any;
rippleDisabled: boolean = false;
chipDestroy: (event?: MatChipEvent) => void = () => {};
chipRemove: (event?: MatChipEvent) => void = () => {};
}
@Component({
template: `<mat-basic-chip>Hello</mat-basic-chip>`,
standalone: true,
imports: [MatChipsModule],
})
class BasicChip {}
@Component({
template: `<mat-basic-chip role="button" tabindex="3">Hello</mat-basic-chip>`,
standalone: true,
imports: [MatChipsModule],
})
class BasicChipWithStaticTabindex {}
@Component({
template: `<mat-basic-chip role="button" [tabIndex]="tabindex">Hello</mat-basic-chip>`,
standalone: true,
imports: [MatChipsModule],
})
class BasicChipWithBoundTabindex {
tabindex = 12;
}
| {
"end_byte": 6165,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip.spec.ts"
} |
components/src/material/chips/chip-remove.spec.ts_0_4290 | import {ENTER, SPACE} from '@angular/cdk/keycodes';
import {dispatchKeyboardEvent, dispatchMouseEvent} from '@angular/cdk/testing/private';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, waitForAsync} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {MatChip, MatChipsModule} from './index';
describe('Chip Remove', () => {
let fixture: ComponentFixture<TestChip>;
let testChip: TestChip;
let chipNativeElement: HTMLElement;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, TestChip],
});
}));
beforeEach(waitForAsync(() => {
fixture = TestBed.createComponent(TestChip);
testChip = fixture.debugElement.componentInstance;
fixture.detectChanges();
const chipDebugElement = fixture.debugElement.query(By.directive(MatChip))!;
chipNativeElement = chipDebugElement.nativeElement;
}));
describe('basic behavior', () => {
it('should apply a CSS class to the remove icon', fakeAsync(() => {
const buttonElement = chipNativeElement.querySelector('.mdc-evolution-chip__icon--trailing')!;
expect(buttonElement.classList).toContain('mat-mdc-chip-remove');
}));
it('should ensure that the button cannot submit its parent form', fakeAsync(() => {
const buttonElement = chipNativeElement.querySelector('button')!;
expect(buttonElement.getAttribute('type')).toBe('button');
}));
it('should not set the `type` attribute on non-button elements', fakeAsync(() => {
const buttonElement = chipNativeElement.querySelector('span.mat-mdc-chip-remove')!;
expect(buttonElement.hasAttribute('type')).toBe(false);
}));
it('should emit (removed) event when exit animation is complete', fakeAsync(() => {
testChip.removable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
chipNativeElement.querySelector('button')!.click();
fixture.detectChanges();
flush();
expect(testChip.didRemove).toHaveBeenCalled();
}));
it('should not make the element aria-hidden when it is focusable', fakeAsync(() => {
const buttonElement = chipNativeElement.querySelector('button')!;
expect(buttonElement.getAttribute('tabindex')).toBe('-1');
expect(buttonElement.hasAttribute('aria-hidden')).toBe(false);
}));
it('should prevent the default SPACE action', fakeAsync(() => {
const buttonElement = chipNativeElement.querySelector('button')!;
testChip.removable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const event = dispatchKeyboardEvent(buttonElement, 'keydown', SPACE);
fixture.detectChanges();
flush();
expect(event.defaultPrevented).toBe(true);
}));
it('should prevent the default ENTER action', fakeAsync(() => {
const buttonElement = chipNativeElement.querySelector('button')!;
testChip.removable = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const event = dispatchKeyboardEvent(buttonElement, 'keydown', ENTER);
fixture.detectChanges();
flush();
expect(event.defaultPrevented).toBe(true);
}));
it('should have a focus indicator', fakeAsync(() => {
const buttonElement = chipNativeElement.querySelector('.mdc-evolution-chip__icon--trailing')!;
expect(buttonElement.classList.contains('mat-focus-indicator')).toBe(true);
}));
it('should prevent the default click action', fakeAsync(() => {
const buttonElement = chipNativeElement.querySelector('button')!;
const event = dispatchMouseEvent(buttonElement, 'click');
fixture.detectChanges();
flush();
expect(event.defaultPrevented).toBe(true);
}));
});
});
@Component({
template: `
<mat-chip-set>
<mat-chip
[removable]="removable"
[disabled]="disabled"
(removed)="didRemove()">
<button matChipRemove></button>
<span matChipRemove></span>
</mat-chip>
</mat-chip-set>
`,
standalone: true,
imports: [MatChipsModule],
})
class TestChip {
removable: boolean;
disabled = false;
didRemove = jasmine.createSpy('didRemove spy');
}
| {
"end_byte": 4290,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-remove.spec.ts"
} |
components/src/material/chips/chip-set.ts_0_1349 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {FocusKeyManager} from '@angular/cdk/a11y';
import {Directionality} from '@angular/cdk/bidi';
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
Input,
OnDestroy,
QueryList,
ViewEncapsulation,
booleanAttribute,
numberAttribute,
inject,
} from '@angular/core';
import {Observable, Subject, merge} from 'rxjs';
import {startWith, switchMap, takeUntil} from 'rxjs/operators';
import {MatChip, MatChipEvent} from './chip';
import {MatChipAction} from './chip-action';
/**
* Basic container component for the MatChip component.
*
* Extended by MatChipListbox and MatChipGrid for different interaction patterns.
*/
@Component({
selector: 'mat-chip-set',
template: `
<div class="mdc-evolution-chip-set__chips" role="presentation">
<ng-content></ng-content>
</div>
`,
styleUrl: 'chip-set.css',
host: {
'class': 'mat-mdc-chip-set mdc-evolution-chip-set',
'(keydown)': '_handleKeydown($event)',
'[attr.role]': 'role',
},
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export | {
"end_byte": 1349,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-set.ts"
} |
components/src/material/chips/chip-set.ts_1350_9502 | class MatChipSet implements AfterViewInit, OnDestroy {
protected _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
protected _changeDetectorRef = inject(ChangeDetectorRef);
private _dir = inject(Directionality, {optional: true});
/** Index of the last destroyed chip that had focus. */
private _lastDestroyedFocusedChipIndex: number | null = null;
/** Used to manage focus within the chip list. */
protected _keyManager: FocusKeyManager<MatChipAction>;
/** Subject that emits when the component has been destroyed. */
protected _destroyed = new Subject<void>();
/** Role to use if it hasn't been overwritten by the user. */
protected _defaultRole = 'presentation';
/** Combined stream of all of the child chips' focus events. */
get chipFocusChanges(): Observable<MatChipEvent> {
return this._getChipStream(chip => chip._onFocus);
}
/** Combined stream of all of the child chips' destroy events. */
get chipDestroyedChanges(): Observable<MatChipEvent> {
return this._getChipStream(chip => chip.destroyed);
}
/** Combined stream of all of the child chips' remove events. */
get chipRemovedChanges(): Observable<MatChipEvent> {
return this._getChipStream(chip => chip.removed);
}
/** Whether the chip set is disabled. */
@Input({transform: booleanAttribute})
get disabled(): boolean {
return this._disabled;
}
set disabled(value: boolean) {
this._disabled = value;
this._syncChipsState();
}
protected _disabled: boolean = false;
/** Whether the chip list contains chips or not. */
get empty(): boolean {
return !this._chips || this._chips.length === 0;
}
/** The ARIA role applied to the chip set. */
@Input()
get role(): string | null {
if (this._explicitRole) {
return this._explicitRole;
}
return this.empty ? null : this._defaultRole;
}
/** Tabindex of the chip set. */
@Input({
transform: (value: unknown) => (value == null ? 0 : numberAttribute(value)),
})
tabIndex: number = 0;
set role(value: string | null) {
this._explicitRole = value;
}
private _explicitRole: string | null = null;
/** Whether any of the chips inside of this chip-set has focus. */
get focused(): boolean {
return this._hasFocusedChip();
}
/** The chips that are part of this chip set. */
@ContentChildren(MatChip, {
// We need to use `descendants: true`, because Ivy will no longer match
// indirect descendants if it's left as false.
descendants: true,
})
_chips: QueryList<MatChip>;
/** Flat list of all the actions contained within the chips. */
_chipActions = new QueryList<MatChipAction>();
constructor(...args: unknown[]);
constructor() {}
ngAfterViewInit() {
this._setUpFocusManagement();
this._trackChipSetChanges();
this._trackDestroyedFocusedChip();
}
ngOnDestroy() {
this._keyManager?.destroy();
this._chipActions.destroy();
this._destroyed.next();
this._destroyed.complete();
}
/** Checks whether any of the chips is focused. */
protected _hasFocusedChip() {
return this._chips && this._chips.some(chip => chip._hasFocus());
}
/** Syncs the chip-set's state with the individual chips. */
protected _syncChipsState() {
this._chips?.forEach(chip => {
chip._chipListDisabled = this._disabled;
chip._changeDetectorRef.markForCheck();
});
}
/** Dummy method for subclasses to override. Base chip set cannot be focused. */
focus() {}
/** Handles keyboard events on the chip set. */
_handleKeydown(event: KeyboardEvent) {
if (this._originatesFromChip(event)) {
this._keyManager.onKeydown(event);
}
}
/**
* Utility to ensure all indexes are valid.
*
* @param index The index to be checked.
* @returns True if the index is valid for our list of chips.
*/
protected _isValidIndex(index: number): boolean {
return index >= 0 && index < this._chips.length;
}
/**
* Removes the `tabindex` from the chip set and resets it back afterwards, allowing the
* user to tab out of it. This prevents the set from capturing focus and redirecting
* it back to the first chip, creating a focus trap, if it user tries to tab away.
*/
protected _allowFocusEscape() {
const previous = this._elementRef.nativeElement.tabIndex;
if (previous !== -1) {
// Set the tabindex directly on the element, instead of going through
// the data binding, because we aren't guaranteed that change detection
// will run quickly enough to allow focus to escape.
this._elementRef.nativeElement.tabIndex = -1;
// Note that this needs to be a `setTimeout`, because a `Promise.resolve`
// doesn't allow enough time for the focus to escape.
setTimeout(() => (this._elementRef.nativeElement.tabIndex = previous));
}
}
/**
* Gets a stream of events from all the chips within the set.
* The stream will automatically incorporate any newly-added chips.
*/
protected _getChipStream<T, C extends MatChip = MatChip>(
mappingFunction: (chip: C) => Observable<T>,
): Observable<T> {
return this._chips.changes.pipe(
startWith(null),
switchMap(() => merge(...(this._chips as QueryList<C>).map(mappingFunction))),
);
}
/** Checks whether an event comes from inside a chip element. */
protected _originatesFromChip(event: Event): boolean {
let currentElement = event.target as HTMLElement | null;
while (currentElement && currentElement !== this._elementRef.nativeElement) {
if (currentElement.classList.contains('mat-mdc-chip')) {
return true;
}
currentElement = currentElement.parentElement;
}
return false;
}
/** Sets up the chip set's focus management logic. */
private _setUpFocusManagement() {
// Create a flat `QueryList` containing the actions of all of the chips.
// This allows us to navigate both within the chip and move to the next/previous
// one using the existing `ListKeyManager`.
this._chips.changes.pipe(startWith(this._chips)).subscribe((chips: QueryList<MatChip>) => {
const actions: MatChipAction[] = [];
chips.forEach(chip => chip._getActions().forEach(action => actions.push(action)));
this._chipActions.reset(actions);
this._chipActions.notifyOnChanges();
});
this._keyManager = new FocusKeyManager(this._chipActions)
.withVerticalOrientation()
.withHorizontalOrientation(this._dir ? this._dir.value : 'ltr')
.withHomeAndEnd()
.skipPredicate(action => this._skipPredicate(action));
// Keep the manager active index in sync so that navigation picks
// up from the current chip if the user clicks into the list directly.
this.chipFocusChanges.pipe(takeUntil(this._destroyed)).subscribe(({chip}) => {
const action = chip._getSourceAction(document.activeElement as Element);
if (action) {
this._keyManager.updateActiveItem(action);
}
});
this._dir?.change
.pipe(takeUntil(this._destroyed))
.subscribe(direction => this._keyManager.withHorizontalOrientation(direction));
}
/**
* Determines if key manager should avoid putting a given chip action in the tab index. Skip
* non-interactive and disabled actions since the user can't do anything with them.
*/
protected _skipPredicate(action: MatChipAction): boolean {
// Skip chips that the user cannot interact with. `mat-chip-set` does not permit focusing disabled
// chips.
return !action.isInteractive || action.disabled;
}
/** Listens to changes in the chip set and syncs up the state of the individual chips. */
private _trackChipSetChanges() {
this._chips.changes.pipe(startWith(null), takeUntil(this._destroyed)).subscribe(() => {
if (this.disabled) {
// Since this happens after the content has been
// checked, we need to defer it to the next tick.
Promise.resolve().then(() => this._syncChipsState());
}
this._redirectDestroyedChipFocus();
});
}
/** Starts tracking the destroyed chips in order to capture the focused one. */ | {
"end_byte": 9502,
"start_byte": 1350,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-set.ts"
} |
components/src/material/chips/chip-set.ts_9505_11083 | private _trackDestroyedFocusedChip() {
this.chipDestroyedChanges.pipe(takeUntil(this._destroyed)).subscribe((event: MatChipEvent) => {
const chipArray = this._chips.toArray();
const chipIndex = chipArray.indexOf(event.chip);
// If the focused chip is destroyed, save its index so that we can move focus to the next
// chip. We only save the index here, rather than move the focus immediately, because we want
// to wait until the chip is removed from the chip list before focusing the next one. This
// allows us to keep focus on the same index if the chip gets swapped out.
if (this._isValidIndex(chipIndex) && event.chip._hasFocus()) {
this._lastDestroyedFocusedChipIndex = chipIndex;
}
});
}
/**
* Finds the next appropriate chip to move focus to,
* if the currently-focused chip is destroyed.
*/
private _redirectDestroyedChipFocus() {
if (this._lastDestroyedFocusedChipIndex == null) {
return;
}
if (this._chips.length) {
const newIndex = Math.min(this._lastDestroyedFocusedChipIndex, this._chips.length - 1);
const chipToFocus = this._chips.toArray()[newIndex];
if (chipToFocus.disabled) {
// If we're down to one disabled chip, move focus back to the set.
if (this._chips.length === 1) {
this.focus();
} else {
this._keyManager.setPreviousItemActive();
}
} else {
chipToFocus.focus();
}
} else {
this.focus();
}
this._lastDestroyedFocusedChipIndex = null;
}
} | {
"end_byte": 11083,
"start_byte": 9505,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-set.ts"
} |
components/src/material/chips/chip-row.ts_0_6098 | /**
* @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 {ENTER} from '@angular/cdk/keycodes';
import {
AfterViewInit,
ChangeDetectionStrategy,
Component,
ContentChild,
EventEmitter,
Input,
Output,
ViewChild,
ViewEncapsulation,
afterNextRender,
} from '@angular/core';
import {takeUntil} from 'rxjs/operators';
import {MatChip, MatChipEvent} from './chip';
import {MatChipAction} from './chip-action';
import {MatChipEditInput} from './chip-edit-input';
import {MAT_CHIP} from './tokens';
/** Represents an event fired on an individual `mat-chip` when it is edited. */
export interface MatChipEditedEvent extends MatChipEvent {
/** The final edit value. */
value: string;
}
/**
* An extension of the MatChip component used with MatChipGrid and
* the matChipInputFor directive.
*/
@Component({
selector: 'mat-chip-row, [mat-chip-row], mat-basic-chip-row, [mat-basic-chip-row]',
templateUrl: 'chip-row.html',
styleUrl: 'chip.css',
host: {
'class': 'mat-mdc-chip mat-mdc-chip-row mdc-evolution-chip',
'[class.mat-mdc-chip-with-avatar]': 'leadingIcon',
'[class.mat-mdc-chip-disabled]': 'disabled',
'[class.mat-mdc-chip-editing]': '_isEditing',
'[class.mat-mdc-chip-editable]': 'editable',
'[class.mdc-evolution-chip--disabled]': 'disabled',
'[class.mdc-evolution-chip--with-trailing-action]': '_hasTrailingIcon()',
'[class.mdc-evolution-chip--with-primary-graphic]': 'leadingIcon',
'[class.mdc-evolution-chip--with-primary-icon]': 'leadingIcon',
'[class.mdc-evolution-chip--with-avatar]': 'leadingIcon',
'[class.mat-mdc-chip-highlighted]': 'highlighted',
'[class.mat-mdc-chip-with-trailing-icon]': '_hasTrailingIcon()',
'[id]': 'id',
// Has to have a negative tabindex in order to capture
// focus and redirect it to the primary action.
'[attr.tabindex]': 'disabled ? null : -1',
'[attr.aria-label]': 'null',
'[attr.aria-description]': 'null',
'[attr.role]': 'role',
'(focus)': '_handleFocus($event)',
'(dblclick)': '_handleDoubleclick($event)',
},
providers: [
{provide: MatChip, useExisting: MatChipRow},
{provide: MAT_CHIP, useExisting: MatChipRow},
],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [MatChipAction, MatChipEditInput],
})
export class MatChipRow extends MatChip implements AfterViewInit {
protected override basicChipAttrName = 'mat-basic-chip-row';
/**
* The editing action has to be triggered in a timeout. While we're waiting on it, a blur
* event might occur which will interrupt the editing. This flag is used to avoid interruptions
* while the editing action is being initialized.
*/
private _editStartPending = false;
@Input() editable: boolean = false;
/** Emitted when the chip is edited. */
@Output() readonly edited: EventEmitter<MatChipEditedEvent> =
new EventEmitter<MatChipEditedEvent>();
/** The default chip edit input that is used if none is projected into this chip row. */
@ViewChild(MatChipEditInput) defaultEditInput?: MatChipEditInput;
/** The projected chip edit input. */
@ContentChild(MatChipEditInput) contentEditInput?: MatChipEditInput;
_isEditing = false;
constructor(...args: unknown[]);
constructor() {
super();
this.role = 'row';
this._onBlur.pipe(takeUntil(this.destroyed)).subscribe(() => {
if (this._isEditing && !this._editStartPending) {
this._onEditFinish();
}
});
}
override _hasTrailingIcon() {
// The trailing icon is hidden while editing.
return !this._isEditing && super._hasTrailingIcon();
}
/** Sends focus to the first gridcell when the user clicks anywhere inside the chip. */
_handleFocus() {
if (!this._isEditing && !this.disabled) {
this.focus();
}
}
override _handleKeydown(event: KeyboardEvent): void {
if (event.keyCode === ENTER && !this.disabled) {
if (this._isEditing) {
event.preventDefault();
this._onEditFinish();
} else if (this.editable) {
this._startEditing(event);
}
} else if (this._isEditing) {
// Stop the event from reaching the chip set in order to avoid navigating.
event.stopPropagation();
} else {
super._handleKeydown(event);
}
}
_handleDoubleclick(event: MouseEvent) {
if (!this.disabled && this.editable) {
this._startEditing(event);
}
}
private _startEditing(event: Event) {
if (
!this.primaryAction ||
(this.removeIcon && this._getSourceAction(event.target as Node) === this.removeIcon)
) {
return;
}
// The value depends on the DOM so we need to extract it before we flip the flag.
const value = this.value;
this._isEditing = this._editStartPending = true;
// Defer initializing the input until after it has been added to the DOM.
afterNextRender(
() => {
this._getEditInput().initialize(value);
this._editStartPending = false;
},
{injector: this._injector},
);
}
private _onEditFinish() {
this._isEditing = this._editStartPending = false;
this.edited.emit({chip: this, value: this._getEditInput().getValue()});
// If the edit input is still focused or focus was returned to the body after it was destroyed,
// return focus to the chip contents.
if (
this._document.activeElement === this._getEditInput().getNativeElement() ||
this._document.activeElement === this._document.body
) {
this.primaryAction.focus();
}
}
override _isRippleDisabled(): boolean {
return super._isRippleDisabled() || this._isEditing;
}
/**
* Gets the projected chip edit input, or the default input if none is projected in. One of these
* two values is guaranteed to be defined.
*/
private _getEditInput(): MatChipEditInput {
return this.contentEditInput || this.defaultEditInput!;
}
}
| {
"end_byte": 6098,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/chip-row.ts"
} |
components/src/material/chips/testing/chip-grid-harness.ts_0_2300 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
} from '@angular/cdk/testing';
import {
ChipGridHarnessFilters,
ChipInputHarnessFilters,
ChipRowHarnessFilters,
} from './chip-harness-filters';
import {MatChipInputHarness} from './chip-input-harness';
import {MatChipRowHarness} from './chip-row-harness';
/** Harness for interacting with a mat-chip-grid in tests. */
export class MatChipGridHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-chip-grid';
/**
* Gets a `HarnessPredicate` that can be used to search for a chip grid with specific attributes.
* @param options Options for filtering which chip grid instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatChipGridHarness>(
this: ComponentHarnessConstructor<T>,
options: ChipGridHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options).addOption(
'disabled',
options.disabled,
async (harness, disabled) => {
return (await harness.isDisabled()) === disabled;
},
);
}
/** Gets whether the chip grid is disabled. */
async isDisabled(): Promise<boolean> {
return (await (await this.host()).getAttribute('aria-disabled')) === 'true';
}
/** Gets whether the chip grid is required. */
async isRequired(): Promise<boolean> {
return await (await this.host()).hasClass('mat-mdc-chip-list-required');
}
/** Gets whether the chip grid is invalid. */
async isInvalid(): Promise<boolean> {
return (await (await this.host()).getAttribute('aria-invalid')) === 'true';
}
/** Gets promise of the harnesses for the chip rows. */
getRows(filter: ChipRowHarnessFilters = {}): Promise<MatChipRowHarness[]> {
return this.locatorForAll(MatChipRowHarness.with(filter))();
}
/** Gets promise of the chip text input harness. */
getInput(filter: ChipInputHarnessFilters = {}): Promise<MatChipInputHarness | null> {
return this.locatorFor(MatChipInputHarness.with(filter))();
}
}
| {
"end_byte": 2300,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-grid-harness.ts"
} |
components/src/material/chips/testing/chip-input-harness.spec.ts_0_3569 | import {COMMA} from '@angular/cdk/keycodes';
import {HarnessLoader, TestKey} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatChipsModule} from '../index';
import {MatChipInputHarness} from './chip-input-harness';
describe('MatChipInputHarness', () => {
let fixture: ComponentFixture<ChipInputHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, ChipInputHarnessTest],
});
fixture = TestBed.createComponent(ChipInputHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should get correct number of chip input harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatChipInputHarness);
expect(harnesses.length).toBe(2);
});
it('should load chip inputs with disabled state match', async () => {
const enabledChips = await loader.getAllHarnesses(MatChipInputHarness.with({disabled: false}));
const disabledChips = await loader.getAllHarnesses(MatChipInputHarness.with({disabled: true}));
expect(enabledChips.length).toBe(1);
expect(disabledChips.length).toBe(1);
});
it('should get the disabled state', async () => {
const harnesses = await loader.getAllHarnesses(MatChipInputHarness);
expect(await harnesses[0].isDisabled()).toBe(false);
expect(await harnesses[1].isDisabled()).toBe(true);
});
it('should get whether the input is required', async () => {
const harness = await loader.getHarness(MatChipInputHarness);
expect(await harness.isRequired()).toBe(false);
fixture.componentInstance.required = true;
fixture.changeDetectorRef.markForCheck();
expect(await harness.isRequired()).toBe(true);
});
it('should get whether the input placeholder', async () => {
const harness = await loader.getHarness(MatChipInputHarness);
expect(await harness.getPlaceholder()).toBe('Placeholder');
});
it('should get and set the input value', async () => {
const harness = await loader.getHarness(MatChipInputHarness);
expect(await harness.getValue()).toBe('');
await harness.setValue('value');
expect(await harness.getValue()).toBe('value');
});
it('should control the input focus state', async () => {
const harness = await loader.getHarness(MatChipInputHarness);
expect(await harness.isFocused()).toBe(false);
await harness.focus();
expect(await harness.isFocused()).toBe(true);
await harness.blur();
expect(await harness.isFocused()).toBe(false);
});
it('should be able to trigger a separator key', async () => {
const input = await loader.getHarness(MatChipInputHarness);
await input.setValue('Hello');
await input.sendSeparatorKey(TestKey.COMMA);
expect(fixture.componentInstance.add).toHaveBeenCalled();
});
});
@Component({
template: `
<mat-chip-grid #grid1>
<input
[matChipInputFor]="grid1"
[required]="required"
placeholder="Placeholder"
(matChipInputTokenEnd)="add()"
[matChipInputSeparatorKeyCodes]="separatorKeyCodes"/>
</mat-chip-grid>
<mat-chip-grid #grid2>
<input [matChipInputFor]="grid2" disabled />
</mat-chip-grid>
`,
standalone: true,
imports: [MatChipsModule],
})
class ChipInputHarnessTest {
required = false;
add = jasmine.createSpy('add spy');
separatorKeyCodes = [COMMA];
}
| {
"end_byte": 3569,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-input-harness.spec.ts"
} |
components/src/material/chips/testing/chip-option-harness.ts_0_2024 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentHarnessConstructor, HarnessPredicate} from '@angular/cdk/testing';
import {MatChipHarness} from './chip-harness';
import {ChipOptionHarnessFilters} from './chip-harness-filters';
/** Harness for interacting with a mat-chip-option in tests. */
export class MatChipOptionHarness extends MatChipHarness {
static override hostSelector = '.mat-mdc-chip-option';
/**
* Gets a `HarnessPredicate` that can be used to search for a chip option with specific
* attributes.
* @param options Options for narrowing the search.
* @return a `HarnessPredicate` configured with the given options.
*/
static override with<T extends MatChipHarness>(
this: ComponentHarnessConstructor<T>,
options: ChipOptionHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(MatChipOptionHarness, options)
.addOption('text', options.text, (harness, label) =>
HarnessPredicate.stringMatches(harness.getText(), label),
)
.addOption(
'selected',
options.selected,
async (harness, selected) => (await harness.isSelected()) === selected,
) as unknown as HarnessPredicate<T>;
}
/** Whether the chip is selected. */
async isSelected(): Promise<boolean> {
return (await this.host()).hasClass('mat-mdc-chip-selected');
}
/** Selects the given chip. Only applies if it's selectable. */
async select(): Promise<void> {
if (!(await this.isSelected())) {
await this.toggle();
}
}
/** Deselects the given chip. Only applies if it's selectable. */
async deselect(): Promise<void> {
if (await this.isSelected()) {
await this.toggle();
}
}
/** Toggles the selected state of the given chip. */
async toggle(): Promise<void> {
return (await this._primaryAction()).click();
}
}
| {
"end_byte": 2024,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-option-harness.ts"
} |
components/src/material/chips/testing/chip-input-harness.ts_0_3390 | /**
* @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,
TestKey,
} from '@angular/cdk/testing';
import {ChipInputHarnessFilters} from './chip-harness-filters';
/** Harness for interacting with a grid's chip input in tests. */
export class MatChipInputHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-chip-input';
/**
* Gets a `HarnessPredicate` that can be used to search for a chip input with specific
* attributes.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatChipInputHarness>(
this: ComponentHarnessConstructor<T>,
options: ChipInputHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options)
.addOption('value', options.value, async (harness, value) => {
return (await harness.getValue()) === value;
})
.addOption('placeholder', options.placeholder, async (harness, placeholder) => {
return (await harness.getPlaceholder()) === placeholder;
})
.addOption('disabled', options.disabled, async (harness, disabled) => {
return (await harness.isDisabled()) === disabled;
});
}
/** Whether the input is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('disabled');
}
/** Whether the input is required. */
async isRequired(): Promise<boolean> {
return (await this.host()).getProperty<boolean>('required');
}
/** Gets the value of the input. */
async getValue(): Promise<string> {
// The "value" property of the native input is never undefined.
return await (await this.host()).getProperty<string>('value');
}
/** Gets the placeholder of the input. */
async getPlaceholder(): Promise<string> {
return await (await this.host()).getProperty<string>('placeholder');
}
/**
* Focuses the input and returns a promise that indicates when the
* action is complete.
*/
async focus(): Promise<void> {
return (await this.host()).focus();
}
/**
* Blurs the input and returns a promise that indicates when the
* action is complete.
*/
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the input is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
/**
* Sets the value of the input. The value will be set by simulating
* keypresses that correspond to the given value.
*/
async setValue(newValue: string): Promise<void> {
const inputEl = await this.host();
await inputEl.clear();
// We don't want to send keys for the value if the value is an empty
// string in order to clear the value. Sending keys with an empty string
// still results in unnecessary focus events.
if (newValue) {
await inputEl.sendKeys(newValue);
}
}
/** Sends a chip separator key to the input element. */
async sendSeparatorKey(key: TestKey | string): Promise<void> {
const inputEl = await this.host();
return inputEl.sendKeys(key);
}
}
| {
"end_byte": 3390,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-input-harness.ts"
} |
components/src/material/chips/testing/chip-avatar-harness.ts_0_1059 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
} from '@angular/cdk/testing';
import {ChipAvatarHarnessFilters} from './chip-harness-filters';
/** Harness for interacting with a standard Material chip avatar in tests. */
export class MatChipAvatarHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-chip-avatar';
/**
* Gets a `HarnessPredicate` that can be used to search for a chip avatar with specific
* attributes.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatChipAvatarHarness>(
this: ComponentHarnessConstructor<T>,
options: ChipAvatarHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
}
| {
"end_byte": 1059,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-avatar-harness.ts"
} |
components/src/material/chips/testing/public-api.ts_0_623 | /**
* @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 './chip-avatar-harness';
export * from './chip-harness';
export * from './chip-harness-filters';
export * from './chip-input-harness';
export * from './chip-remove-harness';
export * from './chip-option-harness';
export * from './chip-listbox-harness';
export * from './chip-grid-harness';
export * from './chip-row-harness';
export * from './chip-set-harness';
export * from './chip-edit-input-harness';
| {
"end_byte": 623,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/public-api.ts"
} |
components/src/material/chips/testing/chip-set-harness.spec.ts_0_1380 | import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatChipsModule} from '../index';
import {MatChipSetHarness} from './chip-set-harness';
describe('MatChipSetHarness', () => {
let fixture: ComponentFixture<ChipSetHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, ChipSetHarnessTest],
});
fixture = TestBed.createComponent(ChipSetHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should get correct number of set harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatChipSetHarness);
expect(harnesses.length).toBe(1);
});
it('should get correct number of chips', async () => {
const harnesses = await loader.getAllHarnesses(MatChipSetHarness);
const chips = await harnesses[0].getChips();
expect(chips.length).toBe(3);
});
});
@Component({
template: `
<mat-chip-set>
<mat-chip> Chip A </mat-chip>
<mat-chip> Chip B </mat-chip>
<mat-chip> Chip C </mat-chip>
</mat-chip-set>
`,
standalone: true,
imports: [MatChipsModule],
})
class ChipSetHarnessTest {}
| {
"end_byte": 1380,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-set-harness.spec.ts"
} |
components/src/material/chips/testing/chip-option-harness.spec.ts_0_3434 | import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatChipsModule} from '../index';
import {MatChipOptionHarness} from './chip-option-harness';
describe('MatChipOptionHarness', () => {
let fixture: ComponentFixture<ChipOptionHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, ChipOptionHarnessTest],
});
fixture = TestBed.createComponent(ChipOptionHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should get correct number of chip harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatChipOptionHarness);
expect(harnesses.length).toBe(4);
});
it('should get whether the chip is selected', async () => {
const harnesses = await loader.getAllHarnesses(MatChipOptionHarness);
expect(await harnesses[0].isSelected()).toBe(false);
expect(await harnesses[1].isSelected()).toBe(false);
expect(await harnesses[2].isSelected()).toBe(true);
});
it('should get the disabled state', async () => {
const harnesses = await loader.getAllHarnesses(MatChipOptionHarness);
expect(await harnesses[0].isDisabled()).toBe(false);
expect(await harnesses[3].isDisabled()).toBe(true);
});
it('should get the chip text content', async () => {
const harnesses = await loader.getAllHarnesses(MatChipOptionHarness);
expect(await harnesses[0].getText()).toBe('Basic Chip Option');
expect(await harnesses[1].getText()).toBe('Chip Option');
expect(await harnesses[2].getText()).toBe('Selected Chip Option');
expect(await harnesses[3].getText()).toBe('Chip Option');
});
it('should be able to select a chip', async () => {
const harness = await loader.getHarness(MatChipOptionHarness.with({selected: false}));
expect(await harness.isSelected()).toBe(false);
await harness.select();
expect(await harness.isSelected()).toBe(true);
});
it('should be able to deselect a chip', async () => {
const harness = await loader.getHarness(MatChipOptionHarness.with({selected: true}));
expect(await harness.isSelected()).toBe(true);
await harness.deselect();
expect(await harness.isSelected()).toBe(false);
});
it('should be able to toggle the selected state of a chip', async () => {
const harness = await loader.getHarness(MatChipOptionHarness.with({selected: false}));
expect(await harness.isSelected()).toBe(false);
await harness.toggle();
expect(await harness.isSelected()).toBe(true);
await harness.toggle();
expect(await harness.isSelected()).toBe(false);
});
});
@Component({
template: `
<mat-chip-listbox>
<mat-basic-chip-option> Basic Chip Option </mat-basic-chip-option>
<mat-chip-option> <mat-chip-avatar>C</mat-chip-avatar>Chip Option </mat-chip-option>
<mat-chip-option selected>
Selected Chip Option
<span matChipTrailingIcon>trailing_icon</span>
</mat-chip-option>
<mat-chip-option disabled>
Chip Option
<span matChipRemove>remove_icon</span>
</mat-chip-option>
</mat-chip-listbox>
`,
standalone: true,
imports: [MatChipsModule],
})
class ChipOptionHarnessTest {}
| {
"end_byte": 3434,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-option-harness.spec.ts"
} |
components/src/material/chips/testing/chip-row-harness.ts_0_1642 | /**
* @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 {TestKey} from '@angular/cdk/testing';
import {MatChipEditInputHarness} from './chip-edit-input-harness';
import {MatChipHarness} from './chip-harness';
import {ChipEditInputHarnessFilters} from './chip-harness-filters';
/** Harness for interacting with a mat-chip-row in tests. */
export class MatChipRowHarness extends MatChipHarness {
static override hostSelector = '.mat-mdc-chip-row';
/** Whether the chip is editable. */
async isEditable(): Promise<boolean> {
return (await this.host()).hasClass('mat-mdc-chip-editable');
}
/** Whether the chip is currently being edited. */
async isEditing(): Promise<boolean> {
return (await this.host()).hasClass('mat-mdc-chip-editing');
}
/** Sets the chip row into an editing state, if it is editable. */
async startEditing(): Promise<void> {
if (!(await this.isEditable())) {
throw new Error('Cannot begin editing a chip that is not editable.');
}
return (await this.host()).dispatchEvent('dblclick');
}
/** Stops editing the chip, if it was in the editing state. */
async finishEditing(): Promise<void> {
if (await this.isEditing()) {
await (await this.host()).sendKeys(TestKey.ENTER);
}
}
/** Gets the edit input inside the chip row. */
async getEditInput(filter: ChipEditInputHarnessFilters = {}): Promise<MatChipEditInputHarness> {
return this.locatorFor(MatChipEditInputHarness.with(filter))();
}
}
| {
"end_byte": 1642,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-row-harness.ts"
} |
components/src/material/chips/testing/chip-listbox-harness.ts_0_2884 | /**
* @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,
parallel,
} from '@angular/cdk/testing';
import {ChipListboxHarnessFilters, ChipOptionHarnessFilters} from './chip-harness-filters';
import {MatChipOptionHarness} from './chip-option-harness';
/** Harness for interacting with a mat-chip-listbox in tests. */
export class MatChipListboxHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-chip-listbox';
/**
* Gets a `HarnessPredicate` that can be used to search for a chip listbox with specific
* attributes.
* @param options Options for narrowing the search.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatChipListboxHarness>(
this: ComponentHarnessConstructor<T>,
options: ChipListboxHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options).addOption(
'disabled',
options.disabled,
async (harness, disabled) => {
return (await harness.isDisabled()) === disabled;
},
);
}
/** Gets whether the chip listbox is disabled. */
async isDisabled(): Promise<boolean> {
return (await (await this.host()).getAttribute('aria-disabled')) === 'true';
}
/** Gets whether the chip listbox is required. */
async isRequired(): Promise<boolean> {
return (await (await this.host()).getAttribute('aria-required')) === 'true';
}
/** Gets whether the chip listbox is in multi selection mode. */
async isMultiple(): Promise<boolean> {
return (await (await this.host()).getAttribute('aria-multiselectable')) === 'true';
}
/** Gets whether the orientation of the chip list. */
async getOrientation(): Promise<'horizontal' | 'vertical'> {
const orientation = await (await this.host()).getAttribute('aria-orientation');
return orientation === 'vertical' ? 'vertical' : 'horizontal';
}
/**
* Gets the list of chips inside the chip list.
* @param filter Optionally filters which chips are included.
*/
async getChips(filter: ChipOptionHarnessFilters = {}): Promise<MatChipOptionHarness[]> {
return this.locatorForAll(MatChipOptionHarness.with(filter))();
}
/**
* Selects a chip inside the chip list.
* @param filter An optional filter to apply to the child chips.
* All the chips matching the filter will be selected.
*/
async selectChips(filter: ChipOptionHarnessFilters = {}): Promise<void> {
const chips = await this.getChips(filter);
if (!chips.length) {
throw Error(`Cannot find chip matching filter ${JSON.stringify(filter)}`);
}
await parallel(() => chips.map(chip => chip.select()));
}
}
| {
"end_byte": 2884,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-listbox-harness.ts"
} |
components/src/material/chips/testing/chip-harness-filters.ts_0_1705 | /**
* @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 ChipHarnessFilters extends BaseHarnessFilters {
/** Only find instances whose text matches the given value. */
text?: string | RegExp;
/** Only find instances which match the given disabled state. */
disabled?: boolean;
}
export interface ChipInputHarnessFilters extends BaseHarnessFilters {
/** Filters based on the value of the input. */
value?: string | RegExp;
/** Filters based on the placeholder text of the input. */
placeholder?: string | RegExp;
/** Only find instances which match the given disabled state. */
disabled?: boolean;
}
export interface ChipListboxHarnessFilters extends BaseHarnessFilters {
/** Only find instances which match the given disabled state. */
disabled?: boolean;
}
export interface ChipOptionHarnessFilters extends ChipHarnessFilters {
/** Only find chip instances whose selected state matches the given value. */
selected?: boolean;
}
export interface ChipGridHarnessFilters extends BaseHarnessFilters {
/** Only find instances which match the given disabled state. */
disabled?: boolean;
}
export interface ChipRowHarnessFilters extends ChipHarnessFilters {}
export interface ChipSetHarnessFilters extends BaseHarnessFilters {}
export interface ChipRemoveHarnessFilters extends BaseHarnessFilters {}
export interface ChipAvatarHarnessFilters extends BaseHarnessFilters {}
export interface ChipEditInputHarnessFilters extends BaseHarnessFilters {}
| {
"end_byte": 1705,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-harness-filters.ts"
} |
components/src/material/chips/testing/chip-edit-input-harness.ts_0_1582 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
} from '@angular/cdk/testing';
import {ChipEditInputHarnessFilters} from './chip-harness-filters';
/** Harness for interacting with an editable chip's input in tests. */
export class MatChipEditInputHarness extends ComponentHarness {
static hostSelector = '.mat-chip-edit-input';
/**
* Gets a `HarnessPredicate` that can be used to search for a chip edit input with specific
* attributes.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatChipEditInputHarness>(
this: ComponentHarnessConstructor<T>,
options: ChipEditInputHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
/** Sets the value of the input. */
async setValue(value: string): Promise<void> {
const host = await this.host();
// @breaking-change 16.0.0 Remove this null check once `setContenteditableValue`
// becomes a required method.
if (!host.setContenteditableValue) {
throw new Error(
'Cannot set chip edit input value, because test ' +
'element does not implement the `setContenteditableValue` method.',
);
}
return host.setContenteditableValue(value);
}
}
| {
"end_byte": 1582,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-edit-input-harness.ts"
} |
components/src/material/chips/testing/chip-harness.spec.ts_0_3691 | import {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 {MatIconModule} from '@angular/material/icon';
import {MatIconHarness} from '@angular/material/icon/testing';
import {MatChipsModule} from '../index';
import {MatChipHarness} from './chip-harness';
describe('MatChipHarness', () => {
let fixture: ComponentFixture<ChipHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, MatIconModule, ChipHarnessTest],
});
fixture = TestBed.createComponent(ChipHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should get correct number of chip harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatChipHarness);
expect(harnesses.length).toBe(5);
});
it('should get the chip text content', async () => {
const harnesses = await loader.getAllHarnesses(MatChipHarness);
expect(await harnesses[0].getText()).toBe('Basic Chip');
expect(await harnesses[1].getText()).toBe('Chip');
expect(await harnesses[2].getText()).toBe('Chip with avatar');
expect(await harnesses[3].getText()).toBe('Disabled Chip');
expect(await harnesses[4].getText()).toBe('Chip Row');
});
it('should be able to remove a chip', async () => {
const removeChipSpy = spyOn(fixture.componentInstance, 'removeChip');
const harnesses = await loader.getAllHarnesses(MatChipHarness);
await harnesses[4].remove();
expect(removeChipSpy).toHaveBeenCalledTimes(1);
});
it('should get the disabled state of a chip', async () => {
const harnesses = await loader.getAllHarnesses(MatChipHarness);
const disabledStates = await parallel(() => harnesses.map(harness => harness.isDisabled()));
expect(disabledStates).toEqual([false, false, false, true, false]);
});
it('should get the remove button of a chip', async () => {
const harness = await loader.getHarness(MatChipHarness.with({selector: '.has-remove-button'}));
expect(await harness.getRemoveButton()).toBeTruthy();
});
it('should find avatar in chip', async () => {
const chip = await loader.getHarness(
MatChipHarness.with({
selector: '.mat-mdc-chip-with-avatar',
}),
);
const avatar = await chip.getAvatar();
expect(avatar).toBeTruthy();
const avatarHost = await avatar?.host();
expect(await avatarHost?.getAttribute('aria-label')).toBe('Coronavirus');
});
it('should find icon in chip', async () => {
const chip = await loader.getHarness(
MatChipHarness.with({
selector: '.mat-mdc-chip-with-icon-avatar',
}),
);
expect(chip).toBeTruthy();
const icon = await chip.getHarness(MatIconHarness);
expect(icon).toBeTruthy();
expect(await icon.getName()).toBe('coronavirus');
});
});
@Component({
template: `
<mat-basic-chip>Basic Chip</mat-basic-chip>
<mat-chip>Chip <span matChipTrailingIcon>trailing_icon</span></mat-chip>
<mat-chip class="mat-mdc-chip-with-icon-avatar">
<mat-icon matChipAvatar aria-label="Coronavirus" aria-hidden="false">coronavirus</mat-icon>
Chip with avatar
</mat-chip>
<mat-chip
class="has-remove-button"
disabled>Disabled Chip <span matChipRemove>remove_icon</span>
</mat-chip>
<mat-chip-row (removed)="removeChip()">Chip Row</mat-chip-row>
`,
standalone: true,
imports: [MatChipsModule, MatIconModule],
})
class ChipHarnessTest {
removeChip() {}
}
| {
"end_byte": 3691,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-harness.spec.ts"
} |
components/src/material/chips/testing/chip-grid-harness.spec.ts_0_5246 | import {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 {FormControl, ReactiveFormsModule, Validators} from '@angular/forms';
import {MatChipsModule} from '../index';
import {MatChipGridHarness} from './chip-grid-harness';
describe('MatChipGridHarness', () => {
let fixture: ComponentFixture<ChipGridHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, ReactiveFormsModule, ChipGridHarnessTest],
});
fixture = TestBed.createComponent(ChipGridHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should get correct number of grid harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatChipGridHarness);
expect(harnesses.length).toBe(1);
});
it('should load chip grids with disabled state match', async () => {
let enabledChips = await loader.getAllHarnesses(MatChipGridHarness.with({disabled: false}));
let disabledChips = await loader.getAllHarnesses(MatChipGridHarness.with({disabled: true}));
expect(enabledChips.length).toBe(1);
expect(disabledChips.length).toBe(0);
fixture.componentInstance.control.disable();
enabledChips = await loader.getAllHarnesses(MatChipGridHarness.with({disabled: false}));
disabledChips = await loader.getAllHarnesses(MatChipGridHarness.with({disabled: true}));
expect(enabledChips.length).toBe(0);
expect(disabledChips.length).toBe(1);
});
it('should get correct number of rows', async () => {
const harness = await loader.getHarness(MatChipGridHarness);
const rows = await harness.getRows();
expect(rows.length).toBe(3);
});
it('should get the chip input harness', async () => {
const harness = await loader.getHarness(MatChipGridHarness);
const input = await harness.getInput();
expect(input).not.toBe(null);
});
it('should get whether the grid is disabled', async () => {
const harness = await loader.getHarness(MatChipGridHarness);
expect(await harness.isDisabled()).toBe(false);
fixture.componentInstance.control.disable();
expect(await harness.isDisabled()).toBe(true);
});
it('should get whether the grid is required', async () => {
const harness = await loader.getHarness(MatChipGridHarness);
expect(await harness.isRequired()).toBe(false);
fixture.componentInstance.required = true;
fixture.changeDetectorRef.markForCheck();
expect(await harness.isRequired()).toBe(true);
});
it('should get whether the grid is invalid', async () => {
const harness = await loader.getHarness(MatChipGridHarness);
expect(await harness.isInvalid()).toBe(false);
// Mark the control as touched since the default error
// state matcher only activates after a control is touched.
fixture.componentInstance.control.markAsTouched();
fixture.componentInstance.control.setValue(null);
expect(await harness.isInvalid()).toBe(true);
});
it('should get whether a chip is editable', async () => {
const grid = await loader.getHarness(MatChipGridHarness);
const chips = await grid.getRows();
fixture.componentInstance.firstChipEditable = true;
fixture.changeDetectorRef.markForCheck();
expect(await parallel(() => chips.map(chip => chip.isEditable()))).toEqual([
true,
false,
false,
]);
});
it('should throw when trying to edit a chip that is not editable', async () => {
const grid = await loader.getHarness(MatChipGridHarness);
const chip = (await grid.getRows())[0];
let error: string | null = null;
fixture.componentInstance.firstChipEditable = false;
fixture.changeDetectorRef.markForCheck();
try {
await chip.startEditing();
} catch (e: any) {
error = e.message;
}
expect(error).toBe('Cannot begin editing a chip that is not editable.');
});
it('should be able to edit a chip row', async () => {
const grid = await loader.getHarness(MatChipGridHarness);
const chip = (await grid.getRows())[0];
fixture.componentInstance.firstChipEditable = true;
fixture.changeDetectorRef.markForCheck();
await chip.startEditing();
await (await chip.getEditInput()).setValue('new value');
await chip.finishEditing();
expect(fixture.componentInstance.editSpy).toHaveBeenCalledWith(
jasmine.objectContaining({
value: 'new value',
}),
);
});
});
@Component({
template: `
<mat-chip-grid [formControl]="control" [required]="required" #grid>
<mat-chip-row [editable]="firstChipEditable" (edited)="editSpy($event)">Chip A</mat-chip-row>
<mat-chip-row>Chip B</mat-chip-row>
<mat-chip-row>Chip C</mat-chip-row>
<input [matChipInputFor]="grid"/>
</mat-chip-grid>
`,
standalone: true,
imports: [MatChipsModule, ReactiveFormsModule],
})
class ChipGridHarnessTest {
control = new FormControl('value', [Validators.required]);
required = false;
firstChipEditable = false;
editSpy = jasmine.createSpy('editSpy');
}
| {
"end_byte": 5246,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-grid-harness.spec.ts"
} |
components/src/material/chips/testing/chip-row-harness.spec.ts_0_1584 | import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component, signal} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {MatChipsModule} from '../index';
import {MatChipRowHarness} from './chip-row-harness';
describe('MatChipRowHarness', () => {
let fixture: ComponentFixture<ChipRowHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, ChipRowHarnessTest],
});
fixture = TestBed.createComponent(ChipRowHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should get correct number of chip harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatChipRowHarness);
expect(harnesses.length).toBe(2);
});
it('should get whether the chip is editable', async () => {
const harness = await loader.getHarness(MatChipRowHarness);
expect(await harness.isEditable()).toBe(false);
fixture.componentInstance.editable.set(true);
expect(await harness.isEditable()).toBe(true);
});
});
@Component({
template: `
<mat-chip-grid #grid>
<mat-basic-chip-row [editable]="editable()"> Basic Chip Row </mat-basic-chip-row>
<mat-chip-row [editable]="editable"> Chip Row </mat-chip-row>
<input [matChipInputFor]="grid" />
</mat-chip-grid>
`,
standalone: true,
imports: [MatChipsModule],
})
class ChipRowHarnessTest {
editable = signal(false);
}
| {
"end_byte": 1584,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-row-harness.spec.ts"
} |
components/src/material/chips/testing/chip-remove-harness.ts_0_1179 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarness,
ComponentHarnessConstructor,
HarnessPredicate,
} from '@angular/cdk/testing';
import {ChipRemoveHarnessFilters} from './chip-harness-filters';
/** Harness for interacting with a standard Material chip remove button in tests. */
export class MatChipRemoveHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-chip-remove';
/**
* Gets a `HarnessPredicate` that can be used to search for a chip remove with specific
* attributes.
* @param options Options for filtering which input instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatChipRemoveHarness>(
this: ComponentHarnessConstructor<T>,
options: ChipRemoveHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
/** Clicks the remove button. */
async click(): Promise<void> {
return (await this.host()).click();
}
}
| {
"end_byte": 1179,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-remove-harness.ts"
} |
components/src/material/chips/testing/BUILD.bazel_0_824 | 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",
],
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/keycodes",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/chips",
"//src/material/icon",
"//src/material/icon/testing",
"@npm//@angular/forms",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":unit_tests_lib",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 824,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/BUILD.bazel"
} |
components/src/material/chips/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/chips/testing/index.ts"
} |
components/src/material/chips/testing/chip-set-harness.ts_0_1295 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarnessConstructor,
ComponentHarness,
HarnessPredicate,
} from '@angular/cdk/testing';
import {MatChipHarness} from './chip-harness';
import {ChipHarnessFilters, ChipSetHarnessFilters} from './chip-harness-filters';
/** Harness for interacting with a mat-chip-set in tests. */
export class MatChipSetHarness extends ComponentHarness {
static hostSelector = '.mat-mdc-chip-set';
/**
* Gets a `HarnessPredicate` that can be used to search for a chip set with specific attributes.
* @param options Options for filtering which chip set instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatChipSetHarness>(
this: ComponentHarnessConstructor<T>,
options: ChipSetHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options);
}
/** Gets promise of the harnesses for the chips. */
async getChips(filter: ChipHarnessFilters = {}): Promise<MatChipHarness[]> {
return await this.locatorForAll(MatChipHarness.with(filter))();
}
}
| {
"end_byte": 1295,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-set-harness.ts"
} |
components/src/material/chips/testing/chip-harness.ts_0_2690 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ComponentHarnessConstructor,
ContentContainerComponentHarness,
HarnessPredicate,
TestKey,
} from '@angular/cdk/testing';
import {MatChipAvatarHarness} from './chip-avatar-harness';
import {
ChipAvatarHarnessFilters,
ChipHarnessFilters,
ChipRemoveHarnessFilters,
} from './chip-harness-filters';
import {MatChipRemoveHarness} from './chip-remove-harness';
/** Harness for interacting with a mat-chip in tests. */
export class MatChipHarness extends ContentContainerComponentHarness {
protected _primaryAction = this.locatorFor('.mdc-evolution-chip__action--primary');
static hostSelector = '.mat-mdc-basic-chip, .mat-mdc-chip';
/**
* Gets a `HarnessPredicate` that can be used to search for a chip with specific attributes.
* @param options Options for narrowing the search.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatChipHarness>(
this: ComponentHarnessConstructor<T>,
options: ChipHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options)
.addOption('text', options.text, (harness, label) => {
return HarnessPredicate.stringMatches(harness.getText(), label);
})
.addOption('disabled', options.disabled, async (harness, disabled) => {
return (await harness.isDisabled()) === disabled;
});
}
/** Gets a promise for the text content the option. */
async getText(): Promise<string> {
return (await this.host()).text({
exclude: '.mat-mdc-chip-avatar, .mat-mdc-chip-trailing-icon, .mat-icon',
});
}
/** Whether the chip is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).hasClass('mat-mdc-chip-disabled');
}
/** Delete a chip from the set. */
async remove(): Promise<void> {
const hostEl = await this.host();
await hostEl.sendKeys(TestKey.DELETE);
}
/**
* Gets the remove button inside of a chip.
* @param filter Optionally filters which chips are included.
*/
async getRemoveButton(filter: ChipRemoveHarnessFilters = {}): Promise<MatChipRemoveHarness> {
return this.locatorFor(MatChipRemoveHarness.with(filter))();
}
/**
* Gets the avatar inside a chip.
* @param filter Optionally filters which avatars are included.
*/
async getAvatar(filter: ChipAvatarHarnessFilters = {}): Promise<MatChipAvatarHarness | null> {
return this.locatorForOptional(MatChipAvatarHarness.with(filter))();
}
}
| {
"end_byte": 2690,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-harness.ts"
} |
components/src/material/chips/testing/chip-listbox-harness.spec.ts_0_5386 | import {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 {MatChipsModule} from '../index';
import {MatChipListboxHarness} from './chip-listbox-harness';
describe('MatChipListboxHarness', () => {
let fixture: ComponentFixture<ChipListboxHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatChipsModule, ChipListboxHarnessTest],
});
fixture = TestBed.createComponent(ChipListboxHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should get correct number of listbox harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatChipListboxHarness);
expect(harnesses.length).toBe(1);
});
it('should get the number of options', async () => {
const harness = await loader.getHarness(MatChipListboxHarness);
expect((await harness.getChips()).length).toBe(4);
});
it('should get whether the listbox is in multi-selection mode', async () => {
const harness = await loader.getHarness(MatChipListboxHarness);
expect(await harness.isMultiple()).toBe(false);
fixture.componentInstance.isMultiple = true;
fixture.changeDetectorRef.markForCheck();
expect(await harness.isMultiple()).toBe(true);
});
it('should load chip inputs with disabled state match', async () => {
let enabledChips = await loader.getAllHarnesses(MatChipListboxHarness.with({disabled: false}));
let disabledChips = await loader.getAllHarnesses(MatChipListboxHarness.with({disabled: true}));
expect(enabledChips.length).toBe(1);
expect(disabledChips.length).toBe(0);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
enabledChips = await loader.getAllHarnesses(MatChipListboxHarness.with({disabled: false}));
disabledChips = await loader.getAllHarnesses(MatChipListboxHarness.with({disabled: true}));
});
it('should get whether the listbox is disabled', async () => {
const harness = await loader.getHarness(MatChipListboxHarness);
expect(await harness.isDisabled()).toBe(false);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
expect(await harness.isDisabled()).toBe(true);
});
it('should get whether the listbox is required', async () => {
const harness = await loader.getHarness(MatChipListboxHarness);
expect(await harness.isRequired()).toBe(false);
fixture.componentInstance.required = true;
fixture.changeDetectorRef.markForCheck();
expect(await harness.isRequired()).toBe(true);
});
it('should get selection when no options are selected', async () => {
const harness = await loader.getHarness(MatChipListboxHarness);
const selectedOptions = await harness.getChips({selected: true});
expect(selectedOptions.length).toBe(0);
});
it('should get selection in single-selection mode', async () => {
fixture.componentInstance.options[0].selected = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const harness = await loader.getHarness(MatChipListboxHarness);
const selectedOptions = await harness.getChips({selected: true});
expect(selectedOptions.length).toBe(1);
expect(await selectedOptions[0].getText()).toContain('Blue');
});
it('should get selection in multi-selection mode', async () => {
fixture.componentInstance.isMultiple = true;
fixture.componentInstance.options[0].selected = true;
fixture.componentInstance.options[1].selected = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const harness = await loader.getHarness(MatChipListboxHarness);
const selectedOptions = await harness.getChips({selected: true});
expect(selectedOptions.length).toBe(2);
expect(await selectedOptions[0].getText()).toContain('Blue');
expect(await selectedOptions[1].getText()).toContain('Green');
});
it('should be able to select specific options', async () => {
fixture.componentInstance.isMultiple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const harness = await loader.getHarness(MatChipListboxHarness);
expect(await harness.getChips({selected: true})).toEqual([]);
await harness.selectChips({text: /Blue|Yellow/});
const selectedOptions = await harness.getChips({selected: true});
const selectedText = await parallel(() => selectedOptions.map(option => option.getText()));
expect(selectedText).toEqual(['Blue', 'Yellow']);
});
});
@Component({
template: `
<mat-chip-listbox [multiple]="isMultiple" [disabled]="disabled" [required]="required">
@for (option of options; track option) {
<mat-chip-option [selected]="option.selected">
{{option.text}}
</mat-chip-option>
}
</mat-chip-listbox>
`,
standalone: true,
imports: [MatChipsModule],
})
class ChipListboxHarnessTest {
isMultiple = false;
disabled = false;
required = false;
options = [
{text: 'Blue', selected: false},
{text: 'Green', selected: false},
{text: 'Red', selected: false},
{text: 'Yellow', selected: false},
];
}
| {
"end_byte": 5386,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/chips/testing/chip-listbox-harness.spec.ts"
} |
components/src/material/input/input.md_0_4859 | `matInput` is a directive that allows native `<input>` and `<textarea>` elements to work with
[`<mat-form-field>`](https://material.angular.io/components/form-field/overview).
<!-- example(input-overview) -->
### `<input>` and `<textarea>` attributes
All of the attributes that can be used with `<input>` and `<textarea>` elements can be used
on elements inside `<mat-form-field>` as well. This includes Angular directives such as `ngModel`
and `formControl`.
The only limitation is that the `type` attribute can only be one of the values supported by
`matNativeControl`.
### Supported `<input>` types
The following [input types](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) can
be used with `matNativeControl`:
* color
* date
* datetime-local
* email
* month
* number
* password
* search
* tel
* text
* time
* url
* week
### Form field features
There are a number of `<mat-form-field>` features that can be used with any `<input matNativeControl>` or
`<textarea matNativeControl>`. These include error messages, hint text, prefix & suffix, and theming. For
additional information about these features, see the
[form field documentation](https://material.angular.io/components/form-field/overview).
### Placeholder
The placeholder is text shown when the `<mat-form-field>` label is floating but the input is empty.
It is used to give the user an additional hint about what they should type in the input. The
placeholder can be specified by setting the `placeholder` attribute on the `<input>` or `<textarea>`
element. In some cases that `<mat-form-field>` may use the placeholder as the label (see the
[form field label documentation](https://material.angular.io/components/form-field/overview#floating-label)).
### Changing when error messages are shown
The `<mat-form-field>` allows you to
[associate error messages](https://material.angular.io/components/form-field/overview#error-messages)
with your `matNativeControl`. By default, these error messages are shown when the control is invalid and
the user has interacted with (touched) the element or the parent form has been submitted. If
you wish to override this behavior (e.g. to show the error as soon as the invalid control is dirty
or when a parent form group is invalid), you can use the `errorStateMatcher` property of the
`matNativeControl`. The property takes an instance of an `ErrorStateMatcher` object. An `ErrorStateMatcher`
must implement a single method `isErrorState` which takes the `FormControl` for this `matNativeControl` as
well as the parent form and returns a boolean indicating whether errors should be shown. (`true`
indicating that they should be shown, and `false` indicating that they should not.)
<!-- example(input-error-state-matcher) -->
A global error state matcher can be specified by setting the `ErrorStateMatcher` provider. This
applies to all inputs. For convenience, `ShowOnDirtyErrorStateMatcher` is available in order to
globally cause input errors to show when the input is dirty and invalid.
```ts
@NgModule({
providers: [
{provide: ErrorStateMatcher, useClass: ShowOnDirtyErrorStateMatcher}
]
})
```
### Auto-resizing `<textarea>` elements
`<textarea>` elements can be made to automatically resize by using the
[`cdkTextareaAutosize` directive](https://material.angular.io/cdk/text-field/overview#automatically-resizing-a-textarea)
available in the CDK.
### Responding to changes in the autofill state of an `<input>`
The CDK provides
[utilities](https://material.angular.io/cdk/text-field/overview#monitoring-the-autofill-state-of-an-input)
for detecting when an input becomes autofilled and changing the appearance of the autofilled state.
### Accessibility
The `matNativeControl` directive works with native `<input>` to provide an accessible experience.
#### Aria attributes
If the containing `<mat-form-field>` has a label it will automatically be used as the `aria-label`
for the `<input>`. However, if there's no label specified in the form field, `aria-label`,
`aria-labelledby` or `<label for=...>` should be added.
#### Errors and hints
Any `mat-error` and `mat-hint` are automatically added to the input's `aria-describedby` list, and
`aria-invalid` is automatically updated based on the input's validity state.
When conveying an error, be sure to not rely solely on color. In the message itself, you can use an
icon or text such as "Error:" to indicate the message is an error message.
### Troubleshooting
#### Error: Input type "..." isn't supported by matInput
This error is thrown when you attempt to set an input's `type` property to a value that isn't
supported by the `matInput` directive. If you need to use an unsupported input type with
`<mat-form-field>` consider writing a
[custom form field control](https://material.angular.io/guide/creating-a-custom-form-field-control)
for it.
| {
"end_byte": 4859,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.md"
} |
components/src/material/input/input-value-accessor.ts_0_718 | /**
* @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, WritableSignal} from '@angular/core';
/**
* This token is used to inject the object whose value should be set into `MatInput`. If none is
* provided, the native `HTMLInputElement` is used. Directives like `MatDatepickerInput` can provide
* themselves for this token, in order to make `MatInput` delegate the getting and setting of the
* value to them.
*/
export const MAT_INPUT_VALUE_ACCESSOR = new InjectionToken<{value: any | WritableSignal<any>}>(
'MAT_INPUT_VALUE_ACCESSOR',
);
| {
"end_byte": 718,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/input-value-accessor.ts"
} |
components/src/material/input/input-errors.ts_0_367 | /**
* @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
*/
/** @docs-private */
export function getMatInputUnsupportedTypeError(type: string): Error {
return Error(`Input type "${type}" isn't supported by matInput.`);
}
| {
"end_byte": 367,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/input-errors.ts"
} |
components/src/material/input/module.ts_0_640 | /**
* @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 {TextFieldModule} from '@angular/cdk/text-field';
import {NgModule} from '@angular/core';
import {MatCommonModule} from '@angular/material/core';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInput} from './input';
@NgModule({
imports: [MatCommonModule, MatFormFieldModule, MatInput],
exports: [MatInput, MatFormFieldModule, TextFieldModule, MatCommonModule],
})
export class MatInputModule {}
| {
"end_byte": 640,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/module.ts"
} |
components/src/material/input/input.ts_0_3735 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {BooleanInput, coerceBooleanProperty} from '@angular/cdk/coercion';
import {getSupportedInputTypes, Platform} from '@angular/cdk/platform';
import {AutofillMonitor} from '@angular/cdk/text-field';
import {
AfterViewInit,
booleanAttribute,
Directive,
DoCheck,
effect,
ElementRef,
inject,
InjectionToken,
Input,
isSignal,
NgZone,
OnChanges,
OnDestroy,
WritableSignal,
} from '@angular/core';
import {FormGroupDirective, NgControl, NgForm, Validators} from '@angular/forms';
import {ErrorStateMatcher, _ErrorStateTracker} from '@angular/material/core';
import {MatFormFieldControl, MatFormField, MAT_FORM_FIELD} from '@angular/material/form-field';
import {Subject} from 'rxjs';
import {getMatInputUnsupportedTypeError} from './input-errors';
import {MAT_INPUT_VALUE_ACCESSOR} from './input-value-accessor';
// Invalid input type. Using one of these will throw an MatInputUnsupportedTypeError.
const MAT_INPUT_INVALID_TYPES = [
'button',
'checkbox',
'file',
'hidden',
'image',
'radio',
'range',
'reset',
'submit',
];
let nextUniqueId = 0;
/** Object that can be used to configure the default options for the input. */
export interface MatInputConfig {
/** Whether disabled inputs should be interactive. */
disabledInteractive?: boolean;
}
/** Injection token that can be used to provide the default options for the input. */
export const MAT_INPUT_CONFIG = new InjectionToken<MatInputConfig>('MAT_INPUT_CONFIG');
@Directive({
selector: `input[matInput], textarea[matInput], select[matNativeControl],
input[matNativeControl], textarea[matNativeControl]`,
exportAs: 'matInput',
host: {
'class': 'mat-mdc-input-element',
// The BaseMatInput parent class adds `mat-input-element`, `mat-form-field-control` and
// `mat-form-field-autofill-control` to the CSS class list, but this should not be added for
// this MDC equivalent input.
'[class.mat-input-server]': '_isServer',
'[class.mat-mdc-form-field-textarea-control]': '_isInFormField && _isTextarea',
'[class.mat-mdc-form-field-input-control]': '_isInFormField',
'[class.mat-mdc-input-disabled-interactive]': 'disabledInteractive',
'[class.mdc-text-field__input]': '_isInFormField',
'[class.mat-mdc-native-select-inline]': '_isInlineSelect()',
// Native input properties that are overwritten by Angular inputs need to be synced with
// the native input element. Otherwise property bindings for those don't work.
'[id]': 'id',
'[disabled]': 'disabled && !disabledInteractive',
'[required]': 'required',
'[attr.name]': 'name || null',
'[attr.readonly]': '_getReadonlyAttribute()',
'[attr.aria-disabled]': 'disabled && disabledInteractive ? "true" : null',
// Only mark the input as invalid for assistive technology if it has a value since the
// state usually overlaps with `aria-required` when the input is empty and can be redundant.
'[attr.aria-invalid]': '(empty && required) ? null : errorState',
'[attr.aria-required]': 'required',
// Native input properties that are overwritten by Angular inputs need to be synced with
// the native input element. Otherwise property bindings for those don't work.
'[attr.id]': 'id',
'(focus)': '_focusChanged(true)',
'(blur)': '_focusChanged(false)',
'(input)': '_onInput()',
},
providers: [{provide: MatFormFieldControl, useExisting: MatInput}],
})
export class MatInput
implements MatFormFieldControl<any>, OnChanges, OnDestroy, AfterViewInit, DoCheck | {
"end_byte": 3735,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.ts"
} |
components/src/material/input/input.ts_3736_12048 | {
protected _elementRef =
inject<ElementRef<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>>(ElementRef);
protected _platform = inject(Platform);
ngControl = inject(NgControl, {optional: true, self: true})!;
private _autofillMonitor = inject(AutofillMonitor);
private _ngZone = inject(NgZone);
protected _formField? = inject<MatFormField>(MAT_FORM_FIELD, {optional: true});
protected _uid = `mat-input-${nextUniqueId++}`;
protected _previousNativeValue: any;
private _inputValueAccessor: {value: any};
private _signalBasedValueAccessor?: {value: WritableSignal<any>};
private _previousPlaceholder: string | null;
private _errorStateTracker: _ErrorStateTracker;
private _webkitBlinkWheelListenerAttached = false;
private _config = inject(MAT_INPUT_CONFIG, {optional: true});
/** Whether the component is being rendered on the server. */
readonly _isServer: boolean;
/** Whether the component is a native html select. */
readonly _isNativeSelect: boolean;
/** Whether the component is a textarea. */
readonly _isTextarea: boolean;
/** Whether the input is inside of a form field. */
readonly _isInFormField: boolean;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
focused: boolean = false;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
readonly stateChanges: Subject<void> = new Subject<void>();
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
controlType: string = 'mat-input';
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
autofilled = false;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input()
get disabled(): boolean {
return this._disabled;
}
set disabled(value: BooleanInput) {
this._disabled = coerceBooleanProperty(value);
// Browsers may not fire the blur event if the input is disabled too quickly.
// Reset from here to ensure that the element doesn't become stuck.
if (this.focused) {
this.focused = false;
this.stateChanges.next();
}
}
protected _disabled = false;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input()
get id(): string {
return this._id;
}
set id(value: string) {
this._id = value || this._uid;
}
protected _id: string;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input() placeholder: string;
/**
* Name of the input.
* @docs-private
*/
@Input() name: string;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input()
get required(): boolean {
return this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false;
}
set required(value: BooleanInput) {
this._required = coerceBooleanProperty(value);
}
protected _required: boolean | undefined;
/** Input type of the element. */
@Input()
get type(): string {
return this._type;
}
set type(value: string) {
this._type = value || 'text';
this._validateType();
// When using Angular inputs, developers are no longer able to set the properties on the native
// input element. To ensure that bindings for `type` work, we need to sync the setter
// with the native property. Textarea elements don't support the type property or attribute.
if (!this._isTextarea && getSupportedInputTypes().has(this._type)) {
(this._elementRef.nativeElement as HTMLInputElement).type = this._type;
}
this._ensureWheelDefaultBehavior();
}
protected _type = 'text';
/** An object used to control when error messages are shown. */
@Input()
get errorStateMatcher() {
return this._errorStateTracker.matcher;
}
set errorStateMatcher(value: ErrorStateMatcher) {
this._errorStateTracker.matcher = value;
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input('aria-describedby') userAriaDescribedBy: string;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input()
get value(): string {
return this._signalBasedValueAccessor
? this._signalBasedValueAccessor.value()
: this._inputValueAccessor.value;
}
set value(value: any) {
if (value !== this.value) {
if (this._signalBasedValueAccessor) {
this._signalBasedValueAccessor.value.set(value);
} else {
this._inputValueAccessor.value = value;
}
this.stateChanges.next();
}
}
/** Whether the element is readonly. */
@Input()
get readonly(): boolean {
return this._readonly;
}
set readonly(value: BooleanInput) {
this._readonly = coerceBooleanProperty(value);
}
private _readonly = false;
/** Whether the input should remain interactive when it is disabled. */
@Input({transform: booleanAttribute})
disabledInteractive: boolean;
/** Whether the input is in an error state. */
get errorState() {
return this._errorStateTracker.errorState;
}
set errorState(value: boolean) {
this._errorStateTracker.errorState = value;
}
protected _neverEmptyInputTypes = [
'date',
'datetime',
'datetime-local',
'month',
'time',
'week',
].filter(t => getSupportedInputTypes().has(t));
constructor(...args: unknown[]);
constructor() {
const parentForm = inject(NgForm, {optional: true});
const parentFormGroup = inject(FormGroupDirective, {optional: true});
const defaultErrorStateMatcher = inject(ErrorStateMatcher);
const accessor = inject(MAT_INPUT_VALUE_ACCESSOR, {optional: true, self: true});
const element = this._elementRef.nativeElement;
const nodeName = element.nodeName.toLowerCase();
if (accessor) {
if (isSignal(accessor.value)) {
this._signalBasedValueAccessor = accessor;
} else {
this._inputValueAccessor = accessor;
}
} else {
// If no input value accessor was explicitly specified, use the element as the input value
// accessor.
this._inputValueAccessor = element;
}
this._previousNativeValue = this.value;
// Force setter to be called in case id was not specified.
this.id = this.id;
// On some versions of iOS the caret gets stuck in the wrong place when holding down the delete
// key. In order to get around this we need to "jiggle" the caret loose. Since this bug only
// exists on iOS, we only bother to install the listener on iOS.
if (this._platform.IOS) {
this._ngZone.runOutsideAngular(() => {
element.addEventListener('keyup', this._iOSKeyupListener);
});
}
this._errorStateTracker = new _ErrorStateTracker(
defaultErrorStateMatcher,
this.ngControl,
parentFormGroup,
parentForm,
this.stateChanges,
);
this._isServer = !this._platform.isBrowser;
this._isNativeSelect = nodeName === 'select';
this._isTextarea = nodeName === 'textarea';
this._isInFormField = !!this._formField;
this.disabledInteractive = this._config?.disabledInteractive || false;
if (this._isNativeSelect) {
this.controlType = (element as HTMLSelectElement).multiple
? 'mat-native-select-multiple'
: 'mat-native-select';
}
if (this._signalBasedValueAccessor) {
effect(() => {
// Read the value so the effect can register the dependency.
this._signalBasedValueAccessor!.value();
this.stateChanges.next();
});
}
}
ngAfterViewInit() {
if (this._platform.isBrowser) {
this._autofillMonitor.monitor(this._elementRef.nativeElement).subscribe(event => {
this.autofilled = event.isAutofilled;
this.stateChanges.next();
});
}
}
ngOnChanges() {
this.stateChanges.next();
}
ngOnDestroy() {
this.stateChanges.complete();
if (this._platform.isBrowser) {
this._autofillMonitor.stopMonitoring(this._elementRef.nativeElement);
}
if (this._platform.IOS) {
this._elementRef.nativeElement.removeEventListener('keyup', this._iOSKeyupListener);
}
if (this._webkitBlinkWheelListenerAttached) {
this._elementRef.nativeElement.removeEventListener('wheel', this._webkitBlinkWheelListener);
}
} | {
"end_byte": 12048,
"start_byte": 3736,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.ts"
} |
components/src/material/input/input.ts_12052_20403 | ngDoCheck() {
if (this.ngControl) {
// We need to re-evaluate this on every change detection cycle, because there are some
// error triggers that we can't subscribe to (e.g. parent form submissions). This means
// that whatever logic is in here has to be super lean or we risk destroying the performance.
this.updateErrorState();
// Since the input isn't a `ControlValueAccessor`, we don't have a good way of knowing when
// the disabled state has changed. We can't use the `ngControl.statusChanges`, because it
// won't fire if the input is disabled with `emitEvents = false`, despite the input becoming
// disabled.
if (this.ngControl.disabled !== null && this.ngControl.disabled !== this.disabled) {
this.disabled = this.ngControl.disabled;
this.stateChanges.next();
}
}
// We need to dirty-check the native element's value, because there are some cases where
// we won't be notified when it changes (e.g. the consumer isn't using forms or they're
// updating the value using `emitEvent: false`).
this._dirtyCheckNativeValue();
// We need to dirty-check and set the placeholder attribute ourselves, because whether it's
// present or not depends on a query which is prone to "changed after checked" errors.
this._dirtyCheckPlaceholder();
}
/** Focuses the input. */
focus(options?: FocusOptions): void {
this._elementRef.nativeElement.focus(options);
}
/** Refreshes the error state of the input. */
updateErrorState() {
this._errorStateTracker.updateErrorState();
}
/** Callback for the cases where the focused state of the input changes. */
_focusChanged(isFocused: boolean) {
if (isFocused === this.focused) {
return;
}
if (!this._isNativeSelect && isFocused && this.disabled && this.disabledInteractive) {
const element = this._elementRef.nativeElement as HTMLInputElement;
// Focusing an input that has text will cause all the text to be selected. Clear it since
// the user won't be able to change it. This is based on the internal implementation.
if (element.type === 'number') {
// setSelectionRange doesn't work on number inputs so it needs to be set briefly to text.
element.type = 'text';
element.setSelectionRange(0, 0);
element.type = 'number';
} else {
element.setSelectionRange(0, 0);
}
}
this.focused = isFocused;
this.stateChanges.next();
}
_onInput() {
// This is a noop function and is used to let Angular know whenever the value changes.
// Angular will run a new change detection each time the `input` event has been dispatched.
// It's necessary that Angular recognizes the value change, because when floatingLabel
// is set to false and Angular forms aren't used, the placeholder won't recognize the
// value changes and will not disappear.
// Listening to the input event wouldn't be necessary when the input is using the
// FormsModule or ReactiveFormsModule, because Angular forms also listens to input events.
}
/** Does some manual dirty checking on the native input `value` property. */
protected _dirtyCheckNativeValue() {
const newValue = this._elementRef.nativeElement.value;
if (this._previousNativeValue !== newValue) {
this._previousNativeValue = newValue;
this.stateChanges.next();
}
}
/** Does some manual dirty checking on the native input `placeholder` attribute. */
private _dirtyCheckPlaceholder() {
const placeholder = this._getPlaceholder();
if (placeholder !== this._previousPlaceholder) {
const element = this._elementRef.nativeElement;
this._previousPlaceholder = placeholder;
placeholder
? element.setAttribute('placeholder', placeholder)
: element.removeAttribute('placeholder');
}
}
/** Gets the current placeholder of the form field. */
protected _getPlaceholder(): string | null {
return this.placeholder || null;
}
/** Make sure the input is a supported type. */
protected _validateType() {
if (
MAT_INPUT_INVALID_TYPES.indexOf(this._type) > -1 &&
(typeof ngDevMode === 'undefined' || ngDevMode)
) {
throw getMatInputUnsupportedTypeError(this._type);
}
}
/** Checks whether the input type is one of the types that are never empty. */
protected _isNeverEmpty() {
return this._neverEmptyInputTypes.indexOf(this._type) > -1;
}
/** Checks whether the input is invalid based on the native validation. */
protected _isBadInput() {
// The `validity` property won't be present on platform-server.
let validity = (this._elementRef.nativeElement as HTMLInputElement).validity;
return validity && validity.badInput;
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
get empty(): boolean {
return (
!this._isNeverEmpty() &&
!this._elementRef.nativeElement.value &&
!this._isBadInput() &&
!this.autofilled
);
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
get shouldLabelFloat(): boolean {
if (this._isNativeSelect) {
// For a single-selection `<select>`, the label should float when the selected option has
// a non-empty display value. For a `<select multiple>`, the label *always* floats to avoid
// overlapping the label with the options.
const selectElement = this._elementRef.nativeElement as HTMLSelectElement;
const firstOption: HTMLOptionElement | undefined = selectElement.options[0];
// On most browsers the `selectedIndex` will always be 0, however on IE and Edge it'll be
// -1 if the `value` is set to something, that isn't in the list of options, at a later point.
return (
this.focused ||
selectElement.multiple ||
!this.empty ||
!!(selectElement.selectedIndex > -1 && firstOption && firstOption.label)
);
} else {
return (this.focused && !this.disabled) || !this.empty;
}
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
setDescribedByIds(ids: string[]) {
if (ids.length) {
this._elementRef.nativeElement.setAttribute('aria-describedby', ids.join(' '));
} else {
this._elementRef.nativeElement.removeAttribute('aria-describedby');
}
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
onContainerClick() {
// Do not re-focus the input element if the element is already focused. Otherwise it can happen
// that someone clicks on a time input and the cursor resets to the "hours" field while the
// "minutes" field was actually clicked. See: https://github.com/angular/components/issues/12849
if (!this.focused) {
this.focus();
}
}
/** Whether the form control is a native select that is displayed inline. */
_isInlineSelect(): boolean {
const element = this._elementRef.nativeElement as HTMLSelectElement;
return this._isNativeSelect && (element.multiple || element.size > 1);
}
private _iOSKeyupListener = (event: Event): void => {
const el = event.target as HTMLInputElement;
// Note: We specifically check for 0, rather than `!el.selectionStart`, because the two
// indicate different things. If the value is 0, it means that the caret is at the start
// of the input, whereas a value of `null` means that the input doesn't support
// manipulating the selection range. Inputs that don't support setting the selection range
// will throw an error so we want to avoid calling `setSelectionRange` on them. See:
// https://html.spec.whatwg.org/multipage/input.html#do-not-apply
if (!el.value && el.selectionStart === 0 && el.selectionEnd === 0) {
// Note: Just setting `0, 0` doesn't fix the issue. Setting
// `1, 1` fixes it for the first time that you type text and
// then hold delete. Toggling to `1, 1` and then back to
// `0, 0` seems to completely fix it.
el.setSelectionRange(1, 1);
el.setSelectionRange(0, 0);
}
};
private _webkitBlinkWheelListener = (): void => {
// This is a noop function and is used to enable mouse wheel input
// on number inputs
// on blink and webkit browsers.
}; | {
"end_byte": 20403,
"start_byte": 12052,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.ts"
} |
components/src/material/input/input.ts_20407_21929 | /**
* In blink and webkit browsers a focused number input does not increment or decrement its value
* on mouse wheel interaction unless a wheel event listener is attached to it or one of its ancestors or a passive wheel listener is attached somewhere in the DOM.
* For example: Hitting a tooltip once enables the mouse wheel input for all number inputs as long as it exists.
* In order to get reliable and intuitive behavior we apply a wheel event on our own
* thus making sure increment and decrement by mouse wheel works every time.
* @docs-private
*/
private _ensureWheelDefaultBehavior(): void {
if (
!this._webkitBlinkWheelListenerAttached &&
this._type === 'number' &&
(this._platform.BLINK || this._platform.WEBKIT)
) {
this._ngZone.runOutsideAngular(() => {
this._elementRef.nativeElement.addEventListener('wheel', this._webkitBlinkWheelListener);
});
this._webkitBlinkWheelListenerAttached = true;
}
if (this._webkitBlinkWheelListenerAttached && this._type !== 'number') {
this._elementRef.nativeElement.removeEventListener('wheel', this._webkitBlinkWheelListener);
this._webkitBlinkWheelListenerAttached = true;
}
}
/** Gets the value to set on the `readonly` attribute. */
protected _getReadonlyAttribute(): string | null {
if (this._isNativeSelect) {
return null;
}
if (this.readonly || (this.disabled && this.disabledInteractive)) {
return 'true';
}
return null;
}
} | {
"end_byte": 21929,
"start_byte": 20407,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.ts"
} |
components/src/material/input/public-api.ts_0_590 | /**
* @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 {MatInput, MatInputConfig, MAT_INPUT_CONFIG} from './input';
export {MatInputModule} from './module';
export * from './input-value-accessor';
export * from './input-errors';
// Re-provide these for convenience since they used to be provided implicitly.
export {
MatFormField,
MatLabel,
MatHint,
MatError,
MatPrefix,
MatSuffix,
} from '@angular/material/form-field';
| {
"end_byte": 590,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/public-api.ts"
} |
components/src/material/input/input.spec.ts_0_1162 | import {getSupportedInputTypes} from '@angular/cdk/platform';
import {dispatchFakeEvent, wrappedErrorMessage} from '@angular/cdk/testing/private';
import {
ChangeDetectionStrategy,
Component,
Directive,
ErrorHandler,
Provider,
Type,
ViewChild,
} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush, tick} from '@angular/core/testing';
import {
FormControl,
FormGroup,
FormGroupDirective,
FormsModule,
NgForm,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import {
ErrorStateMatcher,
ShowOnDirtyErrorStateMatcher,
ThemePalette,
} from '@angular/material/core';
import {
FloatLabelType,
MAT_FORM_FIELD_DEFAULT_OPTIONS,
MatFormField,
MatFormFieldAppearance,
MatFormFieldModule,
SubscriptSizing,
getMatFormFieldDuplicatedHintError,
getMatFormFieldMissingControlError,
} from '@angular/material/form-field';
import {MatIconModule} from '@angular/material/icon';
import {By} from '@angular/platform-browser';
import {BrowserAnimationsModule, NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MAT_INPUT_VALUE_ACCESSOR, MatInput, MatInputModule} from './index'; | {
"end_byte": 1162,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.spec.ts"
} |
components/src/material/input/input.spec.ts_1164_10712 | describe('MatMdcInput without forms', () => {
it('should default to floating labels', fakeAsync(() => {
let fixture = createComponent(MatInputWithLabel);
fixture.detectChanges();
let formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField.floatLabel)
.withContext('Expected MatInput to set floatingLabel to auto by default.')
.toBe('auto');
}));
it('should default to global floating label type', fakeAsync(() => {
let fixture = createComponent(MatInputWithLabel, [
{
provide: MAT_FORM_FIELD_DEFAULT_OPTIONS,
useValue: {floatLabel: 'always'},
},
]);
fixture.detectChanges();
let formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField.floatLabel)
.withContext('Expected MatInput to set floatingLabel to always from global option.')
.toBe('always');
}));
it('should not be treated as empty if type is date', fakeAsync(() => {
const fixture = createComponent(MatInputDateTestController);
fixture.detectChanges();
if (getSupportedInputTypes().has('date')) {
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField).toBeTruthy();
expect(formField!._control.empty).toBe(false);
}
}));
it('should be treated as empty if type is date on unsupported browser', fakeAsync(() => {
const fixture = createComponent(MatInputDateTestController);
fixture.detectChanges();
if (!getSupportedInputTypes().has('date')) {
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField).toBeTruthy();
expect(formField!._control.empty).toBe(true);
}
}));
it('should treat text input type as empty at init', fakeAsync(() => {
let fixture = createComponent(MatInputTextTestController);
fixture.detectChanges();
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField).toBeTruthy();
expect(formField!._control.empty).toBe(true);
}));
it('should treat password input type as empty at init', fakeAsync(() => {
let fixture = createComponent(MatInputPasswordTestController);
fixture.detectChanges();
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField).toBeTruthy();
expect(formField!._control.empty).toBe(true);
}));
it('should treat number input type as empty at init', fakeAsync(() => {
let fixture = createComponent(MatInputNumberTestController);
fixture.detectChanges();
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField).toBeTruthy();
expect(formField!._control.empty).toBe(true);
}));
it('should not be empty after input entered', fakeAsync(() => {
let fixture = createComponent(MatInputTextTestController);
fixture.detectChanges();
let inputEl = fixture.debugElement.query(By.css('input'))!;
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField).toBeTruthy();
expect(formField!._control.empty).toBe(true);
inputEl.nativeElement.value = 'hello';
// Simulate input event.
inputEl.triggerEventHandler('input', {target: inputEl.nativeElement});
fixture.detectChanges();
expect(formField!._control.empty).toBe(false);
}));
it('should update the placeholder when input entered', fakeAsync(() => {
let fixture = createComponent(MatInputWithStaticLabel);
fixture.detectChanges();
const inputEl = fixture.debugElement.query(By.css('input'))!;
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField).toBeTruthy();
expect(formField._control.empty).toBe(true);
expect(formField._shouldLabelFloat()).toBe(false);
// Update the value of the input.
inputEl.nativeElement.value = 'Text';
// Fake behavior of the `(input)` event which should trigger a change detection.
fixture.detectChanges();
expect(formField._control.empty).toBe(false);
// should not float label if there is no label
expect(formField._shouldLabelFloat()).toBe(false);
}));
it('should not be empty when the value set before view init', fakeAsync(() => {
let fixture = createComponent(MatInputWithValueBinding);
fixture.detectChanges();
const formField = fixture.debugElement.query(By.directive(MatFormField))!
.componentInstance as MatFormField;
expect(formField._control.empty).toBe(false);
fixture.componentInstance.value = '';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(formField._control.empty).toBe(true);
}));
it('should add id', fakeAsync(() => {
let fixture = createComponent(MatInputTextTestController);
fixture.detectChanges();
const inputElement: HTMLInputElement = fixture.debugElement.query(
By.css('input'),
)!.nativeElement;
const labelElement: HTMLInputElement = fixture.debugElement.query(
By.css('label'),
)!.nativeElement;
expect(inputElement.id).toBeTruthy();
expect(inputElement.id).toEqual(labelElement.getAttribute('for')!);
}));
it('should add aria-required reflecting the required state', fakeAsync(() => {
const fixture = createComponent(MatInputWithRequired);
fixture.detectChanges();
const inputElement: HTMLInputElement = fixture.debugElement.query(
By.css('input'),
)!.nativeElement;
expect(inputElement.getAttribute('aria-required'))
.withContext('Expected aria-required to reflect required state of false')
.toBe('false');
fixture.componentInstance.required = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputElement.getAttribute('aria-required'))
.withContext('Expected aria-required to reflect required state of true')
.toBe('true');
}));
it('should not overwrite existing id', fakeAsync(() => {
let fixture = createComponent(MatInputWithId);
fixture.detectChanges();
const inputElement: HTMLInputElement = fixture.debugElement.query(
By.css('input'),
)!.nativeElement;
const labelElement: HTMLInputElement = fixture.debugElement.query(
By.css('label'),
)!.nativeElement;
expect(inputElement.id).toBe('test-id');
expect(labelElement.getAttribute('for')).toBe('test-id');
}));
it("validates there's only one hint label per side", () => {
let fixture = createComponent(MatInputInvalidHintTestController);
expect(() => fixture.detectChanges()).toThrowError(
wrappedErrorMessage(getMatFormFieldDuplicatedHintError('start')),
);
});
it("validates there's only one hint label per side (attribute)", () => {
let fixture = createComponent(MatInputInvalidHint2TestController);
expect(() => fixture.detectChanges()).toThrowError(
wrappedErrorMessage(getMatFormFieldDuplicatedHintError('start')),
);
});
it('validates that matInput child is present', fakeAsync(() => {
let fixture = createComponent(MatInputMissingMatInputTestController);
expect(() => fixture.detectChanges()).toThrowError(
wrappedErrorMessage(getMatFormFieldMissingControlError()),
);
}));
it('validates that matInput child is present after initialization', fakeAsync(() => {
let fixture = createComponent(MatInputWithNgIf);
expect(() => fixture.detectChanges()).not.toThrowError(
wrappedErrorMessage(getMatFormFieldMissingControlError()),
);
fixture.componentInstance.renderInput = false;
fixture.changeDetectorRef.markForCheck();
expect(() => fixture.detectChanges()).toThrowError(
wrappedErrorMessage(getMatFormFieldMissingControlError()),
);
}));
it('validates the type', fakeAsync(() => {
let fixture = createComponent(MatInputInvalidTypeTestController);
// Technically this throws during the OnChanges detection phase,
// so the error is really a ChangeDetectionError and it becomes
// hard to build a full exception to compare with.
// We just check for any exception in this case.
expect(() => fixture.detectChanges())
.toThrow
/* new MatInputUnsupportedTypeError('file') */
();
}));
it('supports hint labels attribute', fakeAsync(() => {
let fixture = createComponent(MatInputHintLabelTestController);
fixture.detectChanges();
// If the hint label is empty, expect no label.
expect(fixture.debugElement.query(By.css('.mat-mdc-form-field-hint'))).toBeNull();
fixture.componentInstance.label = 'label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.debugElement.query(By.css('.mat-mdc-form-field-hint'))).not.toBeNull();
}));
it('sets an id on hint labels', fakeAsync(() => {
let fixture = createComponent(MatInputHintLabelTestController);
fixture.componentInstance.label = 'label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let hint = fixture.debugElement.query(By.css('.mat-mdc-form-field-hint'))!.nativeElement;
expect(hint.getAttribute('id')).toBeTruthy();
})); | {
"end_byte": 10712,
"start_byte": 1164,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.spec.ts"
} |
components/src/material/input/input.spec.ts_10716_20742 | it('supports hint labels elements', fakeAsync(() => {
let fixture = createComponent(MatInputHintLabel2TestController);
fixture.detectChanges();
// In this case, we should have an empty <mat-hint>.
let el = fixture.debugElement.query(By.css('mat-hint'))!.nativeElement;
expect(el.textContent).toBeFalsy();
fixture.componentInstance.label = 'label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
el = fixture.debugElement.query(By.css('mat-hint'))!.nativeElement;
expect(el.textContent).toBe('label');
}));
it('sets an id on the hint element', fakeAsync(() => {
let fixture = createComponent(MatInputHintLabel2TestController);
fixture.componentInstance.label = 'label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let hint = fixture.debugElement.query(By.css('mat-hint'))!.nativeElement;
expect(hint.getAttribute('id')).toBeTruthy();
}));
it('supports label required star', fakeAsync(() => {
const fixture = createComponent(MatInputLabelRequiredTestComponent);
fixture.detectChanges();
const label = fixture.debugElement.query(By.css('label'))!;
expect(label).not.toBeNull();
expect(label.nativeElement.textContent).toBe('hello');
expect(label.nativeElement.querySelector('.mat-mdc-form-field-required-marker')).toBeTruthy();
}));
it('should show the required star when using a FormControl', fakeAsync(() => {
const fixture = createComponent(MatInputWithRequiredFormControl);
fixture.detectChanges();
const label = fixture.debugElement.query(By.css('label'))!;
expect(label).not.toBeNull();
expect(label.nativeElement.textContent).toBe('Hello');
expect(label.nativeElement.querySelector('.mat-mdc-form-field-required-marker')).toBeTruthy();
}));
it('should not hide the required star if input is disabled', () => {
const fixture = createComponent(MatInputLabelRequiredTestComponent);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const label = fixture.debugElement.query(By.css('label'))!;
expect(label).not.toBeNull();
expect(label.nativeElement.textContent).toBe('hello');
expect(label.nativeElement.querySelector('.mat-mdc-form-field-required-marker')).toBeTruthy();
});
it('hide label required star when set to hide the required marker', fakeAsync(() => {
const fixture = createComponent(MatInputLabelRequiredTestComponent);
fixture.detectChanges();
const label = fixture.debugElement.query(By.css('label'))!;
expect(label).not.toBeNull();
expect(label.nativeElement.querySelector('.mat-mdc-form-field-required-marker')).toBeTruthy();
expect(label.nativeElement.textContent).toBe('hello');
fixture.componentInstance.hideRequiredMarker = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(label.nativeElement.querySelector('.mat-mdc-form-field-required-marker')).toBeFalsy();
expect(label.nativeElement.textContent).toBe('hello');
}));
it('supports the disabled attribute as binding', fakeAsync(() => {
const fixture = createComponent(MatInputWithDisabled);
fixture.detectChanges();
const wrapperEl = fixture.debugElement.query(
By.css('.mat-mdc-text-field-wrapper'),
)!.nativeElement;
const inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(wrapperEl.classList.contains('mdc-text-field--disabled'))
.withContext(`Expected form field not to start out disabled.`)
.toBe(false);
expect(inputEl.disabled).toBe(false);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(wrapperEl.classList.contains('mdc-text-field--disabled'))
.withContext(`Expected form field to look disabled after property is set.`)
.toBe(true);
expect(inputEl.disabled).toBe(true);
}));
it('should be able to set an input as being disabled and interactive', fakeAsync(() => {
const fixture = createComponent(MatInputWithDisabled);
fixture.componentInstance.disabled = true;
fixture.detectChanges();
const input = fixture.nativeElement.querySelector('input') as HTMLInputElement;
expect(input.disabled).toBe(true);
expect(input.readOnly).toBe(false);
expect(input.hasAttribute('aria-disabled')).toBe(false);
expect(input.classList).not.toContain('mat-mdc-input-disabled-interactive');
fixture.componentInstance.disabledInteractive = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(input.disabled).toBe(false);
expect(input.readOnly).toBe(true);
expect(input.getAttribute('aria-disabled')).toBe('true');
expect(input.classList).toContain('mat-mdc-input-disabled-interactive');
}));
it('should not float the label when disabled and disabledInteractive are set', fakeAsync(() => {
const fixture = createComponent(MatInputTextTestController);
fixture.componentInstance.disabled = fixture.componentInstance.disabledInteractive = true;
fixture.detectChanges();
const label = fixture.nativeElement.querySelector('label');
const input = fixture.debugElement
.query(By.directive(MatInput))!
.injector.get<MatInput>(MatInput);
expect(label.classList).not.toContain('mdc-floating-label--float-above');
// Call the focus handler directly to avoid flakyness where
// browsers don't focus elements if the window is minimized.
input._focusChanged(true);
fixture.detectChanges();
expect(label.classList).not.toContain('mdc-floating-label--float-above');
}));
it('should float the label when disabledInteractive is set and the input has a value', fakeAsync(() => {
const fixture = createComponent(MatInputWithDynamicLabel);
fixture.componentInstance.shouldFloat = 'auto';
fixture.componentInstance.disabled = fixture.componentInstance.disabledInteractive = true;
fixture.detectChanges();
const input = fixture.nativeElement.querySelector('input');
const label = fixture.nativeElement.querySelector('label');
expect(label.classList).not.toContain('mdc-floating-label--float-above');
input.value = 'Text';
dispatchFakeEvent(input, 'input');
fixture.detectChanges();
expect(label.classList).toContain('mdc-floating-label--float-above');
}));
it('supports the disabled attribute as binding for select', fakeAsync(() => {
const fixture = createComponent(MatInputSelect);
fixture.detectChanges();
const wrapperEl = fixture.debugElement.query(
By.css('.mat-mdc-text-field-wrapper'),
)!.nativeElement;
const selectEl = fixture.debugElement.query(By.css('select'))!.nativeElement;
expect(wrapperEl.classList.contains('mdc-text-field--disabled'))
.withContext(`Expected form field not to start out disabled.`)
.toBe(false);
expect(selectEl.disabled).toBe(false);
fixture.componentInstance.disabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(wrapperEl.classList.contains('mdc-text-field--disabled'))
.withContext(`Expected form field to look disabled after property is set.`)
.toBe(true);
expect(selectEl.disabled).toBe(true);
}));
it('should add a class to the form-field if animations are disabled', () => {
configureTestingModule(MatInputWithId, {animations: false});
const fixture = TestBed.createComponent(MatInputWithId);
fixture.detectChanges();
const formFieldEl = fixture.nativeElement.querySelector('.mat-mdc-form-field');
expect(formFieldEl.classList).toContain('mat-form-field-no-animations');
});
it('should add a class to the form field if it has a native select', fakeAsync(() => {
const fixture = createComponent(MatInputSelect);
fixture.detectChanges();
const formField = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
expect(formField.classList).toContain('mat-mdc-form-field-type-mat-native-select');
}));
it('supports the required attribute as binding', fakeAsync(() => {
let fixture = createComponent(MatInputWithRequired);
fixture.detectChanges();
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.required).toBe(false);
fixture.componentInstance.required = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputEl.required).toBe(true);
}));
it('supports the required attribute as binding for select', fakeAsync(() => {
const fixture = createComponent(MatInputSelect);
fixture.detectChanges();
const selectEl = fixture.debugElement.query(By.css('select'))!.nativeElement;
expect(selectEl.required).toBe(false);
fixture.componentInstance.required = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(selectEl.required).toBe(true);
}));
it('supports the type attribute as binding', fakeAsync(() => {
let fixture = createComponent(MatInputWithType);
fixture.detectChanges();
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(inputEl.type).toBe('text');
fixture.componentInstance.type = 'password';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(inputEl.type).toBe('password');
}));
it('supports textarea', fakeAsync(() => {
let fixture = createComponent(MatInputTextareaWithBindings);
fixture.detectChanges();
const textarea: HTMLTextAreaElement = fixture.nativeElement.querySelector('textarea');
expect(textarea).not.toBeNull();
}));
it('supports select', fakeAsync(() => {
const fixture = createComponent(MatInputSelect);
fixture.detectChanges();
const nativeSelect: HTMLTextAreaElement = fixture.nativeElement.querySelector('select');
expect(nativeSelect).not.toBeNull();
})); | {
"end_byte": 20742,
"start_byte": 10716,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.spec.ts"
} |
components/src/material/input/input.spec.ts_20746_30190 | it('sets the aria-describedby when a hintLabel is set', fakeAsync(() => {
let fixture = createComponent(MatInputHintLabelTestController);
fixture.componentInstance.label = 'label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const hint = fixture.debugElement.query(By.css('.mat-mdc-form-field-hint'))!.nativeElement;
const input = fixture.debugElement.query(By.css('input'))!.nativeElement;
const hintId = hint.getAttribute('id');
expect(input.getAttribute('aria-describedby')).toBe(`initial ${hintId}`);
}));
it('supports user binding to aria-describedby', fakeAsync(() => {
let fixture = createComponent(MatInputWithSubscriptAndAriaDescribedBy);
fixture.componentInstance.label = 'label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const hint = fixture.debugElement.query(By.css('.mat-mdc-form-field-hint'))!.nativeElement;
const input = fixture.debugElement.query(By.css('input'))!.nativeElement;
const hintId = hint.getAttribute('id');
expect(input.getAttribute('aria-describedby')).toBe(hintId);
fixture.componentInstance.userDescribedByValue = 'custom-error custom-error-two';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(input.getAttribute('aria-describedby')).toBe(`custom-error custom-error-two ${hintId}`);
fixture.componentInstance.userDescribedByValue = 'custom-error';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(input.getAttribute('aria-describedby')).toBe(`custom-error ${hintId}`);
fixture.componentInstance.showError = true;
fixture.changeDetectorRef.markForCheck();
fixture.componentInstance.formControl.markAsTouched();
fixture.componentInstance.formControl.setErrors({invalid: true});
fixture.detectChanges();
expect(input.getAttribute('aria-describedby')).toMatch(/^custom-error mat-mdc-error-\d+$/);
fixture.componentInstance.label = '';
fixture.componentInstance.userDescribedByValue = '';
fixture.componentInstance.showError = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(input.hasAttribute('aria-describedby')).toBe(false);
}));
it('sets the aria-describedby to the id of the mat-hint', fakeAsync(() => {
let fixture = createComponent(MatInputHintLabel2TestController);
fixture.componentInstance.label = 'label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let hint = fixture.debugElement.query(By.css('.mat-mdc-form-field-hint'))!.nativeElement;
let input = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(input.getAttribute('aria-describedby')).toBe(hint.getAttribute('id'));
}));
it('sets the aria-describedby with multiple mat-hint instances', fakeAsync(() => {
let fixture = createComponent(MatInputMultipleHintTestController);
fixture.componentInstance.startId = 'start';
fixture.componentInstance.endId = 'end';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
let input = fixture.debugElement.query(By.css('input'))!.nativeElement;
expect(input.getAttribute('aria-describedby')).toBe('start end');
}));
it('should set a class on the hint element based on its alignment', fakeAsync(() => {
const fixture = createComponent(MatInputMultipleHintTestController);
fixture.componentInstance.startId = 'start';
fixture.componentInstance.endId = 'end';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const start = fixture.nativeElement.querySelector('#start');
const end = fixture.nativeElement.querySelector('#end');
expect(start.classList).not.toContain('mat-mdc-form-field-hint-end');
expect(end.classList).toContain('mat-mdc-form-field-hint-end');
}));
it('sets the aria-describedby when a hintLabel is set, in addition to a mat-hint', fakeAsync(() => {
let fixture = createComponent(MatInputMultipleHintMixedTestController);
fixture.detectChanges();
let hintLabel = fixture.debugElement.query(
By.css('.mat-mdc-form-field-hint:not(.mat-mdc-form-field-hint-end)'),
)!.nativeElement;
let endLabel = fixture.debugElement.query(
By.css('.mat-mdc-form-field-hint.mat-mdc-form-field-hint-end'),
)!.nativeElement;
let input = fixture.debugElement.query(By.css('input'))!.nativeElement;
let ariaValue = input.getAttribute('aria-describedby');
expect(ariaValue).toBe(`${hintLabel.getAttribute('id')} ${endLabel.getAttribute('id')}`);
}));
it('should float when floatLabel is set to default and text is entered', fakeAsync(() => {
let fixture = createComponent(MatInputWithDynamicLabel);
fixture.detectChanges();
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
let labelEl = fixture.debugElement.query(By.css('label'))!.nativeElement;
expect(labelEl.classList).toContain('mdc-floating-label--float-above');
fixture.componentInstance.shouldFloat = 'auto';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(labelEl.classList).not.toContain('mdc-floating-label--float-above');
// Update the value of the input.
inputEl.value = 'Text';
// Fake behavior of the `(input)` event which should trigger a change detection.
dispatchFakeEvent(inputEl, 'input');
fixture.detectChanges();
expect(labelEl.classList).toContain('mdc-floating-label--float-above');
}));
it('should always float the label when floatLabel is set to always', fakeAsync(() => {
let fixture = createComponent(MatInputWithDynamicLabel);
fixture.detectChanges();
let inputEl = fixture.debugElement.query(By.css('input'))!.nativeElement;
let labelEl = fixture.debugElement.query(By.css('label'))!.nativeElement;
expect(labelEl.classList).toContain('mdc-floating-label--float-above');
fixture.detectChanges();
// Update the value of the input.
inputEl.value = 'Text';
// Fake behavior of the `(input)` event which should trigger a change detection.
fixture.detectChanges();
expect(labelEl.classList).toContain('mdc-floating-label--float-above');
}));
it('should float labels when select has value', fakeAsync(() => {
const fixture = createComponent(MatInputSelect);
fixture.detectChanges();
const labelEl = fixture.debugElement.query(By.css('label'))!.nativeElement;
expect(labelEl.classList).toContain('mdc-floating-label--float-above');
}));
it('should mark a multi-select as being inline', fakeAsync(() => {
const fixture = createComponent(MatInputSelect);
fixture.detectChanges();
const select: HTMLSelectElement = fixture.nativeElement.querySelector('select');
expect(select.classList).not.toContain('mat-mdc-native-select-inline');
select.multiple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(select.classList).toContain('mat-mdc-native-select-inline');
}));
it('should mark a select with a size as being inline', fakeAsync(() => {
const fixture = createComponent(MatInputSelect);
fixture.detectChanges();
const select: HTMLSelectElement = fixture.nativeElement.querySelector('select');
expect(select.classList).not.toContain('mat-mdc-native-select-inline');
select.size = 3;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(select.classList).toContain('mat-mdc-native-select-inline');
select.size = 1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(select.classList).not.toContain('mat-mdc-native-select-inline');
}));
it('should not float the label if the selectedIndex is negative', fakeAsync(() => {
const fixture = createComponent(MatInputSelect);
fixture.detectChanges();
const labelEl = fixture.debugElement.query(By.css('label'))!.nativeElement;
const selectEl: HTMLSelectElement = fixture.nativeElement.querySelector('select');
expect(labelEl.classList).toContain('mdc-floating-label--float-above');
selectEl.selectedIndex = -1;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(labelEl.classList).not.toContain('mdc-floating-label--float-above');
}));
it('should not float labels when select has no value, no option label, no option innerHtml', fakeAsync(() => {
const fixture = createComponent(MatInputSelectWithNoLabelNoValue);
fixture.detectChanges();
const labelEl = fixture.debugElement.query(By.css('label'))!.nativeElement;
expect(labelEl.classList).not.toContain('mdc-floating-label--float-above');
}));
it('should floating labels when select has no value but has option label', fakeAsync(() => {
const fixture = createComponent(MatInputSelectWithLabel);
fixture.detectChanges();
const labelEl = fixture.debugElement.query(By.css('label'))!.nativeElement;
expect(labelEl.classList).toContain('mdc-floating-label--float-above');
}));
it('should floating labels when select has no value but has option innerHTML', fakeAsync(() => {
const fixture = createComponent(MatInputSelectWithInnerHtml);
fixture.detectChanges();
const labelEl = fixture.debugElement.query(By.css('label'))!.nativeElement;
expect(labelEl.classList).toContain('mdc-floating-label--float-above');
})); | {
"end_byte": 30190,
"start_byte": 20746,
"url": "https://github.com/angular/components/blob/main/src/material/input/input.spec.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.