_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material/grid-list/grid-list.spec.ts_8732_15666 | it('should set the correct list height in ratio mode', () => {
const fixture = createComponent(GridListWithRatioHeightAndMulipleRows);
fixture.detectChanges();
const list = fixture.debugElement.query(By.directive(MatGridList))!;
const inlineStyles = list.nativeElement.style;
expect(inlineStyles.paddingBottom).toBeTruthy();
expect(inlineStyles.height).toBeFalsy();
expect(getDimension(list, 'height')).toBe(201);
});
it('should set the correct list height in fixed mode', () => {
const fixture = createComponent(GridListWithFixRowHeightAndMultipleRows);
fixture.detectChanges();
const list = fixture.debugElement.query(By.directive(MatGridList))!;
expect(getDimension(list, 'height')).toBe(201);
});
it('should allow adjustment of tile colspan', () => {
const fixture = createComponent(GridListWithColspanBinding);
fixture.componentInstance.colspan = 2;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tile = fixture.debugElement.query(By.directive(MatGridTile))!;
expect(getDimension(tile, 'width')).toBe(199.5);
fixture.componentInstance.colspan = 3;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(getDimension(tile, 'width')).toBe(299.75);
});
it('should allow adjustment of tile rowspan', () => {
const fixture = createComponent(GridListWithRowspanBinding);
fixture.componentInstance.rowspan = 2;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tile = fixture.debugElement.query(By.directive(MatGridTile))!;
expect(getDimension(tile, 'height')).toBe(201);
fixture.componentInstance.rowspan = 3;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(getDimension(tile, 'height')).toBe(302);
});
it('should lay out tiles correctly for a complex layout', () => {
const fixture = createComponent(GridListWithComplexLayout);
fixture.componentInstance.tiles = [
{cols: 3, rows: 1},
{cols: 1, rows: 2},
{cols: 1, rows: 1},
{cols: 2, rows: 1},
];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const tiles = fixture.debugElement.queryAll(By.css('mat-grid-tile'));
expect(getDimension(tiles[0], 'width')).toBe(299.75);
expect(getDimension(tiles[0], 'height')).toBe(100);
expect(getComputedLeft(tiles[0])).toBe(0);
expect(getDimension(tiles[0], 'top')).toBe(0);
expect(getDimension(tiles[1], 'width')).toBe(99.25);
expect(getDimension(tiles[1], 'height')).toBe(201);
expect(getComputedLeft(tiles[1])).toBe(300.75);
expect(getDimension(tiles[1], 'top')).toBe(0);
expect(getDimension(tiles[2], 'width')).toBe(99.25);
expect(getDimension(tiles[2], 'height')).toBe(100);
expect(getComputedLeft(tiles[2])).toBe(0);
expect(getDimension(tiles[2], 'top')).toBe(101);
expect(getDimension(tiles[3], 'width')).toBe(199.5);
expect(getDimension(tiles[3], 'height')).toBe(100);
expect(getComputedLeft(tiles[3])).toBe(100.25);
expect(getDimension(tiles[3], 'top')).toBe(101);
});
it('should lay out tiles correctly', () => {
const fixture = createComponent(GridListWithLayout);
fixture.detectChanges();
const tiles = fixture.debugElement.queryAll(By.css('mat-grid-tile'));
expect(getDimension(tiles[0], 'width')).toBe(40);
expect(getDimension(tiles[0], 'height')).toBe(40);
expect(getComputedLeft(tiles[0])).toBe(0);
expect(getDimension(tiles[0], 'top')).toBe(0);
expect(getDimension(tiles[1], 'width')).toBe(20);
expect(getDimension(tiles[1], 'height')).toBe(20);
expect(getComputedLeft(tiles[1])).toBe(40);
expect(getDimension(tiles[1], 'top')).toBe(0);
expect(getDimension(tiles[2], 'width')).toBe(40);
expect(getDimension(tiles[2], 'height')).toBe(40);
expect(getComputedLeft(tiles[2])).toBe(60);
expect(getDimension(tiles[2], 'top')).toBe(0);
expect(getDimension(tiles[3], 'width')).toBe(40);
expect(getDimension(tiles[3], 'height')).toBe(40);
expect(getComputedLeft(tiles[3])).toBe(0);
expect(getDimension(tiles[3], 'top')).toBe(40);
expect(getDimension(tiles[4], 'width')).toBe(40);
expect(getDimension(tiles[4], 'height')).toBe(40);
expect(getComputedLeft(tiles[4])).toBe(40);
expect(getDimension(tiles[4], 'top')).toBe(40);
});
it('should lay out tiles correctly when single cell to be placed at the beginning', () => {
const fixture = createComponent(GridListWithSingleCellAtBeginning);
fixture.detectChanges();
const tiles = fixture.debugElement.queryAll(By.css('mat-grid-tile'));
expect(getDimension(tiles[0], 'width')).toBe(40);
expect(getDimension(tiles[0], 'height')).toBe(40);
expect(getComputedLeft(tiles[0])).toBe(0);
expect(getDimension(tiles[0], 'top')).toBe(0);
expect(getDimension(tiles[1], 'width')).toBe(20);
expect(getDimension(tiles[1], 'height')).toBe(40);
expect(getComputedLeft(tiles[1])).toBe(40);
expect(getDimension(tiles[1], 'top')).toBe(0);
expect(getDimension(tiles[2], 'width')).toBe(40);
expect(getDimension(tiles[2], 'height')).toBe(40);
expect(getComputedLeft(tiles[2])).toBe(60);
expect(getDimension(tiles[2], 'top')).toBe(0);
expect(getDimension(tiles[3], 'height')).toBe(20);
expect(getComputedLeft(tiles[3])).toBe(0);
expect(getDimension(tiles[3], 'top')).toBe(40);
});
it('should add not add any classes to footers without lines', () => {
const fixture = createComponent(GridListWithFootersWithoutLines);
fixture.detectChanges();
const footer = fixture.debugElement.query(By.directive(MatGridTileText))!;
expect(footer.nativeElement.classList.contains('mat-2-line')).toBe(false);
});
it('should add class to footers with two lines', () => {
const fixture = createComponent(GridListWithFooterContainingTwoLines);
fixture.detectChanges();
const footer = fixture.debugElement.query(By.directive(MatGridTileText))!;
expect(footer.nativeElement.classList.contains('mat-2-line')).toBe(true);
});
it('should add class to footers with two indirect descendant lines', () => {
const fixture = createComponent(GridListWithFooterContainingTwoIndirectDescendantLines);
fixture.detectChanges();
const footer = fixture.debugElement.query(By.directive(MatGridTileText))!;
expect(footer.nativeElement.classList).toContain('mat-2-line');
});
it('should not use calc() that evaluates to 0', () => {
const fixture = createComponent(GirdListWithRowHeightRatio);
fixture.componentInstance.rowHeight = '4:1';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const firstTile = fixture.debugElement.query(By.directive(MatGridTile))!.nativeElement;
expect(firstTile.style.marginTop).toBe('0px');
expect(firstTile.style.left).toBe('0px');
}); | {
"end_byte": 15666,
"start_byte": 8732,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list.spec.ts"
} |
components/src/material/grid-list/grid-list.spec.ts_15670_23876 | it('should reset the old styles when switching to a new tile styler', () => {
const fixture = createComponent(GirdListWithRowHeightRatio);
fixture.componentInstance.rowHeight = '4:1';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const list = fixture.debugElement.query(By.directive(MatGridList))!;
const tile = fixture.debugElement.query(By.directive(MatGridTile))!;
const listInlineStyles = list.nativeElement.style;
const tileInlineStyles = tile.nativeElement.style;
expect(getDimension(tile, 'height')).toBe(100);
expect(tileInlineStyles.paddingTop).toBeTruthy();
expect(tileInlineStyles.height).toBeFalsy();
expect(getDimension(list, 'height')).toBe(100);
expect(listInlineStyles.paddingBottom).toBeTruthy();
expect(listInlineStyles.height).toBeFalsy();
fixture.componentInstance.rowHeight = '400px';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(tileInlineStyles.paddingTop)
.withContext('Expected tile padding to be reset.')
.toBeFalsy();
expect(listInlineStyles.paddingBottom)
.withContext('Expected list padding to be reset.')
.toBeFalsy();
expect(getDimension(tile, 'top')).toBe(0);
expect(getDimension(tile, 'height')).toBe(400);
});
it('should ensure that all tiles are inside the grid when there are no matching gaps', () => {
const fixture = createComponent(GridListWithoutMatchingGap);
const tiles = fixture.debugElement.queryAll(By.css('mat-grid-tile'));
fixture.detectChanges();
expect(tiles.every(tile => getComputedLeft(tile) >= 0))
.withContext('Expected none of the tiles to have a negative `left`')
.toBe(true);
});
it('should default to LTR if empty directionality is given', () => {
const fixture = createComponent(GridListWithEmptyDirectionality);
const tile: HTMLElement = fixture.debugElement.query(By.css('mat-grid-tile'))!.nativeElement;
fixture.detectChanges();
expect(tile.style.left).toBe('0px');
expect(tile.style.right).toBe('');
});
it('should set `right` styles for RTL', () => {
const fixture = createComponent(GridListWithRtl);
const tile: HTMLElement = fixture.debugElement.query(By.css('mat-grid-tile'))!.nativeElement;
fixture.detectChanges();
expect(tile.style.left).toBe('');
expect(tile.style.right).toBe('0px');
});
it('should lay out the tiles if they are not direct descendants of the list', () => {
const fixture = createComponent(GridListWithIndirectTileDescendants);
fixture.detectChanges();
const tile = fixture.debugElement.query(By.directive(MatGridTile))!;
const inlineStyles = tile.nativeElement.style;
expect(inlineStyles.paddingTop).toBeTruthy();
expect(inlineStyles.height).toBeFalsy();
expect(getDimension(tile, 'height')).toBe(200);
});
it('should throw if an invalid value is set as the `rowHeight`', () => {
const fixture = createComponent(GridListWithUnspecifiedRowHeight);
const gridList = fixture.debugElement.query(By.directive(MatGridList))!;
expect(() => {
// Note the semicolon at the end which will be an invalid value on some browsers (see #13252).
gridList.componentInstance.rowHeight = '350px;';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
}).toThrowError(/^Invalid value/);
});
});
/** Gets the computed dimension of a DebugElement in pixels. */
function getDimension(el: DebugElement, dimension: 'width' | 'height' | 'top' | 'left'): number {
const nativeElement: HTMLElement = el.nativeElement;
switch (dimension) {
// Note that we use direct measurements, rather than the computed style, because
// `getComputedStyle` can be inconsistent between browser and can cause flakes.
case 'width':
return nativeElement.getBoundingClientRect().width;
case 'height':
return nativeElement.getBoundingClientRect().height;
case 'top':
return nativeElement.offsetTop;
case 'left':
return nativeElement.offsetLeft;
default:
throw Error(`Unknown dimension ${dimension}.`);
}
}
/** Gets the `left` position of an element. */
function getComputedLeft(element: DebugElement): number {
// While the other properties in this test use `getComputedStyle`, we use `getBoundingClientRect`
// for left because iOS Safari doesn't support using `getComputedStyle` to get the calculated
// `left` value when using CSS `calc`. We subtract the `left` of the document body because
// browsers, by default, add a margin to the body (typically 8px).
const elementRect = element.nativeElement.getBoundingClientRect();
const bodyRect = document.body.getBoundingClientRect();
return elementRect.left - bodyRect.left;
}
@Component({template: '<mat-grid-list></mat-grid-list>', standalone: false})
class GridListWithoutCols {}
@Component({
template: '<mat-grid-list cols="4" rowHeight="4:3:2"></mat-grid-list>',
standalone: false,
})
class GridListWithInvalidRowHeightRatio {}
@Component({
template: '<mat-grid-list cols="4"><mat-grid-tile colspan="5"></mat-grid-tile></mat-grid-list>',
standalone: false,
})
class GridListWithTooWideColspan {}
@Component({template: '<mat-grid-list [cols]="cols"></mat-grid-list>', standalone: false})
class GridListWithDynamicCols {
@ViewChild(MatGridList) gridList: MatGridList;
cols = 2;
}
@Component({
template: `
<div style="width:200px">
<mat-grid-list cols="1">
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>
</div>`,
standalone: false,
})
class GridListWithUnspecifiedRowHeight {}
@Component({
template: `
<div style="width:400px">
<mat-grid-list cols="1" [rowHeight]="rowHeight">
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>
</div>`,
standalone: false,
})
class GirdListWithRowHeightRatio {
rowHeight: string;
}
@Component({
template: `
<mat-grid-list cols="1" rowHeight="fit" [style.height]="totalHeight">
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>`,
standalone: false,
})
class GridListWithFitRowHeightMode {
totalHeight: string;
}
@Component({
template: `
<mat-grid-list cols="4" [rowHeight]="rowHeight">
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>`,
standalone: false,
})
class GridListWithFixedRowHeightMode {
rowHeight: string;
}
@Component({
template: `
<mat-grid-list cols="4" rowHeight="100">
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>`,
standalone: false,
})
class GridListWithUnitlessFixedRowHeight {
rowHeight: string;
}
@Component({
template: `
<div style="width:200px">
<mat-grid-list cols="2" rowHeight="100px">
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>
</div>`,
standalone: false,
})
class GridListWithUnspecifiedGutterSize {}
@Component({
template: `
<div style="width:200px">
<mat-grid-list cols="2" gutterSize="2px" rowHeight="100px">
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>
</div>`,
standalone: false,
})
class GridListWithGutterSize {}
@Component({
template: `
<div style="width:200px">
<mat-grid-list cols="2" gutterSize="2" rowHeight="100px">
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>
</div>`,
standalone: false,
})
class GridListWithUnitlessGutterSize {}
@Component({
template: `
<div style="width:400px">
<mat-grid-list cols="1" rowHeight="4:1">
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>
</div>`,
standalone: false,
})
class GridListWithRatioHeightAndMulipleRows {}
@Component({
template: `
<mat-grid-list cols="1" rowHeight="100px">
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>`,
standalone: false,
})
class GridListWithFixRowHeightAndMultipleRows {} | {
"end_byte": 23876,
"start_byte": 15670,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list.spec.ts"
} |
components/src/material/grid-list/grid-list.spec.ts_23878_28558 | @Component({
template: `
<div style="width:400px">
<mat-grid-list cols="4">
<mat-grid-tile [colspan]="colspan"></mat-grid-tile>
</mat-grid-list>
</div>`,
standalone: false,
})
class GridListWithColspanBinding {
colspan: number;
}
@Component({
template: `
<mat-grid-list cols="1" rowHeight="100px">
<mat-grid-tile [rowspan]="rowspan"></mat-grid-tile>
</mat-grid-list>`,
standalone: false,
})
class GridListWithRowspanBinding {
rowspan: number;
}
@Component({
template: `
<div style="width:400px">
<mat-grid-list cols="4" rowHeight="100px">
@for (tile of tiles; track tile) {
<mat-grid-tile [colspan]="tile.cols" [rowspan]="tile.rows"
[style.background]="tile.color">
{{tile.text}}
</mat-grid-tile>
}
</mat-grid-list>
</div>`,
standalone: false,
})
class GridListWithComplexLayout {
tiles: any[];
}
@Component({
template: `
<div style="width:100px">
<mat-grid-list [cols]="10" gutterSize="0px" rowHeight="10px">
<mat-grid-tile [colspan]="4" [rowspan]="4"></mat-grid-tile>
<mat-grid-tile [colspan]="2" [rowspan]="2"></mat-grid-tile>
<mat-grid-tile [colspan]="4" [rowspan]="4"></mat-grid-tile>
<mat-grid-tile [colspan]="4" [rowspan]="4"></mat-grid-tile>
<mat-grid-tile [colspan]="4" [rowspan]="4"></mat-grid-tile>
</mat-grid-list>
</div>`,
standalone: false,
})
class GridListWithLayout {}
@Component({
template: `
<div style="width:100px">
<mat-grid-list [cols]="10" gutterSize="0px" rowHeight="10px">
<mat-grid-tile [colspan]="4" [rowspan]="4"></mat-grid-tile>
<mat-grid-tile [colspan]="2" [rowspan]="4"></mat-grid-tile>
<mat-grid-tile [colspan]="4" [rowspan]="4"></mat-grid-tile>
<mat-grid-tile [colspan]="1" [rowspan]="2"></mat-grid-tile>
</mat-grid-list>
</div>`,
standalone: false,
})
class GridListWithSingleCellAtBeginning {}
@Component({
template: `
<mat-grid-list cols="1">
<mat-grid-tile>
<mat-grid-tile-footer>
I'm a footer!
</mat-grid-tile-footer>
</mat-grid-tile>
</mat-grid-list>`,
standalone: false,
})
class GridListWithFootersWithoutLines {}
@Component({
template: `
<mat-grid-list cols="1">
<mat-grid-tile>
<mat-grid-tile-footer>
<h3 mat-line>First line</h3>
<span mat-line>Second line</span>
</mat-grid-tile-footer>
</mat-grid-tile>
</mat-grid-list>`,
standalone: false,
})
class GridListWithFooterContainingTwoLines {}
@Component({
template: `
<mat-grid-list cols="1">
<mat-grid-tile>
<mat-grid-tile-footer>
@if (true) {
<h3 mat-line>First line</h3>
<span mat-line>Second line</span>
}
</mat-grid-tile-footer>
</mat-grid-tile>
</mat-grid-list>`,
standalone: false,
})
class GridListWithFooterContainingTwoIndirectDescendantLines {}
@Component({
template: `
<mat-grid-list cols="5">
<mat-grid-tile [rowspan]="1" [colspan]="3">1</mat-grid-tile>
<mat-grid-tile [rowspan]="2" [colspan]="2">2</mat-grid-tile>
<mat-grid-tile [rowspan]="1" [colspan]="2">3</mat-grid-tile>
<mat-grid-tile [rowspan]="2" [colspan]="2">4</mat-grid-tile>
</mat-grid-list>
`,
standalone: false,
})
class GridListWithoutMatchingGap {}
@Component({
template: `<mat-grid-list cols="1"><mat-grid-tile>Hello</mat-grid-tile></mat-grid-list>`,
providers: [{provide: Directionality, useValue: {}}],
standalone: false,
})
class GridListWithEmptyDirectionality {}
@Component({
template: `<mat-grid-list cols="1"><mat-grid-tile>Hello</mat-grid-tile></mat-grid-list>`,
providers: [{provide: Directionality, useValue: {value: 'rtl'}}],
standalone: false,
})
class GridListWithRtl {}
@Component({
// Note the blank `@if` which we need in order to hit the bug that we're testing.
template: `
<div style="width:200px">
<mat-grid-list cols="1">
@if (true) {
<mat-grid-tile></mat-grid-tile>
}
</mat-grid-list>
</div>
`,
standalone: false,
})
class GridListWithIndirectTileDescendants {}
@Component({
template: `
<div style="width:200px">
<mat-grid-list cols="2" rowHeight="100px">
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile>
<mat-grid-list cols="1" rowHeight="100px">
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
<mat-grid-tile></mat-grid-tile>
</mat-grid-list>
</mat-grid-tile>
</mat-grid-list>
</div>`,
standalone: false,
})
class NestedGridList {} | {
"end_byte": 28558,
"start_byte": 23878,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list.spec.ts"
} |
components/src/material/grid-list/README.md_0_99 | Please see the official documentation at https://material.angular.io/components/component/grid-list | {
"end_byte": 99,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/README.md"
} |
components/src/material/grid-list/BUILD.bazel_0_1357 | 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 = "grid-list",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [":grid-list.css"] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/cdk/bidi",
"//src/cdk/coercion",
"//src/material/core",
"@npm//@angular/core",
],
)
sass_library(
name = "grid_list_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = ["//src/material/core:core_scss_lib"],
)
sass_binary(
name = "grid_list_scss",
src = "grid-list.scss",
deps = ["//src/material/core:core_scss_lib"],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":grid-list",
"//src/cdk/bidi",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [":grid-list.md"],
)
extract_tokens(
name = "tokens",
srcs = [":grid_list_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1357,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/BUILD.bazel"
} |
components/src/material/grid-list/tile-coordinator.ts_0_6286 | /**
* @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 describing a tile.
* @docs-private
*/
export interface Tile {
/** Amount of rows that the tile takes up. */
rowspan: number;
/** Amount of columns that the tile takes up. */
colspan: number;
}
/**
* Class for determining, from a list of tiles, the (row, col) position of each of those tiles
* in the grid. This is necessary (rather than just rendering the tiles in normal document flow)
* because the tiles can have a rowspan.
*
* The positioning algorithm greedily places each tile as soon as it encounters a gap in the grid
* large enough to accommodate it so that the tiles still render in the same order in which they
* are given.
*
* The basis of the algorithm is the use of an array to track the already placed tiles. Each
* element of the array corresponds to a column, and the value indicates how many cells in that
* column are already occupied; zero indicates an empty cell. Moving "down" to the next row
* decrements each value in the tracking array (indicating that the column is one cell closer to
* being free).
*
* @docs-private
*/
export class TileCoordinator {
/** Tracking array (see class description). */
tracker: number[];
/** Index at which the search for the next gap will start. */
columnIndex: number = 0;
/** The current row index. */
rowIndex: number = 0;
/** Gets the total number of rows occupied by tiles */
get rowCount(): number {
return this.rowIndex + 1;
}
/**
* Gets the total span of rows occupied by tiles.
* Ex: A list with 1 row that contains a tile with rowspan 2 will have a total rowspan of 2.
*/
get rowspan() {
const lastRowMax = Math.max(...this.tracker);
// if any of the tiles has a rowspan that pushes it beyond the total row count,
// add the difference to the rowcount
return lastRowMax > 1 ? this.rowCount + lastRowMax - 1 : this.rowCount;
}
/** The computed (row, col) position of each tile (the output). */
positions: TilePosition[];
/**
* Updates the tile positions.
* @param numColumns Amount of columns in the grid.
* @param tiles Tiles to be positioned.
*/
update(numColumns: number, tiles: Tile[]) {
this.columnIndex = 0;
this.rowIndex = 0;
this.tracker = new Array(numColumns);
this.tracker.fill(0, 0, this.tracker.length);
this.positions = tiles.map(tile => this._trackTile(tile));
}
/** Calculates the row and col position of a tile. */
private _trackTile(tile: Tile): TilePosition {
// Find a gap large enough for this tile.
const gapStartIndex = this._findMatchingGap(tile.colspan);
// Place tile in the resulting gap.
this._markTilePosition(gapStartIndex, tile);
// The next time we look for a gap, the search will start at columnIndex, which should be
// immediately after the tile that has just been placed.
this.columnIndex = gapStartIndex + tile.colspan;
return new TilePosition(this.rowIndex, gapStartIndex);
}
/** Finds the next available space large enough to fit the tile. */
private _findMatchingGap(tileCols: number): number {
if (tileCols > this.tracker.length && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error(
`mat-grid-list: tile with colspan ${tileCols} is wider than ` +
`grid with cols="${this.tracker.length}".`,
);
}
// Start index is inclusive, end index is exclusive.
let gapStartIndex = -1;
let gapEndIndex = -1;
// Look for a gap large enough to fit the given tile. Empty spaces are marked with a zero.
do {
// If we've reached the end of the row, go to the next row.
if (this.columnIndex + tileCols > this.tracker.length) {
this._nextRow();
gapStartIndex = this.tracker.indexOf(0, this.columnIndex);
gapEndIndex = this._findGapEndIndex(gapStartIndex);
continue;
}
gapStartIndex = this.tracker.indexOf(0, this.columnIndex);
// If there are no more empty spaces in this row at all, move on to the next row.
if (gapStartIndex == -1) {
this._nextRow();
gapStartIndex = this.tracker.indexOf(0, this.columnIndex);
gapEndIndex = this._findGapEndIndex(gapStartIndex);
continue;
}
gapEndIndex = this._findGapEndIndex(gapStartIndex);
// If a gap large enough isn't found, we want to start looking immediately after the current
// gap on the next iteration.
this.columnIndex = gapStartIndex + 1;
// Continue iterating until we find a gap wide enough for this tile. Since gapEndIndex is
// exclusive, gapEndIndex is 0 means we didn't find a gap and should continue.
} while (gapEndIndex - gapStartIndex < tileCols || gapEndIndex == 0);
// If we still didn't manage to find a gap, ensure that the index is
// at least zero so the tile doesn't get pulled out of the grid.
return Math.max(gapStartIndex, 0);
}
/** Move "down" to the next row. */
private _nextRow(): void {
this.columnIndex = 0;
this.rowIndex++;
// Decrement all spaces by one to reflect moving down one row.
for (let i = 0; i < this.tracker.length; i++) {
this.tracker[i] = Math.max(0, this.tracker[i] - 1);
}
}
/**
* Finds the end index (exclusive) of a gap given the index from which to start looking.
* The gap ends when a non-zero value is found.
*/
private _findGapEndIndex(gapStartIndex: number): number {
for (let i = gapStartIndex + 1; i < this.tracker.length; i++) {
if (this.tracker[i] != 0) {
return i;
}
}
// The gap ends with the end of the row.
return this.tracker.length;
}
/** Update the tile tracker to account for the given tile in the given space. */
private _markTilePosition(start: number, tile: Tile): void {
for (let i = 0; i < tile.colspan; i++) {
this.tracker[start + i] = tile.rowspan;
}
}
}
/**
* Simple data structure for tile position (row, col).
* @docs-private
*/
export class TilePosition {
constructor(
public row: number,
public col: number,
) {}
}
| {
"end_byte": 6286,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/tile-coordinator.ts"
} |
components/src/material/grid-list/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/grid-list/index.ts"
} |
components/src/material/grid-list/grid-list-module.ts_0_994 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {MatLineModule, MatCommonModule} from '@angular/material/core';
import {
MatGridTile,
MatGridTileText,
MatGridTileFooterCssMatStyler,
MatGridTileHeaderCssMatStyler,
MatGridAvatarCssMatStyler,
} from './grid-tile';
import {MatGridList} from './grid-list';
@NgModule({
imports: [
MatLineModule,
MatCommonModule,
MatGridList,
MatGridTile,
MatGridTileText,
MatGridTileHeaderCssMatStyler,
MatGridTileFooterCssMatStyler,
MatGridAvatarCssMatStyler,
],
exports: [
MatGridList,
MatGridTile,
MatGridTileText,
MatLineModule,
MatCommonModule,
MatGridTileHeaderCssMatStyler,
MatGridTileFooterCssMatStyler,
MatGridAvatarCssMatStyler,
],
})
export class MatGridListModule {}
| {
"end_byte": 994,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-list-module.ts"
} |
components/src/material/grid-list/grid-tile-text.html_0_191 | <ng-content select="[mat-grid-avatar], [matGridAvatar]"></ng-content>
<div class="mat-grid-list-text"><ng-content select="[mat-line], [matLine]"></ng-content></div>
<ng-content></ng-content>
| {
"end_byte": 191,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/grid-tile-text.html"
} |
components/src/material/grid-list/tile-styler.ts_0_7736 | /**
* @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 {QueryList} from '@angular/core';
import {MatGridTile} from './grid-tile';
import {TileCoordinator} from './tile-coordinator';
/**
* RegExp that can be used to check whether a value will
* be allowed inside a CSS `calc()` expression.
*/
const cssCalcAllowedValue = /^-?\d+((\.\d+)?[A-Za-z%$]?)+$/;
/** Object that can be styled by the `TileStyler`. */
export interface TileStyleTarget {
_setListStyle(style: [string, string | null] | null): void;
_tiles: QueryList<MatGridTile>;
}
/**
* Sets the style properties for an individual tile, given the position calculated by the
* Tile Coordinator.
* @docs-private
*/
export abstract class TileStyler {
_gutterSize: string;
_rows: number = 0;
_rowspan: number = 0;
_cols: number;
_direction: string;
/**
* Adds grid-list layout info once it is available. Cannot be processed in the constructor
* because these properties haven't been calculated by that point.
*
* @param gutterSize Size of the grid's gutter.
* @param tracker Instance of the TileCoordinator.
* @param cols Amount of columns in the grid.
* @param direction Layout direction of the grid.
*/
init(gutterSize: string, tracker: TileCoordinator, cols: number, direction: string): void {
this._gutterSize = normalizeUnits(gutterSize);
this._rows = tracker.rowCount;
this._rowspan = tracker.rowspan;
this._cols = cols;
this._direction = direction;
}
/**
* Computes the amount of space a single 1x1 tile would take up (width or height).
* Used as a basis for other calculations.
* @param sizePercent Percent of the total grid-list space that one 1x1 tile would take up.
* @param gutterFraction Fraction of the gutter size taken up by one 1x1 tile.
* @return The size of a 1x1 tile as an expression that can be evaluated via CSS calc().
*/
getBaseTileSize(sizePercent: number, gutterFraction: number): string {
// Take the base size percent (as would be if evenly dividing the size between cells),
// and then subtracting the size of one gutter. However, since there are no gutters on the
// edges, each tile only uses a fraction (gutterShare = numGutters / numCells) of the gutter
// size. (Imagine having one gutter per tile, and then breaking up the extra gutter on the
// edge evenly among the cells).
return `(${sizePercent}% - (${this._gutterSize} * ${gutterFraction}))`;
}
/**
* Gets The horizontal or vertical position of a tile, e.g., the 'top' or 'left' property value.
* @param offset Number of tiles that have already been rendered in the row/column.
* @param baseSize Base size of a 1x1 tile (as computed in getBaseTileSize).
* @return Position of the tile as a CSS calc() expression.
*/
getTilePosition(baseSize: string, offset: number): string {
// The position comes the size of a 1x1 tile plus gutter for each previous tile in the
// row/column (offset).
return offset === 0 ? '0' : calc(`(${baseSize} + ${this._gutterSize}) * ${offset}`);
}
/**
* Gets the actual size of a tile, e.g., width or height, taking rowspan or colspan into account.
* @param baseSize Base size of a 1x1 tile (as computed in getBaseTileSize).
* @param span The tile's rowspan or colspan.
* @return Size of the tile as a CSS calc() expression.
*/
getTileSize(baseSize: string, span: number): string {
return `(${baseSize} * ${span}) + (${span - 1} * ${this._gutterSize})`;
}
/**
* Sets the style properties to be applied to a tile for the given row and column index.
* @param tile Tile to which to apply the styling.
* @param rowIndex Index of the tile's row.
* @param colIndex Index of the tile's column.
*/
setStyle(tile: MatGridTile, rowIndex: number, colIndex: number): void {
// Percent of the available horizontal space that one column takes up.
let percentWidthPerTile = 100 / this._cols;
// Fraction of the vertical gutter size that each column takes up.
// For example, if there are 5 columns, each column uses 4/5 = 0.8 times the gutter width.
let gutterWidthFractionPerTile = (this._cols - 1) / this._cols;
this.setColStyles(tile, colIndex, percentWidthPerTile, gutterWidthFractionPerTile);
this.setRowStyles(tile, rowIndex, percentWidthPerTile, gutterWidthFractionPerTile);
}
/** Sets the horizontal placement of the tile in the list. */
setColStyles(tile: MatGridTile, colIndex: number, percentWidth: number, gutterWidth: number) {
// Base horizontal size of a column.
let baseTileWidth = this.getBaseTileSize(percentWidth, gutterWidth);
// The width and horizontal position of each tile is always calculated the same way, but the
// height and vertical position depends on the rowMode.
let side = this._direction === 'rtl' ? 'right' : 'left';
tile._setStyle(side, this.getTilePosition(baseTileWidth, colIndex));
tile._setStyle('width', calc(this.getTileSize(baseTileWidth, tile.colspan)));
}
/**
* Calculates the total size taken up by gutters across one axis of a list.
*/
getGutterSpan(): string {
return `${this._gutterSize} * (${this._rowspan} - 1)`;
}
/**
* Calculates the total size taken up by tiles across one axis of a list.
* @param tileHeight Height of the tile.
*/
getTileSpan(tileHeight: string): string {
return `${this._rowspan} * ${this.getTileSize(tileHeight, 1)}`;
}
/**
* Sets the vertical placement of the tile in the list.
* This method will be implemented by each type of TileStyler.
* @docs-private
*/
abstract setRowStyles(
tile: MatGridTile,
rowIndex: number,
percentWidth: number,
gutterWidth: number,
): void;
/**
* Calculates the computed height and returns the correct style property to set.
* This method can be implemented by each type of TileStyler.
* @docs-private
*/
getComputedHeight(): [string, string] | null {
return null;
}
/**
* Called when the tile styler is swapped out with a different one. To be used for cleanup.
* @param list Grid list that the styler was attached to.
* @docs-private
*/
abstract reset(list: TileStyleTarget): void;
}
/**
* This type of styler is instantiated when the user passes in a fixed row height.
* Example `<mat-grid-list cols="3" rowHeight="100px">`
* @docs-private
*/
export class FixedTileStyler extends TileStyler {
constructor(public fixedRowHeight: string) {
super();
}
override init(gutterSize: string, tracker: TileCoordinator, cols: number, direction: string) {
super.init(gutterSize, tracker, cols, direction);
this.fixedRowHeight = normalizeUnits(this.fixedRowHeight);
if (
!cssCalcAllowedValue.test(this.fixedRowHeight) &&
(typeof ngDevMode === 'undefined' || ngDevMode)
) {
throw Error(`Invalid value "${this.fixedRowHeight}" set as rowHeight.`);
}
}
override setRowStyles(tile: MatGridTile, rowIndex: number): void {
tile._setStyle('top', this.getTilePosition(this.fixedRowHeight, rowIndex));
tile._setStyle('height', calc(this.getTileSize(this.fixedRowHeight, tile.rowspan)));
}
override getComputedHeight(): [string, string] {
return ['height', calc(`${this.getTileSpan(this.fixedRowHeight)} + ${this.getGutterSpan()}`)];
}
override reset(list: TileStyleTarget) {
list._setListStyle(['height', null]);
if (list._tiles) {
list._tiles.forEach(tile => {
tile._setStyle('top', null);
tile._setStyle('height', null);
});
}
}
} | {
"end_byte": 7736,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/tile-styler.ts"
} |
components/src/material/grid-list/tile-styler.ts_7738_11040 | /**
* This type of styler is instantiated when the user passes in a width:height ratio
* for the row height. Example `<mat-grid-list cols="3" rowHeight="3:1">`
* @docs-private
*/
export class RatioTileStyler extends TileStyler {
/** Ratio width:height given by user to determine row height. */
rowHeightRatio: number;
baseTileHeight: string;
constructor(value: string) {
super();
this._parseRatio(value);
}
setRowStyles(
tile: MatGridTile,
rowIndex: number,
percentWidth: number,
gutterWidth: number,
): void {
let percentHeightPerTile = percentWidth / this.rowHeightRatio;
this.baseTileHeight = this.getBaseTileSize(percentHeightPerTile, gutterWidth);
// Use padding-top and margin-top to maintain the given aspect ratio, as
// a percentage-based value for these properties is applied versus the *width* of the
// containing block. See http://www.w3.org/TR/CSS2/box.html#margin-properties
tile._setStyle('marginTop', this.getTilePosition(this.baseTileHeight, rowIndex));
tile._setStyle('paddingTop', calc(this.getTileSize(this.baseTileHeight, tile.rowspan)));
}
override getComputedHeight(): [string, string] {
return [
'paddingBottom',
calc(`${this.getTileSpan(this.baseTileHeight)} + ${this.getGutterSpan()}`),
];
}
reset(list: TileStyleTarget) {
list._setListStyle(['paddingBottom', null]);
list._tiles.forEach(tile => {
tile._setStyle('marginTop', null);
tile._setStyle('paddingTop', null);
});
}
private _parseRatio(value: string): void {
const ratioParts = value.split(':');
if (ratioParts.length !== 2 && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error(`mat-grid-list: invalid ratio given for row-height: "${value}"`);
}
this.rowHeightRatio = parseFloat(ratioParts[0]) / parseFloat(ratioParts[1]);
}
}
/**
* This type of styler is instantiated when the user selects a "fit" row height mode.
* In other words, the row height will reflect the total height of the container divided
* by the number of rows. Example `<mat-grid-list cols="3" rowHeight="fit">`
*
* @docs-private
*/
export class FitTileStyler extends TileStyler {
setRowStyles(tile: MatGridTile, rowIndex: number): void {
// Percent of the available vertical space that one row takes up.
let percentHeightPerTile = 100 / this._rowspan;
// Fraction of the horizontal gutter size that each column takes up.
let gutterHeightPerTile = (this._rows - 1) / this._rows;
// Base vertical size of a column.
let baseTileHeight = this.getBaseTileSize(percentHeightPerTile, gutterHeightPerTile);
tile._setStyle('top', this.getTilePosition(baseTileHeight, rowIndex));
tile._setStyle('height', calc(this.getTileSize(baseTileHeight, tile.rowspan)));
}
reset(list: TileStyleTarget) {
if (list._tiles) {
list._tiles.forEach(tile => {
tile._setStyle('top', null);
tile._setStyle('height', null);
});
}
}
}
/** Wraps a CSS string in a calc function */
function calc(exp: string): string {
return `calc(${exp})`;
}
/** Appends pixels to a CSS string if no units are given. */
function normalizeUnits(value: string): string {
return value.match(/([A-Za-z%]+)$/) ? value : `${value}px`;
} | {
"end_byte": 11040,
"start_byte": 7738,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/tile-styler.ts"
} |
components/src/material/grid-list/testing/grid-list-harness-filters.ts_0_750 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {BaseHarnessFilters} from '@angular/cdk/testing';
/** A set of criteria that can be used to filter a list of `MatGridListHarness` instances. */
export interface GridListHarnessFilters extends BaseHarnessFilters {}
/** A set of criteria that can be used to filter a list of `MatTileHarness` instances. */
export interface GridTileHarnessFilters extends BaseHarnessFilters {
/** Text the grid-tile header should match. */
headerText?: string | RegExp;
/** Text the grid-tile footer should match. */
footerText?: string | RegExp;
}
| {
"end_byte": 750,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/testing/grid-list-harness-filters.ts"
} |
components/src/material/grid-list/testing/grid-list-harness.ts_0_3768 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentHarness, HarnessPredicate, parallel} from '@angular/cdk/testing';
import {ɵTileCoordinator as TileCoordinator} from '@angular/material/grid-list';
import {GridListHarnessFilters, GridTileHarnessFilters} from './grid-list-harness-filters';
import {MatGridTileHarness} from './grid-tile-harness';
/** Harness for interacting with a standard `MatGridList` in tests. */
export class MatGridListHarness extends ComponentHarness {
/** The selector for the host element of a `MatGridList` instance. */
static hostSelector = '.mat-grid-list';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatGridListHarness`
* that meets certain criteria.
* @param options Options for filtering which dialog instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: GridListHarnessFilters = {}): HarnessPredicate<MatGridListHarness> {
return new HarnessPredicate(MatGridListHarness, options);
}
/**
* Tile coordinator that is used by the "MatGridList" for computing
* positions of tiles. We leverage the coordinator to provide an API
* for retrieving tiles based on visual tile positions.
*/
private _tileCoordinator = new TileCoordinator();
/** Gets all tiles of the grid-list. */
async getTiles(filters: GridTileHarnessFilters = {}): Promise<MatGridTileHarness[]> {
return await this.locatorForAll(MatGridTileHarness.with(filters))();
}
/** Gets the amount of columns of the grid-list. */
async getColumns(): Promise<number> {
return Number(await (await this.host()).getAttribute('cols'));
}
/**
* Gets a tile of the grid-list that is located at the given location.
* @param row Zero-based row index.
* @param column Zero-based column index.
*/
async getTileAtPosition({
row,
column,
}: {
row: number;
column: number;
}): Promise<MatGridTileHarness> {
const [tileHarnesses, columns] = await parallel(() => [this.getTiles(), this.getColumns()]);
const tileSpans = tileHarnesses.map(t => parallel(() => [t.getColspan(), t.getRowspan()]));
const tiles = (await parallel(() => tileSpans)).map(([colspan, rowspan]) => ({
colspan,
rowspan,
}));
// Update the tile coordinator to reflect the current column amount and
// rendered tiles. We update upon every call of this method since we do not
// know if tiles have been added, removed or updated (in terms of rowspan/colspan).
this._tileCoordinator.update(columns, tiles);
// The tile coordinator respects the colspan and rowspan for calculating the positions
// of tiles, but it does not create multiple position entries if a tile spans over multiple
// columns or rows. We want to provide an API where developers can retrieve a tile based on
// any position that lies within the visual tile boundaries. For example: If a tile spans
// over two columns, then the same tile should be returned for either column indices.
for (let i = 0; i < this._tileCoordinator.positions.length; i++) {
const position = this._tileCoordinator.positions[i];
const {rowspan, colspan} = tiles[i];
// Return the tile harness if the given position visually resolves to the tile.
if (
column >= position.col &&
column <= position.col + colspan - 1 &&
row >= position.row &&
row <= position.row + rowspan - 1
) {
return tileHarnesses[i];
}
}
throw Error('Could not find tile at given position.');
}
}
| {
"end_byte": 3768,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/testing/grid-list-harness.ts"
} |
components/src/material/grid-list/testing/grid-tile-harness.ts_0_3192 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ContentContainerComponentHarness, HarnessPredicate} from '@angular/cdk/testing';
import {GridTileHarnessFilters} from './grid-list-harness-filters';
/** Selectors for the various `mat-grid-tile` sections that may contain user content. */
export enum MatGridTileSection {
HEADER = '.mat-grid-tile-header',
FOOTER = '.mat-grid-tile-footer',
}
/** Harness for interacting with a standard `MatGridTitle` in tests. */
export class MatGridTileHarness extends ContentContainerComponentHarness<MatGridTileSection> {
/** The selector for the host element of a `MatGridTile` instance. */
static hostSelector = '.mat-grid-tile';
/**
* Gets a `HarnessPredicate` that can be used to search for a `MatGridTileHarness`
* that meets certain criteria.
* @param options Options for filtering which dialog instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: GridTileHarnessFilters = {}): HarnessPredicate<MatGridTileHarness> {
return new HarnessPredicate(MatGridTileHarness, options)
.addOption('headerText', options.headerText, (harness, pattern) =>
HarnessPredicate.stringMatches(harness.getHeaderText(), pattern),
)
.addOption('footerText', options.footerText, (harness, pattern) =>
HarnessPredicate.stringMatches(harness.getFooterText(), pattern),
);
}
private _header = this.locatorForOptional(MatGridTileSection.HEADER);
private _footer = this.locatorForOptional(MatGridTileSection.FOOTER);
private _avatar = this.locatorForOptional('.mat-grid-avatar');
/** Gets the amount of rows that the grid-tile takes up. */
async getRowspan(): Promise<number> {
return Number(await (await this.host()).getAttribute('rowspan'));
}
/** Gets the amount of columns that the grid-tile takes up. */
async getColspan(): Promise<number> {
return Number(await (await this.host()).getAttribute('colspan'));
}
/** Whether the grid-tile has a header. */
async hasHeader(): Promise<boolean> {
return (await this._header()) !== null;
}
/** Whether the grid-tile has a footer. */
async hasFooter(): Promise<boolean> {
return (await this._footer()) !== null;
}
/** Whether the grid-tile has an avatar. */
async hasAvatar(): Promise<boolean> {
return (await this._avatar()) !== null;
}
/** Gets the text of the header if present. */
async getHeaderText(): Promise<string | null> {
// For performance reasons, we do not use "hasHeader" as
// we would then need to query twice for the header.
const headerEl = await this._header();
return headerEl ? headerEl.text() : null;
}
/** Gets the text of the footer if present. */
async getFooterText(): Promise<string | null> {
// For performance reasons, we do not use "hasFooter" as
// we would then need to query twice for the footer.
const headerEl = await this._footer();
return headerEl ? headerEl.text() : null;
}
}
| {
"end_byte": 3192,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/testing/grid-tile-harness.ts"
} |
components/src/material/grid-list/testing/public-api.ts_0_323 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './grid-tile-harness';
export * from './grid-list-harness';
export * from './grid-list-harness-filters';
| {
"end_byte": 323,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/testing/public-api.ts"
} |
components/src/material/grid-list/testing/BUILD.bazel_0_797 | 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/grid-list",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/testing",
"//src/cdk/testing/private",
"//src/cdk/testing/testbed",
"//src/material/grid-list",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 797,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/testing/BUILD.bazel"
} |
components/src/material/grid-list/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/grid-list/testing/index.ts"
} |
components/src/material/grid-list/testing/grid-list-harness.spec.ts_0_7862 | 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 {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatGridListModule} from '@angular/material/grid-list';
import {MatGridListHarness} from './grid-list-harness';
import {MatGridTileHarness} from './grid-tile-harness';
describe('MatGridListHarness', () => {
let fixture: ComponentFixture<GridListHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatGridListModule, NoopAnimationsModule, GridListHarnessTest],
});
fixture = TestBed.createComponent(GridListHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
});
it('should be able to load grid-list harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatGridListHarness);
expect(harnesses.length).toBe(2);
});
it('should be able to load grid-tile harnesses', async () => {
const harnesses = await loader.getAllHarnesses(MatGridTileHarness);
expect(harnesses.length).toBe(8);
});
it('should be able to load grid-tile harness by header text', async () => {
const harnesses = await loader.getAllHarnesses(MatGridTileHarness.with({headerText: /Tile 3/}));
expect(harnesses.length).toBe(1);
expect(await harnesses[0].getFooterText()).toBe('Tile 3 footer');
});
it('should be able to load grid-tile harness by footer text', async () => {
const harnesses = await loader.getAllHarnesses(
MatGridTileHarness.with({footerText: 'Tile 3 footer'}),
);
expect(harnesses.length).toBe(1);
expect(await harnesses[0].getHeaderText()).toBe('Tile 3');
});
it('should be able to get all tiles of a grid-list', async () => {
const gridList = await loader.getHarness(MatGridListHarness.with({selector: '#second'}));
const tiles = await gridList.getTiles();
expect(tiles.length).toBe(4);
});
it('should be able to get tiles of grid-list with filters', async () => {
const gridList = await loader.getHarness(MatGridListHarness.with({selector: '#second'}));
const tiles = await gridList.getTiles({headerText: /Tile [34]/});
expect(tiles.length).toBe(2);
});
it('should be able to get amount of columns of grid-list', async () => {
const gridLists = await loader.getAllHarnesses(MatGridListHarness);
expect(await gridLists[0].getColumns()).toBe(4);
expect(await gridLists[1].getColumns()).toBe(2);
fixture.componentInstance.columns.set(3);
expect(await gridLists[0].getColumns()).toBe(3);
});
it('should be able to get tile by position', async () => {
const gridList = await loader.getHarness(MatGridListHarness);
const tiles = await parallel(() => [
gridList.getTileAtPosition({row: 0, column: 0}),
gridList.getTileAtPosition({row: 0, column: 1}),
gridList.getTileAtPosition({row: 1, column: 0}),
]);
expect(await tiles[0].getHeaderText()).toBe('One');
expect(await tiles[1].getHeaderText()).toBe('Two');
expect(await tiles[2].getHeaderText()).toBe('Four (second row)');
});
it('should be able to get tile by position with respect to tile span', async () => {
const gridList = await loader.getHarness(MatGridListHarness);
const tiles = await parallel(() => [
gridList.getTileAtPosition({row: 0, column: 2}),
gridList.getTileAtPosition({row: 0, column: 3}),
]);
expect(await tiles[0].getHeaderText()).toBe('Three');
expect(await tiles[1].getHeaderText()).toBe('Three');
await expectAsync(gridList.getTileAtPosition({row: 2, column: 0})).toBeRejectedWithError(
/Could not find tile/,
);
// Update the fourth tile to span over two rows. The previous position
// should now be valid and the fourth tile should be returned.
fixture.componentInstance.tile4Rowspan.set(2);
const foundTile = await gridList.getTileAtPosition({row: 2, column: 0});
expect(await foundTile.getHeaderText()).toBe('Four (second and third row)');
});
it('should be able to check whether tile has header', async () => {
const tiles = await loader.getAllHarnesses(MatGridTileHarness);
expect(await tiles[0].hasHeader()).toBe(true);
expect(await tiles[4].hasHeader()).toBe(false);
expect(await (await tiles[4].host()).text()).toBe('Tile 1 (no header, no footer)');
});
it('should be able to check whether tile has footer', async () => {
const tiles = await loader.getAllHarnesses(MatGridTileHarness);
expect(await tiles[0].hasFooter()).toBe(false);
expect(await tiles[6].hasFooter()).toBe(true);
expect(await tiles[6].getFooterText()).toBe('Tile 3 footer');
});
it('should be able to check whether tile has avatar', async () => {
const tiles = await loader.getAllHarnesses(MatGridTileHarness);
expect(await tiles[0].hasAvatar()).toBe(false);
expect(await tiles[1].hasAvatar()).toBe(true);
});
it('should be able to get rowspan of tile', async () => {
const tiles = await loader.getAllHarnesses(MatGridTileHarness);
expect(await tiles[0].getRowspan()).toBe(1);
expect(await tiles[3].getRowspan()).toBe(1);
fixture.componentInstance.tile4Rowspan.set(10);
expect(await tiles[3].getRowspan()).toBe(10);
});
it('should be able to get colspan of tile', async () => {
const tiles = await loader.getAllHarnesses(MatGridTileHarness);
expect(await tiles[0].getColspan()).toBe(1);
expect(await tiles[2].getColspan()).toBe(2);
});
it('should be able to get header text of tile', async () => {
const tiles = await loader.getAllHarnesses(MatGridTileHarness);
expect(await tiles[0].getHeaderText()).toBe('One');
fixture.componentInstance.firstTileText.set('updated');
expect(await tiles[0].getHeaderText()).toBe('updated');
});
it('should be able to get footer text of tile', async () => {
const tiles = await loader.getAllHarnesses(MatGridTileHarness);
expect(await tiles[0].getFooterText()).toBe(null);
fixture.componentInstance.showFooter.set(true);
expect(await tiles[0].getFooterText()).toBe('Footer');
});
});
@Component({
template: `
<mat-grid-list [cols]="columns()">
<mat-grid-tile>
<mat-grid-tile-header>{{firstTileText()}}</mat-grid-tile-header>
@if (showFooter()) {
<mat-grid-tile-footer>Footer</mat-grid-tile-footer>
}
</mat-grid-tile>
<mat-grid-tile>
<mat-grid-tile-header>Two</mat-grid-tile-header>
<div matGridAvatar class="css-rendered-avatar"></div>
</mat-grid-tile>
<mat-grid-tile colspan="2">
<mat-grid-tile-header>Three</mat-grid-tile-header>
</mat-grid-tile>
<mat-grid-tile [rowspan]="tile4Rowspan()">
<mat-grid-tile-header>
Four (second {{tile4Rowspan() === 2 ? 'and third ' : ''}}row)
</mat-grid-tile-header>
</mat-grid-tile>
</mat-grid-list>
<mat-grid-list id="second" cols="2" rowHeight="100px">
<mat-grid-tile>Tile 1 (no header, no footer)</mat-grid-tile>
<mat-grid-tile>
<mat-grid-tile-header>Tile 2</mat-grid-tile-header>
</mat-grid-tile>
<mat-grid-tile colspan="2">
<mat-grid-tile-header>Tile 3</mat-grid-tile-header>
<mat-grid-tile-footer>Tile 3 footer</mat-grid-tile-footer>
</mat-grid-tile>
<mat-grid-tile>
<mat-grid-tile-header>Tile 4</mat-grid-tile-header>
</mat-grid-tile>
</mat-grid-list>
`,
standalone: true,
imports: [MatGridListModule],
})
class GridListHarnessTest {
firstTileText = signal('One');
showFooter = signal(false);
columns = signal(4);
tile4Rowspan = signal(1);
}
| {
"end_byte": 7862,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/grid-list/testing/grid-list-harness.spec.ts"
} |
components/src/material/bottom-sheet/bottom-sheet-container.ts_0_3948 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {AnimationEvent} from '@angular/animations';
import {CdkDialogContainer} from '@angular/cdk/dialog';
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';
import {
ChangeDetectionStrategy,
Component,
EventEmitter,
OnDestroy,
ViewEncapsulation,
inject,
} from '@angular/core';
import {Subscription} from 'rxjs';
import {matBottomSheetAnimations} from './bottom-sheet-animations';
import {CdkPortalOutlet} from '@angular/cdk/portal';
/**
* Internal component that wraps user-provided bottom sheet content.
* @docs-private
*/
@Component({
selector: 'mat-bottom-sheet-container',
templateUrl: 'bottom-sheet-container.html',
styleUrl: 'bottom-sheet-container.css',
// In Ivy embedded views will be change detected from their declaration place, rather than where
// they were stamped out. This means that we can't have the bottom sheet container be OnPush,
// because it might cause the sheets that were opened from a template not to be out of date.
// tslint:disable-next-line:validate-decorators
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.None,
animations: [matBottomSheetAnimations.bottomSheetState],
host: {
'class': 'mat-bottom-sheet-container',
'tabindex': '-1',
'[attr.role]': '_config.role',
'[attr.aria-modal]': '_config.ariaModal',
'[attr.aria-label]': '_config.ariaLabel',
'[@state]': '_animationState',
'(@state.start)': '_onAnimationStart($event)',
'(@state.done)': '_onAnimationDone($event)',
},
imports: [CdkPortalOutlet],
})
export class MatBottomSheetContainer extends CdkDialogContainer implements OnDestroy {
private _breakpointSubscription: Subscription;
/** The state of the bottom sheet animations. */
_animationState: 'void' | 'visible' | 'hidden' = 'void';
/** Emits whenever the state of the animation changes. */
_animationStateChanged = new EventEmitter<AnimationEvent>();
/** Whether the component has been destroyed. */
private _destroyed: boolean;
constructor(...args: unknown[]);
constructor() {
super();
const breakpointObserver = inject(BreakpointObserver);
this._breakpointSubscription = breakpointObserver
.observe([Breakpoints.Medium, Breakpoints.Large, Breakpoints.XLarge])
.subscribe(() => {
const classList = (this._elementRef.nativeElement as HTMLElement).classList;
classList.toggle(
'mat-bottom-sheet-container-medium',
breakpointObserver.isMatched(Breakpoints.Medium),
);
classList.toggle(
'mat-bottom-sheet-container-large',
breakpointObserver.isMatched(Breakpoints.Large),
);
classList.toggle(
'mat-bottom-sheet-container-xlarge',
breakpointObserver.isMatched(Breakpoints.XLarge),
);
});
}
/** Begin animation of bottom sheet entrance into view. */
enter(): void {
if (!this._destroyed) {
this._animationState = 'visible';
this._changeDetectorRef.markForCheck();
this._changeDetectorRef.detectChanges();
}
}
/** Begin animation of the bottom sheet exiting from view. */
exit(): void {
if (!this._destroyed) {
this._animationState = 'hidden';
this._changeDetectorRef.markForCheck();
}
}
override ngOnDestroy() {
super.ngOnDestroy();
this._breakpointSubscription.unsubscribe();
this._destroyed = true;
}
_onAnimationDone(event: AnimationEvent) {
if (event.toState === 'visible') {
this._trapFocus();
}
this._animationStateChanged.emit(event);
}
_onAnimationStart(event: AnimationEvent) {
this._animationStateChanged.emit(event);
}
protected override _captureInitialFocus(): void {}
}
| {
"end_byte": 3948,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet-container.ts"
} |
components/src/material/bottom-sheet/bottom-sheet-config.ts_0_2652 | /**
* @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 {Direction} from '@angular/cdk/bidi';
import {ScrollStrategy} from '@angular/cdk/overlay';
import {InjectionToken, ViewContainerRef} from '@angular/core';
/** Options for where to set focus to automatically on dialog open */
export type AutoFocusTarget = 'dialog' | 'first-tabbable' | 'first-heading';
/** Injection token that can be used to access the data that was passed in to a bottom sheet. */
export const MAT_BOTTOM_SHEET_DATA = new InjectionToken<any>('MatBottomSheetData');
/**
* Configuration used when opening a bottom sheet.
*/
export class MatBottomSheetConfig<D = any> {
/** The view container to place the overlay for the bottom sheet into. */
viewContainerRef?: ViewContainerRef;
/** Extra CSS classes to be added to the bottom sheet container. */
panelClass?: string | string[];
/** Text layout direction for the bottom sheet. */
direction?: Direction;
/** Data being injected into the child component. */
data?: D | null = null;
/** Whether the bottom sheet has a backdrop. */
hasBackdrop?: boolean = true;
/** Custom class for the backdrop. */
backdropClass?: string;
/** Whether the user can use escape or clicking outside to close the bottom sheet. */
disableClose?: boolean = false;
/** Aria label to assign to the bottom sheet element. */
ariaLabel?: string | null = null;
/** Whether this is a modal bottom sheet. Used to set the `aria-modal` attribute. */
ariaModal?: boolean = true;
/**
* Whether the bottom sheet should close when the user goes backwards/forwards in history.
* Note that this usually doesn't include clicking on links (unless the user is using
* the `HashLocationStrategy`).
*/
closeOnNavigation?: boolean = true;
// Note that this is set to 'dialog' by default, because while the a11y recommendations
// are to focus the first focusable element, doing so prevents screen readers from reading out the
// rest of the bottom sheet content.
/**
* Where the bottom sheet should focus on open.
* @breaking-change 14.0.0 Remove boolean option from autoFocus. Use string or
* AutoFocusTarget instead.
*/
autoFocus?: AutoFocusTarget | string | boolean = 'dialog';
/**
* Whether the bottom sheet should restore focus to the
* previously-focused element, after it's closed.
*/
restoreFocus?: boolean = true;
/** Scroll strategy to be used for the bottom sheet. */
scrollStrategy?: ScrollStrategy;
}
| {
"end_byte": 2652,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet-config.ts"
} |
components/src/material/bottom-sheet/bottom-sheet.spec.ts_0_1176 | import {Directionality} from '@angular/cdk/bidi';
import {A, ESCAPE} from '@angular/cdk/keycodes';
import {OverlayContainer, ScrollStrategy} from '@angular/cdk/overlay';
import {_supportsShadowDom} from '@angular/cdk/platform';
import {ViewportRuler} from '@angular/cdk/scrolling';
import {
createKeyboardEvent,
dispatchEvent,
dispatchKeyboardEvent,
} from '@angular/cdk/testing/private';
import {Location} from '@angular/common';
import {SpyLocation} from '@angular/common/testing';
import {
Component,
ComponentRef,
Directive,
Injector,
TemplateRef,
ViewChild,
ViewContainerRef,
ViewEncapsulation,
inject,
} from '@angular/core';
import {
ComponentFixture,
TestBed,
fakeAsync,
flush,
flushMicrotasks,
tick,
} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MAT_BOTTOM_SHEET_DEFAULT_OPTIONS, MatBottomSheet} from './bottom-sheet';
import {MAT_BOTTOM_SHEET_DATA, MatBottomSheetConfig} from './bottom-sheet-config';
import {MatBottomSheetModule} from './bottom-sheet-module';
import {MatBottomSheetRef} from './bottom-sheet-ref'; | {
"end_byte": 1176,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet.spec.ts"
} |
components/src/material/bottom-sheet/bottom-sheet.spec.ts_1178_10781 | describe('MatBottomSheet', () => {
let bottomSheet: MatBottomSheet;
let overlayContainerElement: HTMLElement;
let viewportRuler: ViewportRuler;
let testViewContainerRef: ViewContainerRef;
let viewContainerFixture: ComponentFixture<ComponentWithChildViewContainer>;
let mockLocation: SpyLocation;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [
MatBottomSheetModule,
NoopAnimationsModule,
ComponentWithChildViewContainer,
ComponentWithTemplateRef,
ContentElementDialog,
PizzaMsg,
TacoMsg,
DirectiveWithViewContainer,
BottomSheetWithInjectedData,
ShadowDomComponent,
],
providers: [{provide: Location, useClass: SpyLocation}],
});
bottomSheet = TestBed.inject(MatBottomSheet);
viewportRuler = TestBed.inject(ViewportRuler);
overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement();
mockLocation = TestBed.inject(Location) as SpyLocation;
viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer);
viewContainerFixture.detectChanges();
testViewContainerRef = viewContainerFixture.componentInstance.childViewContainer;
}));
it('should open a bottom sheet with a component', () => {
const bottomSheetRef = bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
viewContainerFixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('Pizza');
expect(bottomSheetRef.instance instanceof PizzaMsg).toBe(true);
expect(bottomSheetRef.componentRef instanceof ComponentRef).toBe(true);
expect(bottomSheetRef.instance.bottomSheetRef).toBe(bottomSheetRef);
});
it('should open a bottom sheet with a template', () => {
const templateRefFixture = TestBed.createComponent(ComponentWithTemplateRef);
templateRefFixture.componentInstance.localValue = 'Bees';
templateRefFixture.detectChanges();
const bottomSheetRef = bottomSheet.open(templateRefFixture.componentInstance.templateRef, {
data: {value: 'Knees'},
});
viewContainerFixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('Cheese Bees Knees');
expect(templateRefFixture.componentInstance.bottomSheetRef).toBe(bottomSheetRef);
});
it('should position the bottom sheet at the bottom center of the screen', () => {
bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
viewContainerFixture.detectChanges();
const containerElement = overlayContainerElement.querySelector('mat-bottom-sheet-container')!;
const containerRect = containerElement.getBoundingClientRect();
const viewportSize = viewportRuler.getViewportSize();
expect(Math.floor(containerRect.bottom)).toBe(Math.floor(viewportSize.height));
expect(Math.floor(containerRect.left + containerRect.width / 2)).toBe(
Math.floor(viewportSize.width / 2),
);
});
it('should emit when the bottom sheet opening animation is complete', fakeAsync(() => {
const bottomSheetRef = bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
const spy = jasmine.createSpy('afterOpened spy');
bottomSheetRef.afterOpened().subscribe(spy);
viewContainerFixture.detectChanges();
// callback should not be called before animation is complete
expect(spy).not.toHaveBeenCalled();
flush();
expect(spy).toHaveBeenCalled();
}));
it('should use the correct injector', () => {
const bottomSheetRef = bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
viewContainerFixture.detectChanges();
const injector = bottomSheetRef.instance.injector;
expect(bottomSheetRef.instance.bottomSheetRef).toBe(bottomSheetRef);
expect(injector.get<DirectiveWithViewContainer>(DirectiveWithViewContainer)).toBeTruthy();
});
it('should open a bottom sheet with a component and no ViewContainerRef', () => {
const bottomSheetRef = bottomSheet.open(PizzaMsg);
viewContainerFixture.detectChanges();
expect(overlayContainerElement.textContent).toContain('Pizza');
expect(bottomSheetRef.instance instanceof PizzaMsg).toBe(true);
expect(bottomSheetRef.instance.bottomSheetRef).toBe(bottomSheetRef);
});
it('should apply the correct role to the container element', () => {
bottomSheet.open(PizzaMsg);
viewContainerFixture.detectChanges();
const containerElement = overlayContainerElement.querySelector('mat-bottom-sheet-container')!;
expect(containerElement.getAttribute('role')).toBe('dialog');
expect(containerElement.getAttribute('aria-modal')).toBe('true');
});
it('should close a bottom sheet via the escape key', fakeAsync(() => {
bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
const event = dispatchKeyboardEvent(document.body, 'keydown', ESCAPE);
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeNull();
expect(event.defaultPrevented).toBe(true);
}));
it('should not close a bottom sheet via the escape key with a modifier', fakeAsync(() => {
bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
const event = createKeyboardEvent('keydown', ESCAPE, undefined, {alt: true});
dispatchEvent(document.body, event);
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeTruthy();
expect(event.defaultPrevented).toBe(false);
}));
it('should close when clicking on the overlay backdrop', fakeAsync(() => {
bottomSheet.open(PizzaMsg, {
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
const backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement;
backdrop.click();
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeFalsy();
}));
it('should dispose of bottom sheet if view container is destroyed while animating', fakeAsync(() => {
const bottomSheetRef = bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
bottomSheetRef.dismiss();
viewContainerFixture.detectChanges();
viewContainerFixture.destroy();
flush();
expect(overlayContainerElement.querySelector('mat-dialog-container')).toBeNull();
}));
it('should emit the backdropClick stream when clicking on the overlay backdrop', fakeAsync(() => {
const bottomSheetRef = bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
const spy = jasmine.createSpy('backdropClick spy');
bottomSheetRef.backdropClick().subscribe(spy);
viewContainerFixture.detectChanges();
const backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement;
backdrop.click();
expect(spy).toHaveBeenCalledTimes(1);
viewContainerFixture.detectChanges();
flush();
// Additional clicks after the bottom sheet was closed should not be emitted
backdrop.click();
expect(spy).toHaveBeenCalledTimes(1);
}));
it('should emit the keyboardEvent stream when key events target the overlay', fakeAsync(() => {
const bottomSheetRef = bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
const spy = jasmine.createSpy('keyboardEvent spy');
bottomSheetRef.keydownEvents().subscribe(spy);
viewContainerFixture.detectChanges();
flush();
const backdrop = overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement;
const container = overlayContainerElement.querySelector(
'mat-bottom-sheet-container',
) as HTMLElement;
dispatchKeyboardEvent(document.body, 'keydown', A);
dispatchKeyboardEvent(backdrop, 'keydown', A);
dispatchKeyboardEvent(container, 'keydown', A);
expect(spy).toHaveBeenCalledTimes(3);
}));
it('should allow setting the layout direction', () => {
bottomSheet.open(PizzaMsg, {direction: 'rtl'});
viewContainerFixture.detectChanges();
const overlayPane = overlayContainerElement.querySelector('.cdk-global-overlay-wrapper')!;
expect(overlayPane.getAttribute('dir')).toBe('rtl');
});
it('should inject the correct direction in the instantiated component', () => {
const bottomSheetRef = bottomSheet.open(PizzaMsg, {direction: 'rtl'});
viewContainerFixture.detectChanges();
expect(bottomSheetRef.instance.directionality.value).toBe('rtl');
});
it('should fall back to injecting the global direction if none is passed by the config', () => {
const bottomSheetRef = bottomSheet.open(PizzaMsg, {});
viewContainerFixture.detectChanges();
expect(bottomSheetRef.instance.directionality.value).toBe('ltr');
});
it('should be able to set a custom panel class', () => {
bottomSheet.open(PizzaMsg, {
panelClass: 'custom-panel-class',
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
expect(overlayContainerElement.querySelector('.custom-panel-class')).toBeTruthy();
});
it('should be able to set a custom aria-label', () => {
bottomSheet.open(PizzaMsg, {
ariaLabel: 'Hello there',
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
const container = overlayContainerElement.querySelector('mat-bottom-sheet-container')!;
expect(container.getAttribute('aria-label')).toBe('Hello there');
}); | {
"end_byte": 10781,
"start_byte": 1178,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet.spec.ts"
} |
components/src/material/bottom-sheet/bottom-sheet.spec.ts_10785_20134 | it('should be able to get dismissed through the service', fakeAsync(() => {
bottomSheet.open(PizzaMsg);
viewContainerFixture.detectChanges();
expect(overlayContainerElement.childElementCount).toBeGreaterThan(0);
bottomSheet.dismiss();
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.childElementCount).toBe(0);
}));
it('should dismiss the bottom sheet when the service is destroyed', fakeAsync(() => {
bottomSheet.open(PizzaMsg);
viewContainerFixture.detectChanges();
expect(overlayContainerElement.childElementCount).toBeGreaterThan(0);
bottomSheet.ngOnDestroy();
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.childElementCount).toBe(0);
}));
it('should open a new bottom sheet after dismissing a previous sheet', fakeAsync(() => {
const config: MatBottomSheetConfig = {viewContainerRef: testViewContainerRef};
let bottomSheetRef: MatBottomSheetRef<any> = bottomSheet.open(PizzaMsg, config);
viewContainerFixture.detectChanges();
bottomSheetRef.dismiss();
viewContainerFixture.detectChanges();
// Wait for the dismiss animation to finish.
flush();
bottomSheetRef = bottomSheet.open(TacoMsg, config);
viewContainerFixture.detectChanges();
// Wait for the open animation to finish.
flush();
expect(bottomSheetRef.containerInstance._animationState)
.withContext(`Expected the animation state would be 'visible'.`)
.toBe('visible');
}));
it('should remove past bottom sheets when opening new ones', fakeAsync(() => {
bottomSheet.open(PizzaMsg);
viewContainerFixture.detectChanges();
bottomSheet.open(TacoMsg);
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.textContent).toContain('Taco');
}));
it('should not throw when opening multiple bottom sheet in quick succession', fakeAsync(() => {
expect(() => {
for (let i = 0; i < 3; i++) {
bottomSheet.open(PizzaMsg);
viewContainerFixture.detectChanges();
}
flush();
}).not.toThrow();
}));
it('should remove bottom sheet if another is shown while its still animating open', fakeAsync(() => {
bottomSheet.open(PizzaMsg);
viewContainerFixture.detectChanges();
bottomSheet.open(TacoMsg);
viewContainerFixture.detectChanges();
tick();
expect(overlayContainerElement.textContent).toContain('Taco');
tick(500);
}));
it('should emit after being dismissed', fakeAsync(() => {
const bottomSheetRef = bottomSheet.open(PizzaMsg);
const spy = jasmine.createSpy('afterDismissed spy');
bottomSheetRef.afterDismissed().subscribe(spy);
viewContainerFixture.detectChanges();
bottomSheetRef.dismiss();
viewContainerFixture.detectChanges();
flush();
expect(spy).toHaveBeenCalledTimes(1);
}));
it('should be able to pass a result back to the dismissed stream', fakeAsync(() => {
const bottomSheetRef = bottomSheet.open<PizzaMsg, any, number>(PizzaMsg);
const spy = jasmine.createSpy('afterDismissed spy');
bottomSheetRef.afterDismissed().subscribe(spy);
viewContainerFixture.detectChanges();
bottomSheetRef.dismiss(1337);
viewContainerFixture.detectChanges();
flush();
expect(spy).toHaveBeenCalledWith(1337);
}));
it('should be able to pass data when dismissing through the service', fakeAsync(() => {
const bottomSheetRef = bottomSheet.open<PizzaMsg, any, number>(PizzaMsg);
const spy = jasmine.createSpy('afterDismissed spy');
bottomSheetRef.afterDismissed().subscribe(spy);
viewContainerFixture.detectChanges();
bottomSheet.dismiss(1337);
viewContainerFixture.detectChanges();
flush();
expect(spy).toHaveBeenCalledWith(1337);
}));
it('should close the bottom sheet when going forwards/backwards in history', fakeAsync(() => {
bottomSheet.open(PizzaMsg);
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeTruthy();
mockLocation.simulateUrlPop('');
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeFalsy();
}));
it('should close the bottom sheet when the location hash changes', fakeAsync(() => {
bottomSheet.open(PizzaMsg);
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeTruthy();
mockLocation.simulateHashChange('');
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeFalsy();
}));
it('should allow the consumer to disable closing a bottom sheet on navigation', fakeAsync(() => {
bottomSheet.open(PizzaMsg, {closeOnNavigation: false});
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeTruthy();
mockLocation.simulateUrlPop('');
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeTruthy();
}));
it('should be able to attach a custom scroll strategy', () => {
const scrollStrategy: ScrollStrategy = {
attach: () => {},
enable: jasmine.createSpy('scroll strategy enable spy'),
disable: () => {},
};
bottomSheet.open(PizzaMsg, {scrollStrategy});
expect(scrollStrategy.enable).toHaveBeenCalled();
});
describe('passing in data', () => {
it('should be able to pass in data', () => {
const config = {
data: {
stringParam: 'hello',
dateParam: new Date(),
},
};
const instance = bottomSheet.open(BottomSheetWithInjectedData, config).instance;
expect(instance.data.stringParam).toBe(config.data.stringParam);
expect(instance.data.dateParam).toBe(config.data.dateParam);
});
it('should default to null if no data is passed', () => {
expect(() => {
const bottomSheetRef = bottomSheet.open(BottomSheetWithInjectedData);
expect(bottomSheetRef.instance.data).toBeNull();
}).not.toThrow();
});
});
describe('disableClose option', () => {
it('should prevent closing via clicks on the backdrop', fakeAsync(() => {
bottomSheet.open(PizzaMsg, {
disableClose: true,
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
const backdrop = overlayContainerElement.querySelector(
'.cdk-overlay-backdrop',
) as HTMLElement;
backdrop.click();
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeTruthy();
}));
it('should prevent closing via the escape key', fakeAsync(() => {
bottomSheet.open(PizzaMsg, {
disableClose: true,
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
dispatchKeyboardEvent(document.body, 'keydown', ESCAPE);
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeTruthy();
}));
it('should allow for the disableClose option to be updated while open', fakeAsync(() => {
const bottomSheetRef = bottomSheet.open(PizzaMsg, {
disableClose: true,
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
const backdrop = overlayContainerElement.querySelector(
'.cdk-overlay-backdrop',
) as HTMLElement;
backdrop.click();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeTruthy();
bottomSheetRef.disableClose = false;
backdrop.click();
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeFalsy();
}));
});
describe('hasBackdrop option', () => {
it('should have a backdrop', () => {
bottomSheet.open(PizzaMsg, {
hasBackdrop: true,
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeTruthy();
});
it('should not have a backdrop', () => {
bottomSheet.open(PizzaMsg, {
hasBackdrop: false,
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeFalsy();
});
});
describe('backdropClass option', () => {
it('should have default backdrop class', () => {
bottomSheet.open(PizzaMsg, {
backdropClass: '',
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
expect(overlayContainerElement.querySelector('.cdk-overlay-dark-backdrop')).toBeTruthy();
});
it('should have custom backdrop class', () => {
bottomSheet.open(PizzaMsg, {
backdropClass: 'custom-backdrop-class',
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
expect(overlayContainerElement.querySelector('.custom-backdrop-class')).toBeTruthy();
});
}); | {
"end_byte": 20134,
"start_byte": 10785,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet.spec.ts"
} |
components/src/material/bottom-sheet/bottom-sheet.spec.ts_20138_28343 | describe('focus management', () => {
// When testing focus, all of the elements must be in the DOM.
beforeEach(() => document.body.appendChild(overlayContainerElement));
afterEach(() => overlayContainerElement.remove());
it('should focus the bottom sheet container by default', fakeAsync(() => {
bottomSheet.open(PizzaMsg, {
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
flush();
viewContainerFixture.detectChanges();
expect(document.activeElement!.tagName)
.withContext('Expected bottom sheet container to be focused.')
.toBe('MAT-BOTTOM-SHEET-CONTAINER');
}));
it('should create a focus trap if autoFocus is disabled', fakeAsync(() => {
bottomSheet.open(PizzaMsg, {
viewContainerRef: testViewContainerRef,
autoFocus: false,
});
viewContainerFixture.detectChanges();
flush();
const focusTrapAnchors = overlayContainerElement.querySelectorAll('.cdk-focus-trap-anchor');
expect(focusTrapAnchors.length).toBeGreaterThan(0);
}));
it(
'should focus the first tabbable element of the bottom sheet on open when' +
'autoFocus is set to "first-tabbable"',
async () => {
bottomSheet.open(PizzaMsg, {
viewContainerRef: testViewContainerRef,
autoFocus: 'first-tabbable',
});
viewContainerFixture.detectChanges();
await viewContainerFixture.whenStable();
viewContainerFixture.detectChanges();
expect(document.activeElement!.tagName)
.withContext('Expected first tabbable element (input) in the dialog to be focused.')
.toBe('INPUT');
},
);
it(
'should focus the bottom sheet element on open when autoFocus is set to ' +
'"dialog" (the default)',
fakeAsync(() => {
bottomSheet.open(PizzaMsg, {
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
flush();
viewContainerFixture.detectChanges();
let container = overlayContainerElement.querySelector(
'.mat-bottom-sheet-container',
) as HTMLInputElement;
expect(document.activeElement)
.withContext('Expected container to be focused on open')
.toBe(container);
}),
);
it(
'should focus the bottom sheet element on open when autoFocus is set to ' + '"first-heading"',
fakeAsync(() => {
bottomSheet.open(ContentElementDialog, {
viewContainerRef: testViewContainerRef,
autoFocus: 'first-heading',
});
viewContainerFixture.detectChanges();
flush();
viewContainerFixture.detectChanges();
let firstHeader = overlayContainerElement.querySelector(
'h1[tabindex="-1"]',
) as HTMLInputElement;
expect(document.activeElement)
.withContext('Expected first header to be focused on open')
.toBe(firstHeader);
}),
);
it(
'should focus the first element that matches the css selector on open when ' +
'autoFocus is set to a css selector',
fakeAsync(() => {
bottomSheet.open(ContentElementDialog, {
viewContainerRef: testViewContainerRef,
autoFocus: 'p',
});
viewContainerFixture.detectChanges();
flush();
viewContainerFixture.detectChanges();
let firstParagraph = overlayContainerElement.querySelector(
'p[tabindex="-1"]',
) as HTMLInputElement;
expect(document.activeElement)
.withContext('Expected first paragraph to be focused on open')
.toBe(firstParagraph);
}),
);
it('should re-focus trigger element when bottom sheet closes', fakeAsync(() => {
const button = document.createElement('button');
button.id = 'bottom-sheet-trigger';
document.body.appendChild(button);
button.focus();
const bottomSheetRef = bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
flush();
viewContainerFixture.detectChanges();
flush();
viewContainerFixture.detectChanges();
expect(document.activeElement!.id).not.toBe(
'bottom-sheet-trigger',
'Expected the focus to change when sheet was opened.',
);
bottomSheetRef.dismiss();
expect(document.activeElement!.id).not.toBe(
'bottom-sheet-trigger',
'Expcted the focus not to have changed before the animation finishes.',
);
flush();
viewContainerFixture.detectChanges();
tick(500);
expect(document.activeElement!.id)
.withContext('Expected that the trigger was refocused after the sheet is closed.')
.toBe('bottom-sheet-trigger');
button.remove();
}));
it('should be able to disable focus restoration', fakeAsync(() => {
const button = document.createElement('button');
button.id = 'bottom-sheet-trigger';
document.body.appendChild(button);
button.focus();
const bottomSheetRef = bottomSheet.open(PizzaMsg, {
viewContainerRef: testViewContainerRef,
restoreFocus: false,
});
flush();
viewContainerFixture.detectChanges();
flush();
viewContainerFixture.detectChanges();
expect(document.activeElement!.id).not.toBe(
'bottom-sheet-trigger',
'Expected the focus to change when sheet was opened.',
);
bottomSheetRef.dismiss();
expect(document.activeElement!.id).not.toBe(
'bottom-sheet-trigger',
'Expcted the focus not to have changed before the animation finishes.',
);
flush();
viewContainerFixture.detectChanges();
tick(500);
expect(document.activeElement!.id).not.toBe(
'bottom-sheet-trigger',
'Expected the trigger not to be refocused on close.',
);
button.remove();
}));
it('should not move focus if it was moved outside the sheet while animating', fakeAsync(() => {
// Create a element that has focus before the bottom sheet is opened.
const button = document.createElement('button');
const otherButton = document.createElement('button');
const body = document.body;
button.id = 'bottom-sheet-trigger';
otherButton.id = 'other-button';
body.appendChild(button);
body.appendChild(otherButton);
button.focus();
const bottomSheetRef = bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
flush();
viewContainerFixture.detectChanges();
flush();
viewContainerFixture.detectChanges();
expect(document.activeElement!.id).not.toBe(
'bottom-sheet-trigger',
'Expected the focus to change when the bottom sheet was opened.',
);
// Start the closing sequence and move focus out of bottom sheet.
bottomSheetRef.dismiss();
otherButton.focus();
expect(document.activeElement!.id)
.withContext('Expected focus to be on the alternate button.')
.toBe('other-button');
flushMicrotasks();
viewContainerFixture.detectChanges();
flush();
expect(document.activeElement!.id)
.withContext('Expected focus to stay on the alternate button.')
.toBe('other-button');
button.remove();
otherButton.remove();
}));
it('should re-focus trigger element inside the shadow DOM when the bottom sheet is dismissed', fakeAsync(() => {
if (!_supportsShadowDom()) {
return;
}
viewContainerFixture.destroy();
const fixture = TestBed.createComponent(ShadowDomComponent);
fixture.detectChanges();
const button = fixture.debugElement.query(By.css('button'))!.nativeElement;
button.focus();
const ref = bottomSheet.open(PizzaMsg);
flushMicrotasks();
fixture.detectChanges();
flushMicrotasks();
const spy = spyOn(button, 'focus').and.callThrough();
ref.dismiss();
flushMicrotasks();
fixture.detectChanges();
tick(500);
expect(spy).toHaveBeenCalled();
}));
});
}); | {
"end_byte": 28343,
"start_byte": 20138,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet.spec.ts"
} |
components/src/material/bottom-sheet/bottom-sheet.spec.ts_28345_34931 | describe('MatBottomSheet with parent MatBottomSheet', () => {
let parentBottomSheet: MatBottomSheet;
let childBottomSheet: MatBottomSheet;
let overlayContainerElement: HTMLElement;
let fixture: ComponentFixture<ComponentThatProvidesMatBottomSheet>;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [MatBottomSheetModule, NoopAnimationsModule, ComponentThatProvidesMatBottomSheet],
});
parentBottomSheet = TestBed.inject(MatBottomSheet);
overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement();
fixture = TestBed.createComponent(ComponentThatProvidesMatBottomSheet);
childBottomSheet = fixture.componentInstance.bottomSheet;
fixture.detectChanges();
}));
it('should close bottom sheets opened by parent when opening from child', fakeAsync(() => {
parentBottomSheet.open(PizzaMsg);
fixture.detectChanges();
tick(1000);
expect(overlayContainerElement.textContent)
.withContext('Expected a bottom sheet to be opened')
.toContain('Pizza');
childBottomSheet.open(TacoMsg);
fixture.detectChanges();
tick(1000);
expect(overlayContainerElement.textContent)
.withContext('Expected parent bottom sheet to be dismissed by opening from child')
.toContain('Taco');
}));
it('should close bottom sheets opened by child when opening from parent', fakeAsync(() => {
childBottomSheet.open(PizzaMsg);
fixture.detectChanges();
tick(1000);
expect(overlayContainerElement.textContent)
.withContext('Expected a bottom sheet to be opened')
.toContain('Pizza');
parentBottomSheet.open(TacoMsg);
fixture.detectChanges();
tick(1000);
expect(overlayContainerElement.textContent)
.withContext('Expected child bottom sheet to be dismissed by opening from parent')
.toContain('Taco');
}));
it('should not close parent bottom sheet when child is destroyed', fakeAsync(() => {
parentBottomSheet.open(PizzaMsg);
fixture.detectChanges();
tick(1000);
expect(overlayContainerElement.textContent)
.withContext('Expected a bottom sheet to be opened')
.toContain('Pizza');
childBottomSheet.ngOnDestroy();
fixture.detectChanges();
tick(1000);
expect(overlayContainerElement.textContent)
.withContext('Expected a bottom sheet to stay open')
.toContain('Pizza');
}));
});
describe('MatBottomSheet with default options', () => {
let bottomSheet: MatBottomSheet;
let overlayContainerElement: HTMLElement;
let testViewContainerRef: ViewContainerRef;
let viewContainerFixture: ComponentFixture<ComponentWithChildViewContainer>;
beforeEach(fakeAsync(() => {
const defaultConfig: MatBottomSheetConfig = {
hasBackdrop: false,
disableClose: true,
autoFocus: 'dialog',
};
TestBed.configureTestingModule({
imports: [
MatBottomSheetModule,
NoopAnimationsModule,
ComponentWithChildViewContainer,
DirectiveWithViewContainer,
],
providers: [{provide: MAT_BOTTOM_SHEET_DEFAULT_OPTIONS, useValue: defaultConfig}],
});
bottomSheet = TestBed.inject(MatBottomSheet);
overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement();
viewContainerFixture = TestBed.createComponent(ComponentWithChildViewContainer);
viewContainerFixture.detectChanges();
testViewContainerRef = viewContainerFixture.componentInstance.childViewContainer;
}));
it('should use the provided defaults', () => {
bottomSheet.open(PizzaMsg, {viewContainerRef: testViewContainerRef});
viewContainerFixture.detectChanges();
expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeFalsy();
dispatchKeyboardEvent(document.body, 'keydown', ESCAPE);
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeTruthy();
expect(document.activeElement!.tagName).not.toBe('INPUT');
});
it('should be overridable by open() options', fakeAsync(() => {
bottomSheet.open(PizzaMsg, {
hasBackdrop: true,
disableClose: false,
viewContainerRef: testViewContainerRef,
});
viewContainerFixture.detectChanges();
expect(overlayContainerElement.querySelector('.cdk-overlay-backdrop')).toBeTruthy();
dispatchKeyboardEvent(document.body, 'keydown', ESCAPE);
viewContainerFixture.detectChanges();
flush();
expect(overlayContainerElement.querySelector('mat-bottom-sheet-container')).toBeFalsy();
}));
});
@Directive({
selector: 'dir-with-view-container',
standalone: true,
})
class DirectiveWithViewContainer {
viewContainerRef = inject(ViewContainerRef);
}
@Component({
template: `<dir-with-view-container></dir-with-view-container>`,
standalone: true,
imports: [DirectiveWithViewContainer],
})
class ComponentWithChildViewContainer {
@ViewChild(DirectiveWithViewContainer) childWithViewContainer: DirectiveWithViewContainer;
get childViewContainer() {
return this.childWithViewContainer.viewContainerRef;
}
}
@Component({
selector: 'arbitrary-component-with-template-ref',
template: `<ng-template let-data let-bottomSheetRef="bottomSheetRef">
Cheese {{localValue}} {{data?.value}}{{setRef(bottomSheetRef)}}</ng-template>`,
standalone: true,
})
class ComponentWithTemplateRef {
localValue: string;
bottomSheetRef: MatBottomSheetRef<any>;
@ViewChild(TemplateRef) templateRef: TemplateRef<any>;
setRef(bottomSheetRef: MatBottomSheetRef<any>): string {
this.bottomSheetRef = bottomSheetRef;
return '';
}
}
@Component({
template: '<p>Pizza</p> <input> <button>Close</button>',
standalone: true,
})
class PizzaMsg {
bottomSheetRef = inject<MatBottomSheetRef<PizzaMsg>>(MatBottomSheetRef);
injector = inject(Injector);
directionality = inject(Directionality);
}
@Component({
template: '<p>Taco</p>',
standalone: true,
})
class TacoMsg {}
@Component({
template: `
<h1>This is the title</h1>
<p>This is the paragraph</p>
`,
standalone: true,
})
class ContentElementDialog {}
@Component({
template: '',
providers: [MatBottomSheet],
standalone: true,
imports: [MatBottomSheetModule],
})
class ComponentThatProvidesMatBottomSheet {
bottomSheet = inject(MatBottomSheet);
}
@Component({
template: '',
standalone: true,
})
class BottomSheetWithInjectedData {
data = inject(MAT_BOTTOM_SHEET_DATA);
}
@Component({
template: `<button>I'm a button</button>`,
encapsulation: ViewEncapsulation.ShadowDom,
standalone: true,
})
class ShadowDomComponent {} | {
"end_byte": 34931,
"start_byte": 28345,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet.spec.ts"
} |
components/src/material/bottom-sheet/public-api.ts_0_435 | /**
* @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 './bottom-sheet-module';
export * from './bottom-sheet';
export * from './bottom-sheet-config';
export * from './bottom-sheet-container';
export * from './bottom-sheet-animations';
export * from './bottom-sheet-ref';
| {
"end_byte": 435,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/public-api.ts"
} |
components/src/material/bottom-sheet/bottom-sheet-ref.ts_0_5004 | /**
* @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 {ComponentRef} from '@angular/core';
import {DialogRef} from '@angular/cdk/dialog';
import {ESCAPE, hasModifierKey} from '@angular/cdk/keycodes';
import {merge, Observable, Subject} from 'rxjs';
import {filter, take} from 'rxjs/operators';
import {MatBottomSheetConfig} from './bottom-sheet-config';
import {MatBottomSheetContainer} from './bottom-sheet-container';
/**
* Reference to a bottom sheet dispatched from the bottom sheet service.
*/
export class MatBottomSheetRef<T = any, R = any> {
/** Instance of the component making up the content of the bottom sheet. */
get instance(): T {
return this._ref.componentInstance!;
}
/**
* `ComponentRef` of the component opened into the bottom sheet. Will be
* null when the bottom sheet is opened using a `TemplateRef`.
*/
get componentRef(): ComponentRef<T> | null {
return this._ref.componentRef;
}
/**
* Instance of the component into which the bottom sheet content is projected.
* @docs-private
*/
containerInstance: MatBottomSheetContainer;
/** Whether the user is allowed to close the bottom sheet. */
disableClose: boolean | undefined;
/** Subject for notifying the user that the bottom sheet has opened and appeared. */
private readonly _afterOpened = new Subject<void>();
/** Result to be passed down to the `afterDismissed` stream. */
private _result: R | undefined;
/** Handle to the timeout that's running as a fallback in case the exit animation doesn't fire. */
private _closeFallbackTimeout: number;
constructor(
private _ref: DialogRef<R, T>,
config: MatBottomSheetConfig,
containerInstance: MatBottomSheetContainer,
) {
this.containerInstance = containerInstance;
this.disableClose = config.disableClose;
// Emit when opening animation completes
containerInstance._animationStateChanged
.pipe(
filter(event => event.phaseName === 'done' && event.toState === 'visible'),
take(1),
)
.subscribe(() => {
this._afterOpened.next();
this._afterOpened.complete();
});
// Dispose overlay when closing animation is complete
containerInstance._animationStateChanged
.pipe(
filter(event => event.phaseName === 'done' && event.toState === 'hidden'),
take(1),
)
.subscribe(() => {
clearTimeout(this._closeFallbackTimeout);
this._ref.close(this._result);
});
_ref.overlayRef.detachments().subscribe(() => {
this._ref.close(this._result);
});
merge(
this.backdropClick(),
this.keydownEvents().pipe(filter(event => event.keyCode === ESCAPE)),
).subscribe(event => {
if (
!this.disableClose &&
(event.type !== 'keydown' || !hasModifierKey(event as KeyboardEvent))
) {
event.preventDefault();
this.dismiss();
}
});
}
/**
* Dismisses the bottom sheet.
* @param result Data to be passed back to the bottom sheet opener.
*/
dismiss(result?: R): void {
if (!this.containerInstance) {
return;
}
// Transition the backdrop in parallel to the bottom sheet.
this.containerInstance._animationStateChanged
.pipe(
filter(event => event.phaseName === 'start'),
take(1),
)
.subscribe(event => {
// The logic that disposes of the overlay depends on the exit animation completing, however
// it isn't guaranteed if the parent view is destroyed while it's running. Add a fallback
// timeout which will clean everything up if the animation hasn't fired within the specified
// amount of time plus 100ms. We don't need to run this outside the NgZone, because for the
// vast majority of cases the timeout will have been cleared before it has fired.
this._closeFallbackTimeout = setTimeout(() => {
this._ref.close(this._result);
}, event.totalTime + 100);
this._ref.overlayRef.detachBackdrop();
});
this._result = result;
this.containerInstance.exit();
this.containerInstance = null!;
}
/** Gets an observable that is notified when the bottom sheet is finished closing. */
afterDismissed(): Observable<R | undefined> {
return this._ref.closed;
}
/** Gets an observable that is notified when the bottom sheet has opened and appeared. */
afterOpened(): Observable<void> {
return this._afterOpened;
}
/**
* Gets an observable that emits when the overlay's backdrop has been clicked.
*/
backdropClick(): Observable<MouseEvent> {
return this._ref.backdropClick;
}
/**
* Gets an observable that emits when keydown events are targeted on the overlay.
*/
keydownEvents(): Observable<KeyboardEvent> {
return this._ref.keydownEvents;
}
}
| {
"end_byte": 5004,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet-ref.ts"
} |
components/src/material/bottom-sheet/bottom-sheet-animations.ts_0_1270 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
animate,
state,
style,
transition,
trigger,
AnimationTriggerMetadata,
group,
query,
animateChild,
} from '@angular/animations';
import {AnimationCurves, AnimationDurations} from '@angular/material/core';
/** Animations used by the Material bottom sheet. */
export const matBottomSheetAnimations: {
readonly bottomSheetState: AnimationTriggerMetadata;
} = {
/** Animation that shows and hides a bottom sheet. */
bottomSheetState: trigger('state', [
state('void, hidden', style({transform: 'translateY(100%)'})),
state('visible', style({transform: 'translateY(0%)'})),
transition(
'visible => void, visible => hidden',
group([
animate(`${AnimationDurations.COMPLEX} ${AnimationCurves.ACCELERATION_CURVE}`),
query('@*', animateChild(), {optional: true}),
]),
),
transition(
'void => visible',
group([
animate(`${AnimationDurations.EXITING} ${AnimationCurves.DECELERATION_CURVE}`),
query('@*', animateChild(), {optional: true}),
]),
),
]),
};
| {
"end_byte": 1270,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet-animations.ts"
} |
components/src/material/bottom-sheet/README.md_0_103 | Please see the official documentation at https://material.angular.io/components/component/bottom-sheet
| {
"end_byte": 103,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/README.md"
} |
components/src/material/bottom-sheet/bottom-sheet.md_0_4499 | The `MatBottomSheet` service can be used to open Material Design panels to the bottom of the screen.
These panels are intended primarily as an interaction on mobile devices where they can be used as an
alternative to dialogs and menus.
<!-- example(bottom-sheet-overview) -->
You can open a bottom sheet by calling the `open` method with a component to be loaded and an
optional config object. The `open` method will return an instance of `MatBottomSheetRef`:
```ts
const bottomSheetRef = bottomSheet.open(SocialShareComponent, {
ariaLabel: 'Share on social media'
});
```
The `MatBottomSheetRef` is a reference to the currently-opened bottom sheet and can be used to close
it or to subscribe to events. Note that only one bottom sheet can be open at a time. Any component
contained inside of a bottom sheet can inject the `MatBottomSheetRef` as well.
```ts
bottomSheetRef.afterDismissed().subscribe(() => {
console.log('Bottom sheet has been dismissed.');
});
bottomSheetRef.dismiss();
```
### Sharing data with the bottom sheet component.
If you want to pass in some data to the bottom sheet, you can do so using the `data` property:
```ts
const bottomSheetRef = bottomSheet.open(HobbitSheet, {
data: { names: ['Frodo', 'Bilbo'] },
});
```
Afterwards you can access the injected data using the `MAT_BOTTOM_SHEET_DATA` injection token:
```ts
import {Component, Inject} from '@angular/core';
import {MAT_BOTTOM_SHEET_DATA} from '@angular/material/bottom-sheet';
@Component({
selector: 'hobbit-sheet',
template: 'passed in {{ data.names }}',
})
export class HobbitSheet {
constructor(@Inject(MAT_BOTTOM_SHEET_DATA) public data: {names: string[]}) { }
}
```
### Specifying global configuration defaults
Default bottom sheet options can be specified by providing an instance of `MatBottomSheetConfig`
for `MAT_BOTTOM_SHEET_DEFAULT_OPTIONS` in your application's root module.
```ts
@NgModule({
providers: [
{provide: MAT_BOTTOM_SHEET_DEFAULT_OPTIONS, useValue: {hasBackdrop: false}}
]
})
```
### Accessibility
`MatBottomSheet` creates modal dialogs that implement the ARIA `role="dialog"` pattern. This root
dialog element should be given an accessible label via the `ariaLabel` property of
`MatBottomSheetConfig`.
#### Keyboard interaction
By default, the escape key closes `MatBottomSheet`. While you can disable this behavior by using
the `disableClose` property of `MatBottomSheetConfig`, doing this breaks the expected interaction
pattern for the ARIA `role="dialog"` pattern.
#### Focus management
When opened, `MatBottomSheet` traps browser focus such that it cannot escape the root
`role="dialog"` element. By default, the first tabbable element in the bottom sheet receives focus.
You can customize which element receives focus with the `autoFocus` property of
`MatBottomSheetConfig`, which supports the following values.
| Value | Behavior |
|------------------|--------------------------------------------------------------------------|
| `first-tabbable` | Focus the first tabbable element. This is the default setting. |
| `first-header` | Focus the first header element (`role="heading"`, `h1` through `h6`) |
| `dialog` | Focus the root `role="dialog"` element. |
| Any CSS selector | Focus the first element matching the given selector. |
While the default setting applies the best behavior for most applications, special cases may benefit
from these alternatives. Always test your application to verify the behavior that works best for
your users.
#### Focus restoration
When closed, `MatBottomSheet` restores focus to the element that previously held focus when the
bottom sheet opened. However, if that previously focused element no longer exists, you must
add additional handling to return focus to an element that makes sense for the user's workflow.
Opening a bottom sheet from a menu is one common pattern that causes this situation. The menu
closes upon clicking an item, thus the focused menu item is no longer in the DOM when the bottom
sheet attempts to restore focus.
You can add handling for this situation with the `afterDismissed()` observable from
`MatBottomSheetRef`.
```typescript
const bottomSheetRef = bottomSheet.open(FileTypeChooser);
bottomSheetRef.afterDismissed().subscribe(() => {
// Restore focus to an appropriate element for the user's workflow here.
});
```
| {
"end_byte": 4499,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet.md"
} |
components/src/material/bottom-sheet/_bottom-sheet-theme.scss_0_2935 | @use 'sass:map';
@use '../core/typography/typography';
@use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/style/sass-utils';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/bottom-sheet' as tokens-mat-bottom-sheet;
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-bottom-sheet.$prefix,
tokens-mat-bottom-sheet.get-unthemable-tokens()
);
}
}
}
@mixin color($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-bottom-sheet.$prefix,
tokens-mat-bottom-sheet.get-color-tokens($theme)
);
}
}
}
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-bottom-sheet.$prefix,
tokens-mat-bottom-sheet.get-typography-tokens($theme)
);
}
}
}
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-bottom-sheet.$prefix,
tokens: tokens-mat-bottom-sheet.get-token-slots(),
),
);
}
@mixin overrides($tokens: ()) {
@include token-utils.batch-create-token-values($tokens, _define-overrides()...);
}
@mixin theme($theme) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-bottom-sheet') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme));
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
@if ($tokens != ()) {
@include token-utils.create-token-values(
tokens-mat-bottom-sheet.$prefix,
map.get($tokens, tokens-mat-bottom-sheet.$prefix)
);
}
}
| {
"end_byte": 2935,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/_bottom-sheet-theme.scss"
} |
components/src/material/bottom-sheet/BUILD.bazel_0_1959 | 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 = "bottom-sheet",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = [
":bottom-sheet-container.css",
] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/coercion",
"//src/cdk/dialog",
"//src/cdk/keycodes",
"//src/cdk/layout",
"//src/cdk/overlay",
"//src/cdk/platform",
"//src/cdk/portal",
"//src/material/core",
"@npm//@angular/animations",
"@npm//@angular/core",
"@npm//rxjs",
],
)
sass_library(
name = "bottom_sheet_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = ["//src/material/core:core_scss_lib"],
)
sass_binary(
name = "bottom_sheet_container_scss",
src = "bottom-sheet-container.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material/core:core_scss_lib",
],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":bottom-sheet",
"//src/cdk/bidi",
"//src/cdk/keycodes",
"//src/cdk/overlay",
"//src/cdk/platform",
"//src/cdk/scrolling",
"//src/cdk/testing/private",
"@npm//@angular/common",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [":bottom-sheet.md"],
)
extract_tokens(
name = "tokens",
srcs = [":bottom_sheet_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1959,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/BUILD.bazel"
} |
components/src/material/bottom-sheet/bottom-sheet-container.scss_0_2479 | @use '@angular/cdk';
@use '../core/style/elevation';
@use '../core/tokens/m2/mat/bottom-sheet' as tokens-mat-bottom-sheet;
@use '../core/tokens/token-utils';
// The bottom sheet minimum width on larger screen sizes is based
// on increments of the toolbar, according to the spec. See:
// https://material.io/guidelines/components/bottom-sheets.html#bottom-sheets-specs
$_width-increment: 64px;
$container-vertical-padding: 8px !default;
$container-horizontal-padding: 16px !default;
.mat-bottom-sheet-container {
@include elevation.elevation(16);
padding: $container-vertical-padding
$container-horizontal-padding;
min-width: 100vw;
box-sizing: border-box;
display: block;
outline: 0;
max-height: 80vh;
overflow: auto;
@include token-utils.use-tokens(
tokens-mat-bottom-sheet.$prefix, tokens-mat-bottom-sheet.get-token-slots()) {
@include token-utils.create-token-slot(background, container-background-color);
@include token-utils.create-token-slot(color, container-text-color);
@include token-utils.create-token-slot(font-family, container-text-font);
@include token-utils.create-token-slot(font-size, container-text-size);
@include token-utils.create-token-slot(line-height, container-text-line-height);
@include token-utils.create-token-slot(font-weight, container-text-weight);
@include token-utils.create-token-slot(letter-spacing, container-text-tracking);
}
@include cdk.high-contrast {
outline: 1px solid;
}
}
// Applies a border radius to the bottom sheet. Should only be applied when it's not full-screen.
%_mat-bottom-sheet-container-border-radius {
@include token-utils.use-tokens(
tokens-mat-bottom-sheet.$prefix, tokens-mat-bottom-sheet.get-token-slots()) {
@include token-utils.create-token-slot(border-top-left-radius, container-shape);
@include token-utils.create-token-slot(border-top-right-radius, container-shape);
}
}
.mat-bottom-sheet-container-medium {
@extend %_mat-bottom-sheet-container-border-radius;
min-width: $_width-increment * 6;
max-width: calc(100vw - #{$_width-increment * 2});
}
.mat-bottom-sheet-container-large {
@extend %_mat-bottom-sheet-container-border-radius;
min-width: $_width-increment * 8;
max-width: calc(100vw - #{$_width-increment * 4});
}
.mat-bottom-sheet-container-xlarge {
@extend %_mat-bottom-sheet-container-border-radius;
min-width: $_width-increment * 9;
max-width: calc(100vw - #{$_width-increment * 6});
}
| {
"end_byte": 2479,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet-container.scss"
} |
components/src/material/bottom-sheet/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/bottom-sheet/index.ts"
} |
components/src/material/bottom-sheet/bottom-sheet-module.ts_0_735 | /**
* @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 {DialogModule} from '@angular/cdk/dialog';
import {PortalModule} from '@angular/cdk/portal';
import {NgModule} from '@angular/core';
import {MatCommonModule} from '@angular/material/core';
import {MatBottomSheetContainer} from './bottom-sheet-container';
import {MatBottomSheet} from './bottom-sheet';
@NgModule({
imports: [DialogModule, MatCommonModule, PortalModule, MatBottomSheetContainer],
exports: [MatBottomSheetContainer, MatCommonModule],
providers: [MatBottomSheet],
})
export class MatBottomSheetModule {}
| {
"end_byte": 735,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet-module.ts"
} |
components/src/material/bottom-sheet/bottom-sheet.ts_0_5062 | /**
* @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 {Dialog} from '@angular/cdk/dialog';
import {Overlay} from '@angular/cdk/overlay';
import {ComponentType} from '@angular/cdk/portal';
import {Injectable, TemplateRef, InjectionToken, OnDestroy, inject} from '@angular/core';
import {MAT_BOTTOM_SHEET_DATA, MatBottomSheetConfig} from './bottom-sheet-config';
import {MatBottomSheetContainer} from './bottom-sheet-container';
import {MatBottomSheetRef} from './bottom-sheet-ref';
/** Injection token that can be used to specify default bottom sheet options. */
export const MAT_BOTTOM_SHEET_DEFAULT_OPTIONS = new InjectionToken<MatBottomSheetConfig>(
'mat-bottom-sheet-default-options',
);
/**
* Service to trigger Material Design bottom sheets.
*/
@Injectable({providedIn: 'root'})
export class MatBottomSheet implements OnDestroy {
private _overlay = inject(Overlay);
private _parentBottomSheet = inject(MatBottomSheet, {optional: true, skipSelf: true});
private _defaultOptions = inject<MatBottomSheetConfig>(MAT_BOTTOM_SHEET_DEFAULT_OPTIONS, {
optional: true,
});
private _bottomSheetRefAtThisLevel: MatBottomSheetRef<any> | null = null;
private _dialog = inject(Dialog);
/** Reference to the currently opened bottom sheet. */
get _openedBottomSheetRef(): MatBottomSheetRef<any> | null {
const parent = this._parentBottomSheet;
return parent ? parent._openedBottomSheetRef : this._bottomSheetRefAtThisLevel;
}
set _openedBottomSheetRef(value: MatBottomSheetRef<any> | null) {
if (this._parentBottomSheet) {
this._parentBottomSheet._openedBottomSheetRef = value;
} else {
this._bottomSheetRefAtThisLevel = value;
}
}
constructor(...args: unknown[]);
constructor() {}
/**
* Opens a bottom sheet containing the given component.
* @param component Type of the component to load into the bottom sheet.
* @param config Extra configuration options.
* @returns Reference to the newly-opened bottom sheet.
*/
open<T, D = any, R = any>(
component: ComponentType<T>,
config?: MatBottomSheetConfig<D>,
): MatBottomSheetRef<T, R>;
/**
* Opens a bottom sheet containing the given template.
* @param template TemplateRef to instantiate as the bottom sheet content.
* @param config Extra configuration options.
* @returns Reference to the newly-opened bottom sheet.
*/
open<T, D = any, R = any>(
template: TemplateRef<T>,
config?: MatBottomSheetConfig<D>,
): MatBottomSheetRef<T, R>;
open<T, D = any, R = any>(
componentOrTemplateRef: ComponentType<T> | TemplateRef<T>,
config?: MatBottomSheetConfig<D>,
): MatBottomSheetRef<T, R> {
const _config = {...(this._defaultOptions || new MatBottomSheetConfig()), ...config};
let ref: MatBottomSheetRef<T, R>;
this._dialog.open<R, D, T>(componentOrTemplateRef, {
..._config,
// Disable closing since we need to sync it up to the animation ourselves.
disableClose: true,
// Disable closing on detachments so that we can sync up the animation.
closeOnOverlayDetachments: false,
maxWidth: '100%',
container: MatBottomSheetContainer,
scrollStrategy: _config.scrollStrategy || this._overlay.scrollStrategies.block(),
positionStrategy: this._overlay.position().global().centerHorizontally().bottom('0'),
templateContext: () => ({bottomSheetRef: ref}),
providers: (cdkRef, _cdkConfig, container) => {
ref = new MatBottomSheetRef(cdkRef, _config, container as MatBottomSheetContainer);
return [
{provide: MatBottomSheetRef, useValue: ref},
{provide: MAT_BOTTOM_SHEET_DATA, useValue: _config.data},
];
},
});
// When the bottom sheet is dismissed, clear the reference to it.
ref!.afterDismissed().subscribe(() => {
// Clear the bottom sheet ref if it hasn't already been replaced by a newer one.
if (this._openedBottomSheetRef === ref) {
this._openedBottomSheetRef = null;
}
});
if (this._openedBottomSheetRef) {
// If a bottom sheet is already in view, dismiss it and enter the
// new bottom sheet after exit animation is complete.
this._openedBottomSheetRef.afterDismissed().subscribe(() => ref.containerInstance?.enter());
this._openedBottomSheetRef.dismiss();
} else {
// If no bottom sheet is in view, enter the new bottom sheet.
ref!.containerInstance.enter();
}
this._openedBottomSheetRef = ref!;
return ref!;
}
/**
* Dismisses the currently-visible bottom sheet.
* @param result Data to pass to the bottom sheet instance.
*/
dismiss<R = any>(result?: R): void {
if (this._openedBottomSheetRef) {
this._openedBottomSheetRef.dismiss(result);
}
}
ngOnDestroy() {
if (this._bottomSheetRefAtThisLevel) {
this._bottomSheetRefAtThisLevel.dismiss();
}
}
}
| {
"end_byte": 5062,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet.ts"
} |
components/src/material/bottom-sheet/bottom-sheet-container.html_0_44 | <ng-template cdkPortalOutlet></ng-template>
| {
"end_byte": 44,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/bottom-sheet-container.html"
} |
components/src/material/bottom-sheet/testing/bottom-sheet-harness-filters.ts_0_335 | /**
* @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 BottomSheetHarnessFilters extends BaseHarnessFilters {}
| {
"end_byte": 335,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/testing/bottom-sheet-harness-filters.ts"
} |
components/src/material/bottom-sheet/testing/bottom-sheet-harness.spec.ts_0_2269 | import {Component, TemplateRef, ViewChild, inject} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {
MatBottomSheet,
MatBottomSheetConfig,
MatBottomSheetModule,
} from '@angular/material/bottom-sheet';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatBottomSheetHarness} from './bottom-sheet-harness';
describe('MatBottomSheetHarness', () => {
let fixture: ComponentFixture<BottomSheetHarnessTest>;
let loader: HarnessLoader;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MatBottomSheetModule, NoopAnimationsModule, BottomSheetHarnessTest],
});
fixture = TestBed.createComponent(BottomSheetHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.documentRootLoader(fixture);
});
it('should load harness for a bottom sheet', async () => {
fixture.componentInstance.open();
const bottomSheets = await loader.getAllHarnesses(MatBottomSheetHarness);
expect(bottomSheets.length).toBe(1);
});
it('should be able to get aria-label of the bottom sheet', async () => {
fixture.componentInstance.open({ariaLabel: 'Confirm purchase.'});
const bottomSheet = await loader.getHarness(MatBottomSheetHarness);
expect(await bottomSheet.getAriaLabel()).toBe('Confirm purchase.');
});
it('should be able to dismiss the bottom sheet', async () => {
fixture.componentInstance.open();
let bottomSheets = await loader.getAllHarnesses(MatBottomSheetHarness);
expect(bottomSheets.length).toBe(1);
await bottomSheets[0].dismiss();
bottomSheets = await loader.getAllHarnesses(MatBottomSheetHarness);
expect(bottomSheets.length).toBe(0);
});
});
@Component({
template: `
<ng-template>
Hello from the bottom sheet!
</ng-template>
`,
standalone: true,
imports: [MatBottomSheetModule],
})
class BottomSheetHarnessTest {
readonly bottomSheet = inject(MatBottomSheet);
@ViewChild(TemplateRef) template: TemplateRef<any>;
open(config?: MatBottomSheetConfig) {
return this.bottomSheet.open(this.template, config);
}
}
| {
"end_byte": 2269,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/testing/bottom-sheet-harness.spec.ts"
} |
components/src/material/bottom-sheet/testing/public-api.ts_0_292 | /**
* @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 './bottom-sheet-harness';
export * from './bottom-sheet-harness-filters';
| {
"end_byte": 292,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/testing/public-api.ts"
} |
components/src/material/bottom-sheet/testing/BUILD.bazel_0_795 | 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/bottom-sheet",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/overlay",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/bottom-sheet",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_tests_lib"],
)
| {
"end_byte": 795,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/testing/BUILD.bazel"
} |
components/src/material/bottom-sheet/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/bottom-sheet/testing/index.ts"
} |
components/src/material/bottom-sheet/testing/bottom-sheet-harness.ts_0_1588 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ContentContainerComponentHarness, HarnessPredicate, TestKey} from '@angular/cdk/testing';
import {BottomSheetHarnessFilters} from './bottom-sheet-harness-filters';
/** Harness for interacting with a standard MatBottomSheet in tests. */
export class MatBottomSheetHarness extends ContentContainerComponentHarness<string> {
// Developers can provide a custom component or template for the
// bottom sheet. The canonical parent is the ".mat-bottom-sheet-container".
static hostSelector = '.mat-bottom-sheet-container';
/**
* Gets a `HarnessPredicate` that can be used to search for a bottom sheet with
* specific attributes.
* @param options Options for narrowing the search.
* @return a `HarnessPredicate` configured with the given options.
*/
static with(options: BottomSheetHarnessFilters = {}): HarnessPredicate<MatBottomSheetHarness> {
return new HarnessPredicate(MatBottomSheetHarness, options);
}
/** Gets the value of the bottom sheet's "aria-label" attribute. */
async getAriaLabel(): Promise<string | null> {
return (await this.host()).getAttribute('aria-label');
}
/**
* Dismisses the bottom sheet by pressing escape. Note that this method cannot
* be used if "disableClose" has been set to true via the config.
*/
async dismiss(): Promise<void> {
await (await this.host()).sendKeys(TestKey.ESCAPE);
}
}
| {
"end_byte": 1588,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/bottom-sheet/testing/bottom-sheet-harness.ts"
} |
components/src/material/select/select.html_0_2083 | <div cdk-overlay-origin
class="mat-mdc-select-trigger"
(click)="open()"
#fallbackOverlayOrigin="cdkOverlayOrigin"
#trigger>
<div class="mat-mdc-select-value" [attr.id]="_valueId">
@if (empty) {
<span class="mat-mdc-select-placeholder mat-mdc-select-min-line">{{placeholder}}</span>
} @else {
<span class="mat-mdc-select-value-text">
@if (customTrigger) {
<ng-content select="mat-select-trigger"></ng-content>
} @else {
<span class="mat-mdc-select-min-line">{{triggerValue}}</span>
}
</span>
}
</div>
<div class="mat-mdc-select-arrow-wrapper">
<div class="mat-mdc-select-arrow">
<!-- Use an inline SVG, because it works better than a CSS triangle in high contrast mode. -->
<svg viewBox="0 0 24 24" width="24px" height="24px" focusable="false" aria-hidden="true">
<path d="M7 10l5 5 5-5z"/>
</svg>
</div>
</div>
</div>
<ng-template
cdk-connected-overlay
cdkConnectedOverlayLockPosition
cdkConnectedOverlayHasBackdrop
cdkConnectedOverlayBackdropClass="cdk-overlay-transparent-backdrop"
[cdkConnectedOverlayPanelClass]="_overlayPanelClass"
[cdkConnectedOverlayScrollStrategy]="_scrollStrategy"
[cdkConnectedOverlayOrigin]="_preferredOverlayOrigin || fallbackOverlayOrigin"
[cdkConnectedOverlayOpen]="panelOpen"
[cdkConnectedOverlayPositions]="_positions"
[cdkConnectedOverlayWidth]="_overlayWidth"
(backdropClick)="close()"
(attach)="_onAttached()"
(detach)="close()">
<div
#panel
role="listbox"
tabindex="-1"
class="mat-mdc-select-panel mdc-menu-surface mdc-menu-surface--open {{ _getPanelTheme() }}"
[attr.id]="id + '-panel'"
[attr.aria-multiselectable]="multiple"
[attr.aria-label]="ariaLabel || null"
[attr.aria-labelledby]="_getPanelAriaLabelledby()"
[ngClass]="panelClass"
[@transformPanel]="'showing'"
(@transformPanel.done)="_panelDoneAnimatingStream.next($event.toState)"
(keydown)="_handleKeydown($event)">
<ng-content></ng-content>
</div>
</ng-template>
| {
"end_byte": 2083,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.html"
} |
components/src/material/select/select.spec.ts_0_3551 | import {LiveAnnouncer} from '@angular/cdk/a11y';
import {Directionality} from '@angular/cdk/bidi';
import {
A,
DOWN_ARROW,
END,
ENTER,
ESCAPE,
HOME,
LEFT_ARROW,
PAGE_DOWN,
PAGE_UP,
RIGHT_ARROW,
SPACE,
TAB,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {OverlayContainer, OverlayModule} from '@angular/cdk/overlay';
import {ScrollDispatcher} from '@angular/cdk/scrolling';
import {
createKeyboardEvent,
dispatchEvent,
dispatchFakeEvent,
dispatchKeyboardEvent,
wrappedErrorMessage,
} from '@angular/cdk/testing/private';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
DebugElement,
ElementRef,
OnInit,
Provider,
QueryList,
ViewChild,
ViewChildren,
inject,
} from '@angular/core';
import {
ComponentFixture,
TestBed,
fakeAsync,
flush,
tick,
waitForAsync,
} from '@angular/core/testing';
import {
ControlValueAccessor,
FormBuilder,
FormControl,
FormGroup,
FormGroupDirective,
FormsModule,
NG_VALUE_ACCESSOR,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import {ErrorStateMatcher, MatOption, MatOptionSelectionChange} from '@angular/material/core';
import {
FloatLabelType,
MAT_FORM_FIELD_DEFAULT_OPTIONS,
MatFormFieldModule,
} from '@angular/material/form-field';
import {MAT_SELECT_CONFIG, MatSelectConfig} from '@angular/material/select';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {EMPTY, Observable, Subject, Subscription} from 'rxjs';
import {map} from 'rxjs/operators';
import {MatSelectModule} from './index';
import {MatSelect} from './select';
import {
getMatSelectDynamicMultipleError,
getMatSelectNonArrayValueError,
getMatSelectNonFunctionValueError,
} from './select-errors';
/** Default debounce interval when typing letters to select an option. */
const DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL = 200;
describe('MatSelect', () => {
let overlayContainerElement: HTMLElement;
let dir: {value: 'ltr' | 'rtl'; change: Observable<string>};
let scrolledSubject = new Subject();
/**
* Configures the test module for MatSelect with the given declarations. This is broken out so
* that we're only compiling the necessary test components for each test in order to speed up
* overall test time.
* @param declarations Components to declare for this block
* @param providers Additional providers for this block
*/
function configureMatSelectTestingModule(declarations: any[], providers: Provider[] = []) {
TestBed.configureTestingModule({
imports: [
MatFormFieldModule,
MatSelectModule,
ReactiveFormsModule,
FormsModule,
NoopAnimationsModule,
OverlayModule,
],
providers: [
{provide: Directionality, useFactory: () => (dir = {value: 'ltr', change: EMPTY})},
{
provide: ScrollDispatcher,
useFactory: () => ({
scrolled: () => scrolledSubject,
}),
},
...providers,
],
declarations: declarations,
});
overlayContainerElement = TestBed.inject(OverlayContainer).getContainerElement();
}
describe('core', () => {
beforeEach(waitForAsync(() => {
configureMatSelectTestingModule([
BasicSelect,
SelectInsideAModal,
MultiSelect,
SelectWithGroups,
SelectWithGroupsAndNgContainer,
SelectWithFormFieldLabel,
SelectWithChangeEvent,
SelectInsideDynamicFormGroup,
]);
})); | {
"end_byte": 3551,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_3557_14291 | describe('accessibility', () => {
describe('for select', () => {
let fixture: ComponentFixture<BasicSelect>;
let select: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(BasicSelect);
fixture.detectChanges();
select = fixture.debugElement.query(By.css('mat-select'))!.nativeElement;
});
it('should set the role of the select to combobox', () => {
expect(select.getAttribute('role')).toEqual('combobox');
expect(select.getAttribute('aria-haspopup')).toBe('listbox');
});
it('should point the aria-controls attribute to the listbox', fakeAsync(() => {
expect(select.hasAttribute('aria-controls')).toBe(false);
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
const ariaControls = select.getAttribute('aria-controls');
expect(ariaControls).toBeTruthy();
expect(ariaControls).toBe(document.querySelector('.mat-mdc-select-panel')!.id);
}));
it('should set aria-expanded based on the select open state', fakeAsync(() => {
expect(select.getAttribute('aria-expanded')).toBe('false');
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
expect(select.getAttribute('aria-expanded')).toBe('true');
}));
it('should support setting a custom aria-label', () => {
fixture.componentInstance.ariaLabel = 'Custom Label';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(select.getAttribute('aria-label')).toEqual('Custom Label');
expect(select.hasAttribute('aria-labelledby')).toBeFalsy();
});
it('should be able to add an extra aria-labelledby on top of the default', () => {
fixture.componentInstance.ariaLabelledby = 'myLabelId';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const labelId = fixture.nativeElement.querySelector('label').id;
const valueId = fixture.nativeElement.querySelector('.mat-mdc-select-value').id;
expect(select.getAttribute('aria-labelledby')).toBe(`${labelId} ${valueId} myLabelId`);
});
it('should set aria-labelledby to the value and label IDs', () => {
fixture.detectChanges();
const labelId = fixture.nativeElement.querySelector('label').id;
const valueId = fixture.nativeElement.querySelector('.mat-mdc-select-value').id;
expect(select.getAttribute('aria-labelledby')).toBe(`${labelId} ${valueId}`);
});
it('should trim the trigger aria-labelledby when there is no label', fakeAsync(() => {
fixture.componentInstance.hasLabel = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
// Note that we assert that there are no spaces around the value.
const valueId = fixture.nativeElement.querySelector('.mat-mdc-select-value').id;
expect(select.getAttribute('aria-labelledby')).toBe(`${valueId}`);
}));
it('should set the tabindex of the select to 0 by default', () => {
expect(select.getAttribute('tabindex')).toEqual('0');
});
it('should set `aria-describedby` to the id of the mat-hint', () => {
expect(select.getAttribute('aria-describedby')).toBeNull();
fixture.componentInstance.hint = 'test';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const hint = fixture.debugElement.query(By.css('mat-hint')).nativeElement;
expect(select.getAttribute('aria-describedby')).toBe(hint.getAttribute('id'));
expect(select.getAttribute('aria-describedby')).toMatch(/^mat-mdc-hint-\d+$/);
});
it('should support user binding to `aria-describedby`', () => {
fixture.componentInstance.ariaDescribedBy = 'test';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(select.getAttribute('aria-describedby')).toBe('test');
});
it('should be able to override the tabindex', () => {
fixture.componentInstance.tabIndexOverride = 3;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(select.getAttribute('tabindex')).toBe('3');
});
it('should set aria-required for required selects', () => {
expect(select.getAttribute('aria-required'))
.withContext(`Expected aria-required attr to be false for normal selects.`)
.toEqual('false');
fixture.componentInstance.isRequired = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(select.getAttribute('aria-required'))
.withContext(`Expected aria-required attr to be true for required selects.`)
.toEqual('true');
});
it('should set the mat-select-required class for required selects', () => {
expect(select.classList).not.toContain(
'mat-mdc-select-required',
`Expected the mat-mdc-select-required class not to be set.`,
);
fixture.componentInstance.isRequired = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(select.classList)
.withContext(`Expected the mat-mdc-select-required class to be set.`)
.toContain('mat-mdc-select-required');
});
it('should set aria-invalid for selects that are invalid and touched', () => {
expect(select.getAttribute('aria-invalid'))
.withContext(`Expected aria-invalid attr to be false for valid selects.`)
.toEqual('false');
fixture.componentInstance.isRequired = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.control.markAsTouched();
fixture.detectChanges();
expect(select.getAttribute('aria-invalid'))
.withContext(`Expected aria-invalid attr to be true for invalid selects.`)
.toEqual('true');
});
it('should set aria-disabled for disabled selects', () => {
expect(select.getAttribute('aria-disabled')).toEqual('false');
fixture.componentInstance.control.disable();
fixture.detectChanges();
expect(select.getAttribute('aria-disabled')).toEqual('true');
});
it('should set the tabindex of the select to -1 if disabled', () => {
fixture.componentInstance.control.disable();
fixture.detectChanges();
expect(select.getAttribute('tabindex')).toEqual('-1');
fixture.componentInstance.control.enable();
fixture.detectChanges();
expect(select.getAttribute('tabindex')).toEqual('0');
});
it('should set `aria-labelledby` to the value ID if there is no form field', () => {
fixture.destroy();
const labelFixture = TestBed.createComponent(SelectWithChangeEvent);
labelFixture.detectChanges();
select = labelFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
const valueId = labelFixture.nativeElement.querySelector('.mat-mdc-select-value').id;
expect(select.getAttribute('aria-labelledby')?.trim()).toBe(valueId);
});
it('should select options via the UP/DOWN arrow keys on a closed select', fakeAsync(() => {
const formControl = fixture.componentInstance.control;
const options = fixture.componentInstance.options.toArray();
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
expect(options[0].selected)
.withContext('Expected first option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from first option to have been set on the model.')
.toBe(options[0].value);
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
// Note that the third option is skipped, because it is disabled.
// Note that the third option is skipped, because it is disabled.
expect(options[3].selected)
.withContext('Expected fourth option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from fourth option to have been set on the model.')
.toBe(options[3].value);
dispatchKeyboardEvent(select, 'keydown', UP_ARROW);
expect(options[1].selected)
.withContext('Expected second option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from second option to have been set on the model.')
.toBe(options[1].value);
flush();
}));
it('should go back to first option if value is reset after interacting using the arrow keys on a closed select', fakeAsync(() => {
const formControl = fixture.componentInstance.control;
const options = fixture.componentInstance.options.toArray();
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
flush();
expect(options[0].selected)
.withContext('Expected first option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from first option to have been set on the model.')
.toBe(options[0].value);
formControl.reset();
fixture.detectChanges();
expect(options[0].selected)
.withContext('Expected first option to be deselected.')
.toBe(false);
expect(formControl.value).withContext('Expected value to be reset.').toBeFalsy();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
flush();
expect(options[0].selected)
.withContext('Expected first option to be selected again.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from first option to have been set on the model again.')
.toBe(options[0].value);
})); | {
"end_byte": 14291,
"start_byte": 3557,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_14301_24673 | it('should select first/last options via the HOME/END keys on a closed select', fakeAsync(() => {
const formControl = fixture.componentInstance.control;
const firstOption = fixture.componentInstance.options.first;
const lastOption = fixture.componentInstance.options.last;
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
const endEvent = dispatchKeyboardEvent(select, 'keydown', END);
expect(endEvent.defaultPrevented).toBe(true);
expect(lastOption.selected)
.withContext('Expected last option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from last option to have been set on the model.')
.toBe(lastOption.value);
const homeEvent = dispatchKeyboardEvent(select, 'keydown', HOME);
expect(homeEvent.defaultPrevented).toBe(true);
expect(firstOption.selected)
.withContext('Expected first option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from first option to have been set on the model.')
.toBe(firstOption.value);
flush();
}));
it('should select first/last options via the PAGE_DOWN/PAGE_UP keys on a closed select with less than 10 options', fakeAsync(() => {
const formControl = fixture.componentInstance.control;
const firstOption = fixture.componentInstance.options.first;
const lastOption = fixture.componentInstance.options.last;
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(-1);
const endEvent = dispatchKeyboardEvent(select, 'keydown', PAGE_DOWN);
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(7);
expect(endEvent.defaultPrevented).toBe(true);
expect(lastOption.selected)
.withContext('Expected last option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from last option to have been set on the model.')
.toBe(lastOption.value);
const homeEvent = dispatchKeyboardEvent(select, 'keydown', PAGE_UP);
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(0);
expect(homeEvent.defaultPrevented).toBe(true);
expect(firstOption.selected)
.withContext('Expected first option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from first option to have been set on the model.')
.toBe(firstOption.value);
flush();
}));
it('should resume focus from selected item after selecting via click', fakeAsync(() => {
const formControl = fixture.componentInstance.control;
const options = fixture.componentInstance.options.toArray();
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
(overlayContainerElement.querySelectorAll('mat-option')[3] as HTMLElement).click();
fixture.detectChanges();
flush();
expect(formControl.value).toBe(options[3].value);
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
fixture.detectChanges();
expect(formControl.value).toBe(options[4].value);
flush();
}));
it('should select options via LEFT/RIGHT arrow keys on a closed select', fakeAsync(() => {
const formControl = fixture.componentInstance.control;
const options = fixture.componentInstance.options.toArray();
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
dispatchKeyboardEvent(select, 'keydown', RIGHT_ARROW);
expect(options[0].selected)
.withContext('Expected first option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from first option to have been set on the model.')
.toBe(options[0].value);
dispatchKeyboardEvent(select, 'keydown', RIGHT_ARROW);
dispatchKeyboardEvent(select, 'keydown', RIGHT_ARROW);
// Note that the third option is skipped, because it is disabled.
// Note that the third option is skipped, because it is disabled.
expect(options[3].selected)
.withContext('Expected fourth option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from fourth option to have been set on the model.')
.toBe(options[3].value);
dispatchKeyboardEvent(select, 'keydown', LEFT_ARROW);
expect(options[1].selected)
.withContext('Expected second option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from second option to have been set on the model.')
.toBe(options[1].value);
flush();
}));
it('should announce changes via the keyboard on a closed select', fakeAsync(() => {
const liveAnnouncer = TestBed.inject(LiveAnnouncer);
spyOn(liveAnnouncer, 'announce');
dispatchKeyboardEvent(select, 'keydown', RIGHT_ARROW);
expect(liveAnnouncer.announce).toHaveBeenCalledWith('Steak', jasmine.any(Number));
flush();
}));
it('should not throw when reaching a reset option using the arrow keys on a closed select', fakeAsync(() => {
fixture.componentInstance.foods = [
{value: 'steak-0', viewValue: 'Steak'},
{value: null, viewValue: 'None'},
];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.control.setValue('steak-0');
expect(() => {
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
fixture.detectChanges();
}).not.toThrow();
flush();
}));
it('should open a single-selection select using ALT + DOWN_ARROW', () => {
const {control: formControl, select: selectInstance} = fixture.componentInstance;
expect(selectInstance.panelOpen).withContext('Expected select to be closed.').toBe(false);
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
const event = createKeyboardEvent('keydown', DOWN_ARROW, undefined, {alt: true});
dispatchEvent(select, event);
expect(selectInstance.panelOpen).withContext('Expected select to be open.').toBe(true);
expect(formControl.value).withContext('Expected value not to have changed.').toBeFalsy();
});
it('should open a single-selection select using ALT + UP_ARROW', () => {
const {control: formControl, select: selectInstance} = fixture.componentInstance;
expect(selectInstance.panelOpen).withContext('Expected select to be closed.').toBe(false);
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
const event = createKeyboardEvent('keydown', UP_ARROW, undefined, {alt: true});
dispatchEvent(select, event);
expect(selectInstance.panelOpen).withContext('Expected select to be open.').toBe(true);
expect(formControl.value).withContext('Expected value not to have changed.').toBeFalsy();
});
it('should close when pressing ALT + DOWN_ARROW', () => {
const {select: selectInstance} = fixture.componentInstance;
selectInstance.open();
fixture.detectChanges();
expect(selectInstance.panelOpen).withContext('Expected select to be open.').toBe(true);
const event = createKeyboardEvent('keydown', DOWN_ARROW, undefined, {alt: true});
dispatchEvent(select, event);
expect(selectInstance.panelOpen).withContext('Expected select to be closed.').toBe(false);
expect(event.defaultPrevented)
.withContext('Expected default action to be prevented.')
.toBe(true);
});
it('should close when pressing ALT + UP_ARROW', () => {
const {select: selectInstance} = fixture.componentInstance;
selectInstance.open();
fixture.detectChanges();
expect(selectInstance.panelOpen).withContext('Expected select to be open.').toBe(true);
const event = createKeyboardEvent('keydown', UP_ARROW, undefined, {alt: true});
dispatchEvent(select, event);
expect(selectInstance.panelOpen).withContext('Expected select to be closed.').toBe(false);
expect(event.defaultPrevented)
.withContext('Expected default action to be prevented.')
.toBe(true);
});
it('should be able to select options by typing on a closed select', fakeAsync(() => {
const formControl = fixture.componentInstance.control;
const options = fixture.componentInstance.options.toArray();
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
dispatchEvent(select, createKeyboardEvent('keydown', 80, 'p'));
tick(DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL);
expect(options[1].selected)
.withContext('Expected second option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from second option to have been set on the model.')
.toBe(options[1].value);
dispatchEvent(select, createKeyboardEvent('keydown', 69, 'e'));
tick(DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL);
expect(options[5].selected)
.withContext('Expected sixth option to be selected.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from sixth option to have been set on the model.')
.toBe(options[5].value);
})); | {
"end_byte": 24673,
"start_byte": 14301,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_24683_35056 | it('should not open the select when pressing space while typing', fakeAsync(() => {
const selectInstance = fixture.componentInstance.select;
fixture.componentInstance.typeaheadDebounceInterval = DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(selectInstance.panelOpen)
.withContext('Expected select to be closed on init.')
.toBe(false);
dispatchEvent(select, createKeyboardEvent('keydown', 80, 'p'));
tick(DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL / 2);
fixture.detectChanges();
dispatchKeyboardEvent(select, 'keydown', SPACE);
fixture.detectChanges();
expect(selectInstance.panelOpen)
.withContext('Expected select to remain closed after space was pressed.')
.toBe(false);
tick(DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL / 2);
fixture.detectChanges();
expect(selectInstance.panelOpen)
.withContext('Expected select to be closed when the timer runs out.')
.toBe(false);
}));
it('should be able to customize the typeahead debounce interval', fakeAsync(() => {
const formControl = fixture.componentInstance.control;
const options = fixture.componentInstance.options.toArray();
fixture.componentInstance.typeaheadDebounceInterval = 1337;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
dispatchEvent(select, createKeyboardEvent('keydown', 80, 'p'));
tick(DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL);
expect(formControl.value)
.withContext('Expected no value after a bit of time has passed.')
.toBeFalsy();
tick(1337);
expect(options[1].selected)
.withContext('Expected second option to be selected after all the time has passed.')
.toBe(true);
expect(formControl.value)
.withContext('Expected value from second option to have been set on the model.')
.toBe(options[1].value);
}));
it('should cancel the typeahead selection on blur', fakeAsync(() => {
const formControl = fixture.componentInstance.control;
const options = fixture.componentInstance.options.toArray();
expect(formControl.value).withContext('Expected no initial value.').toBeFalsy();
dispatchEvent(select, createKeyboardEvent('keydown', 80, 'p'));
dispatchFakeEvent(select, 'blur');
tick(DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL);
expect(options.some(o => o.selected))
.withContext('Expected no options to be selected.')
.toBe(false);
expect(formControl.value).withContext('Expected no value to be assigned.').toBeFalsy();
}));
it('should open the panel when pressing a vertical arrow key on a closed multiple select', () => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
const instance = multiFixture.componentInstance;
multiFixture.detectChanges();
select = multiFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
const initialValue = instance.control.value;
expect(instance.select.panelOpen).withContext('Expected panel to be closed.').toBe(false);
const event = dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
expect(instance.select.panelOpen).withContext('Expected panel to be open.').toBe(true);
expect(instance.control.value)
.withContext('Expected value to stay the same.')
.toBe(initialValue);
expect(event.defaultPrevented)
.withContext('Expected default to be prevented.')
.toBe(true);
});
it('should open the panel when pressing a horizontal arrow key on closed multiple select', () => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
const instance = multiFixture.componentInstance;
multiFixture.detectChanges();
select = multiFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
const initialValue = instance.control.value;
expect(instance.select.panelOpen).withContext('Expected panel to be closed.').toBe(false);
const event = dispatchKeyboardEvent(select, 'keydown', RIGHT_ARROW);
expect(instance.select.panelOpen).withContext('Expected panel to be open.').toBe(true);
expect(instance.control.value)
.withContext('Expected value to stay the same.')
.toBe(initialValue);
expect(event.defaultPrevented)
.withContext('Expected default to be prevented.')
.toBe(true);
});
it('should do nothing when typing on a closed multi-select', () => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
const instance = multiFixture.componentInstance;
multiFixture.detectChanges();
select = multiFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
const initialValue = instance.control.value;
expect(instance.select.panelOpen).withContext('Expected panel to be closed.').toBe(false);
dispatchEvent(select, createKeyboardEvent('keydown', 80, 'p'));
expect(instance.select.panelOpen)
.withContext('Expected panel to stay closed.')
.toBe(false);
expect(instance.control.value)
.withContext('Expected value to stay the same.')
.toBe(initialValue);
});
it('should do nothing if the key manager did not change the active item', () => {
const formControl = fixture.componentInstance.control;
expect(formControl.value)
.withContext('Expected form control value to be empty.')
.toBeNull();
expect(formControl.pristine).withContext('Expected form control to be clean.').toBe(true);
dispatchKeyboardEvent(select, 'keydown', 16); // Press a random key.
expect(formControl.value)
.withContext('Expected form control value to stay empty.')
.toBeNull();
expect(formControl.pristine)
.withContext('Expected form control to stay clean.')
.toBe(true);
});
it('should continue from the selected option when the value is set programmatically', fakeAsync(() => {
const formControl = fixture.componentInstance.control;
formControl.setValue('eggs-5');
fixture.detectChanges();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
expect(formControl.value).toBe('pasta-6');
expect(fixture.componentInstance.options.toArray()[6].selected).toBe(true);
flush();
}));
it('should not shift focus when the selected options are updated programmatically in a multi select', () => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
multiFixture.detectChanges();
select = multiFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
multiFixture.componentInstance.select.open();
multiFixture.detectChanges();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
select.focus();
multiFixture.detectChanges();
multiFixture.componentInstance.select._keyManager.setActiveItem(3);
multiFixture.detectChanges();
expect(document.activeElement)
.withContext('Expected select to have DOM focus.')
.toBe(select);
expect(select.getAttribute('aria-activedescendant'))
.withContext('Expected fourth option to be activated.')
.toBe(options[3].id);
multiFixture.componentInstance.control.setValue(['steak-0', 'sushi-7']);
multiFixture.detectChanges();
expect(document.activeElement)
.withContext('Expected select to have DOM focus.')
.toBe(select);
expect(select.getAttribute('aria-activedescendant'))
.withContext('Expected fourth optino to remain activated.')
.toBe(options[3].id);
});
it('should not cycle through the options if the control is disabled', () => {
const formControl = fixture.componentInstance.control;
formControl.setValue('eggs-5');
formControl.disable();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
expect(formControl.value)
.withContext('Expected value to remain unchaged.')
.toBe('eggs-5');
});
it('should not wrap selection after reaching the end of the options', () => {
const lastOption = fixture.componentInstance.options.last;
fixture.componentInstance.options.forEach(() => {
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
});
expect(lastOption.selected)
.withContext('Expected last option to be selected.')
.toBe(true);
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
expect(lastOption.selected)
.withContext('Expected last option to stay selected.')
.toBe(true);
});
it('should not open a multiple select when tabbing through', () => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
multiFixture.detectChanges();
select = multiFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
expect(multiFixture.componentInstance.select.panelOpen)
.withContext('Expected panel to be closed initially.')
.toBe(false);
dispatchKeyboardEvent(select, 'keydown', TAB);
expect(multiFixture.componentInstance.select.panelOpen)
.withContext('Expected panel to stay closed.')
.toBe(false);
}); | {
"end_byte": 35056,
"start_byte": 24683,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_35066_46011 | it('should toggle the next option when pressing shift + DOWN_ARROW on a multi-select', fakeAsync(() => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
const event = createKeyboardEvent('keydown', DOWN_ARROW, undefined, {shift: true});
multiFixture.detectChanges();
select = multiFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
multiFixture.componentInstance.select.open();
multiFixture.detectChanges();
flush();
expect(multiFixture.componentInstance.select.value).toBeFalsy();
dispatchEvent(select, event);
multiFixture.detectChanges();
expect(multiFixture.componentInstance.select.value).toEqual(['pizza-1']);
dispatchEvent(select, event);
multiFixture.detectChanges();
expect(multiFixture.componentInstance.select.value).toEqual(['pizza-1', 'tacos-2']);
}));
it('should toggle the previous option when pressing shift + UP_ARROW on a multi-select', fakeAsync(() => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
const event = createKeyboardEvent('keydown', UP_ARROW, undefined, {shift: true});
multiFixture.detectChanges();
select = multiFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
multiFixture.componentInstance.select.open();
multiFixture.detectChanges();
flush();
// Move focus down first.
for (let i = 0; i < 5; i++) {
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
multiFixture.detectChanges();
}
expect(multiFixture.componentInstance.select.value).toBeFalsy();
dispatchEvent(select, event);
multiFixture.detectChanges();
expect(multiFixture.componentInstance.select.value).toEqual(['chips-4']);
dispatchEvent(select, event);
multiFixture.detectChanges();
expect(multiFixture.componentInstance.select.value).toEqual(['sandwich-3', 'chips-4']);
}));
it('should prevent the default action when pressing space', () => {
const event = dispatchKeyboardEvent(select, 'keydown', SPACE);
expect(event.defaultPrevented).toBe(true);
});
it('should prevent the default action when pressing enter', () => {
const event = dispatchKeyboardEvent(select, 'keydown', ENTER);
expect(event.defaultPrevented).toBe(true);
});
it('should not prevent the default actions on selection keys when pressing a modifier', () => {
[ENTER, SPACE].forEach(key => {
const event = createKeyboardEvent('keydown', key, undefined, {shift: true});
expect(event.defaultPrevented).toBe(false);
});
});
it('should consider the selection a result of a user action when closed', fakeAsync(() => {
const option = fixture.componentInstance.options.first;
const spy = jasmine.createSpy('option selection spy');
const subscription = option.onSelectionChange
.pipe(map(e => e.isUserInput))
.subscribe(spy);
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
expect(spy).toHaveBeenCalledWith(true);
subscription.unsubscribe();
flush();
}));
it('should be able to focus the select trigger', () => {
document.body.focus(); // ensure that focus isn't on the trigger already
fixture.componentInstance.select.focus();
expect(document.activeElement)
.withContext('Expected select element to be focused.')
.toBe(select);
});
it('should set `aria-multiselectable` to true on the listbox inside multi select', fakeAsync(() => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
multiFixture.detectChanges();
select = multiFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
multiFixture.componentInstance.select.open();
multiFixture.detectChanges();
flush();
const panel = document.querySelector('.mat-mdc-select-panel')!;
expect(panel.getAttribute('aria-multiselectable')).toBe('true');
}));
it('should set aria-multiselectable false on single-selection instances', fakeAsync(() => {
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
const panel = document.querySelector('.mat-mdc-select-panel')!;
expect(panel.getAttribute('aria-multiselectable')).toBe('false');
}));
it('should set aria-activedescendant only while the panel is open', fakeAsync(() => {
fixture.componentInstance.control.setValue('chips-4');
fixture.detectChanges();
const host = fixture.debugElement.query(By.css('mat-select'))!.nativeElement;
expect(host.hasAttribute('aria-activedescendant'))
.withContext('Expected no aria-activedescendant on init.')
.toBe(false);
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll('mat-option');
expect(host.getAttribute('aria-activedescendant'))
.withContext('Expected aria-activedescendant to match the active option.')
.toBe(options[4].id);
fixture.componentInstance.select.close();
fixture.detectChanges();
flush();
expect(host.hasAttribute('aria-activedescendant'))
.withContext('Expected no aria-activedescendant when closed.')
.toBe(false);
}));
it('should set aria-activedescendant based on the focused option', fakeAsync(() => {
const host = fixture.debugElement.query(By.css('mat-select'))!.nativeElement;
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll('mat-option');
expect(host.getAttribute('aria-activedescendant')).toBe(options[0].id);
[1, 2, 3].forEach(() => {
dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW);
fixture.detectChanges();
});
expect(host.getAttribute('aria-activedescendant')).toBe(options[3].id);
dispatchKeyboardEvent(host, 'keydown', UP_ARROW);
fixture.detectChanges();
expect(host.getAttribute('aria-activedescendant')).toBe(options[2].id);
}));
it('should not change the aria-activedescendant using the horizontal arrow keys', fakeAsync(() => {
const host = fixture.debugElement.query(By.css('mat-select'))!.nativeElement;
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll('mat-option');
expect(host.getAttribute('aria-activedescendant')).toBe(options[0].id);
[1, 2, 3].forEach(() => {
dispatchKeyboardEvent(host, 'keydown', RIGHT_ARROW);
fixture.detectChanges();
});
expect(host.getAttribute('aria-activedescendant')).toBe(options[0].id);
}));
it('should restore focus to the trigger after selecting an option in multi-select mode', () => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
const instance = multiFixture.componentInstance;
multiFixture.detectChanges();
select = multiFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
instance.select.open();
multiFixture.detectChanges();
// Ensure that the select isn't focused to begin with.
select.blur();
expect(document.activeElement).not.toBe(select, 'Expected trigger not to be focused.');
const option = overlayContainerElement.querySelector('mat-option')! as HTMLElement;
option.click();
multiFixture.detectChanges();
expect(document.activeElement)
.withContext('Expected trigger to be focused.')
.toBe(select);
});
it('should set a role of listbox on the select panel', fakeAsync(() => {
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
const panel = document.querySelector('.mat-mdc-select-panel')!;
expect(panel.getAttribute('role')).toBe('listbox');
}));
it('should point the aria-labelledby of the panel to the field label', fakeAsync(() => {
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
const labelId = fixture.nativeElement.querySelector('label').id;
const panel = document.querySelector('.mat-mdc-select-panel')!;
expect(panel.getAttribute('aria-labelledby')).toBe(labelId);
}));
it('should add a custom aria-labelledby to the panel', fakeAsync(() => {
fixture.componentInstance.ariaLabelledby = 'myLabelId';
fixture.changeDetectorRef.markForCheck();
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
const labelId = fixture.nativeElement.querySelector('label').id;
const panel = document.querySelector('.mat-mdc-select-panel')!;
expect(panel.getAttribute('aria-labelledby')).toBe(`${labelId} myLabelId`);
}));
it('should trim the custom panel aria-labelledby when there is no label', fakeAsync(() => {
fixture.componentInstance.hasLabel = false;
fixture.componentInstance.ariaLabelledby = 'myLabelId';
fixture.changeDetectorRef.markForCheck();
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
// Note that we assert that there are no spaces around the value.
const panel = document.querySelector('.mat-mdc-select-panel')!;
expect(panel.getAttribute('aria-labelledby')).toBe(`myLabelId`);
}));
it('should clear aria-labelledby from the panel if an aria-label is set', fakeAsync(() => {
fixture.componentInstance.ariaLabel = 'My label';
fixture.changeDetectorRef.markForCheck();
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
const panel = document.querySelector('.mat-mdc-select-panel')!;
expect(panel.getAttribute('aria-label')).toBe('My label');
expect(panel.hasAttribute('aria-labelledby')).toBe(false);
}));
}); | {
"end_byte": 46011,
"start_byte": 35066,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_46019_56423 | describe('for select inside a modal', () => {
let fixture: ComponentFixture<SelectInsideAModal>;
beforeEach(() => {
fixture = TestBed.createComponent(SelectInsideAModal);
fixture.detectChanges();
});
it('should add the id of the select panel to the aria-owns of the modal', () => {
fixture.componentInstance.select.open();
fixture.detectChanges();
const panelId = `${fixture.componentInstance.select.id}-panel`;
const modalElement = fixture.componentInstance.modal.nativeElement;
expect(modalElement.getAttribute('aria-owns')?.split(' '))
.withContext('expecting modal to own the select panel')
.toContain(panelId);
});
});
describe('for options', () => {
let fixture: ComponentFixture<BasicSelect>;
let trigger: HTMLElement;
let options: HTMLElement[];
beforeEach(() => {
fixture = TestBed.createComponent(BasicSelect);
fixture.detectChanges();
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
trigger.click();
fixture.detectChanges();
options = Array.from(overlayContainerElement.querySelectorAll('mat-option'));
});
it('should set the role of mat-option to option', fakeAsync(() => {
expect(options[0].getAttribute('role')).toEqual('option');
expect(options[1].getAttribute('role')).toEqual('option');
expect(options[2].getAttribute('role')).toEqual('option');
}));
it('should set aria-selected on each option for single select', fakeAsync(() => {
expect(options.every(option => option.getAttribute('aria-selected') === 'false'))
.withContext(
'Expected all unselected single-select options to have ' + 'aria-selected="false".',
)
.toBe(true);
options[1].click();
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
expect(options[1].getAttribute('aria-selected'))
.withContext(
'Expected selected single-select option to have ' + 'aria-selected="true".',
)
.toEqual('true');
options.splice(1, 1);
expect(options.every(option => option.getAttribute('aria-selected') === 'false'))
.withContext(
'Expected all unselected single-select options to have ' + 'aria-selected="false".',
)
.toBe(true);
}));
it('should set aria-selected on each option for multi-select', fakeAsync(() => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
multiFixture.detectChanges();
trigger = multiFixture.debugElement.query(
By.css('.mat-mdc-select-trigger'),
)!.nativeElement;
trigger.click();
multiFixture.detectChanges();
options = Array.from(overlayContainerElement.querySelectorAll('mat-option'));
expect(
options.every(
option =>
option.hasAttribute('aria-selected') &&
option.getAttribute('aria-selected') === 'false',
),
)
.withContext(
'Expected all unselected multi-select options to have ' + 'aria-selected="false".',
)
.toBe(true);
options[1].click();
multiFixture.detectChanges();
trigger.click();
multiFixture.detectChanges();
flush();
expect(options[1].getAttribute('aria-selected'))
.withContext('Expected selected multi-select option to have aria-selected="true".')
.toEqual('true');
options.splice(1, 1);
expect(
options.every(
option =>
option.hasAttribute('aria-selected') &&
option.getAttribute('aria-selected') === 'false',
),
)
.withContext(
'Expected all unselected multi-select options to have ' + 'aria-selected="false".',
)
.toBe(true);
}));
it('should omit the tabindex attribute on each option', fakeAsync(() => {
expect(options[0].hasAttribute('tabindex')).toBeFalse();
expect(options[1].hasAttribute('tabindex')).toBeFalse();
expect(options[2].hasAttribute('tabindex')).toBeFalse();
}));
it('should set aria-disabled for disabled options', fakeAsync(() => {
expect(options[0].getAttribute('aria-disabled')).toEqual('false');
expect(options[1].getAttribute('aria-disabled')).toEqual('false');
expect(options[2].getAttribute('aria-disabled')).toEqual('true');
fixture.componentInstance.foods[2]['disabled'] = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(options[0].getAttribute('aria-disabled')).toEqual('false');
expect(options[1].getAttribute('aria-disabled')).toEqual('false');
expect(options[2].getAttribute('aria-disabled')).toEqual('false');
}));
it('should remove the active state from options that have been deselected while closed', fakeAsync(() => {
let activeOptions = options.filter(option => {
return option.classList.contains('mat-mdc-option-active');
});
expect(activeOptions)
.withContext('Expected first option to have active styles.')
.toEqual([options[0]]);
options[1].click();
fixture.detectChanges();
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
activeOptions = options.filter(option => {
return option.classList.contains('mat-mdc-option-active');
});
expect(activeOptions)
.withContext(
'Expected only selected option to be marked as active after it is ' + 'clicked.',
)
.toEqual([options[1]]);
fixture.componentInstance.control.setValue(fixture.componentInstance.foods[7].value);
fixture.detectChanges();
fixture.componentInstance.select.close();
fixture.detectChanges();
flush();
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
activeOptions = options.filter(option => {
return option.classList.contains('mat-mdc-option-active');
});
expect(activeOptions)
.withContext(
'Expected only selected option to be marked as active after the ' +
'value has changed.',
)
.toEqual([options[7]]);
}));
it('should render a checkmark on selected option', fakeAsync(() => {
fixture.componentInstance.control.setValue(fixture.componentInstance.foods[2].value);
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
const pseudoCheckboxes = options
.map(option => option.querySelector('.mat-pseudo-checkbox-minimal'))
.filter((x): x is HTMLElement => !!x);
const selectedOption = options[2];
expect(selectedOption.querySelector('.mat-pseudo-checkbox-minimal')).not.toBeNull();
expect(pseudoCheckboxes.length).toBe(1);
}));
it('should render checkboxes for multi-select', fakeAsync(() => {
fixture.destroy();
const multiFixture = TestBed.createComponent(MultiSelect);
multiFixture.detectChanges();
multiFixture.componentInstance.control.setValue([
multiFixture.componentInstance.foods[2].value,
]);
multiFixture.detectChanges();
trigger = multiFixture.debugElement.query(
By.css('.mat-mdc-select-trigger'),
)!.nativeElement;
trigger.click();
multiFixture.detectChanges();
flush();
options = Array.from(overlayContainerElement.querySelectorAll('mat-option'));
const pseudoCheckboxes = options
.map(option => option.querySelector('.mat-pseudo-checkbox.mat-pseudo-checkbox-full'))
.filter((x): x is HTMLElement => !!x);
const selectedPseudoCheckbox = pseudoCheckboxes[2];
expect(pseudoCheckboxes.length)
.withContext('expecting each option to have a pseudo-checkbox with "full" appearance')
.toEqual(options.length);
expect(selectedPseudoCheckbox.classList)
.withContext('expecting selected pseudo-checkbox to be checked')
.toContain('mat-pseudo-checkbox-checked');
}));
});
describe('for option groups', () => {
let fixture: ComponentFixture<SelectWithGroups>;
let trigger: HTMLElement;
let groups: NodeListOf<HTMLElement>;
beforeEach(() => {
fixture = TestBed.createComponent(SelectWithGroups);
fixture.detectChanges();
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
trigger.click();
fixture.detectChanges();
groups = overlayContainerElement.querySelectorAll(
'mat-optgroup',
) as NodeListOf<HTMLElement>;
});
it('should set the appropriate role', fakeAsync(() => {
expect(groups[0].getAttribute('role')).toBe('group');
}));
it('should set the `aria-labelledby` attribute', fakeAsync(() => {
let group = groups[0];
let label = group.querySelector('.mat-mdc-optgroup-label') as HTMLElement;
expect(label.getAttribute('id'))
.withContext('Expected label to have an id.')
.toBeTruthy();
expect(group.getAttribute('aria-labelledby'))
.withContext('Expected `aria-labelledby` to match the label id.')
.toBe(label.getAttribute('id'));
}));
it('should set the `aria-disabled` attribute if the group is disabled', fakeAsync(() => {
expect(groups[1].getAttribute('aria-disabled')).toBe('true');
}));
});
}); | {
"end_byte": 56423,
"start_byte": 46019,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_56429_67246 | describe('overlay panel', () => {
let fixture: ComponentFixture<BasicSelect>;
let formField: HTMLElement;
let trigger: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(BasicSelect);
fixture.detectChanges();
formField = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
trigger = formField.querySelector('.mat-mdc-select-trigger') as HTMLElement;
});
it('should not throw when attempting to open too early', () => {
// Create component and then immediately open without running change detection
fixture = TestBed.createComponent(BasicSelect);
expect(() => fixture.componentInstance.select.open()).not.toThrow();
});
it('should open the panel when trigger is clicked', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select.panelOpen).toBe(true);
expect(overlayContainerElement.textContent).toContain('Steak');
expect(overlayContainerElement.textContent).toContain('Pizza');
expect(overlayContainerElement.textContent).toContain('Tacos');
}));
it('should close the panel when an item is clicked', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
const option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
option.click();
fixture.detectChanges();
flush();
expect(overlayContainerElement.textContent).toEqual('');
expect(fixture.componentInstance.select.panelOpen).toBe(false);
}));
it('should close the panel when a click occurs outside the panel', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
const backdrop = overlayContainerElement.querySelector(
'.cdk-overlay-backdrop',
) as HTMLElement;
backdrop.click();
fixture.detectChanges();
flush();
expect(overlayContainerElement.textContent).toEqual('');
expect(fixture.componentInstance.select.panelOpen).toBe(false);
}));
it('should set the width of the overlay based on the trigger', fakeAsync(() => {
formField.style.width = '200px';
trigger.click();
fixture.detectChanges();
flush();
const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
expect(pane.style.width).toBe('200px');
}));
it('should update the width of the panel on resize', fakeAsync(() => {
formField.style.width = '300px';
trigger.click();
fixture.detectChanges();
flush();
const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
const initialWidth = parseInt(pane.style.width || '0');
expect(initialWidth).toBeGreaterThan(0);
formField.style.width = '400px';
dispatchFakeEvent(window, 'resize');
fixture.detectChanges();
tick(1000);
fixture.detectChanges();
expect(parseInt(pane.style.width || '0')).toBeGreaterThan(initialWidth);
}));
it('should be able to set a custom width on the select panel', fakeAsync(() => {
fixture.componentInstance.panelWidth = '42px';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
expect(pane.style.width).toBe('42px');
}));
it('should not set a width on the panel if panelWidth is null', fakeAsync(() => {
fixture.componentInstance.panelWidth = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
expect(pane.style.width).toBeFalsy();
}));
it('should not set a width on the panel if panelWidth is an empty string', fakeAsync(() => {
fixture.componentInstance.panelWidth = '';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
expect(pane.style.width).toBeFalsy();
}));
it('should not attempt to open a select that does not have any options', () => {
fixture.componentInstance.foods = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
expect(fixture.componentInstance.select.panelOpen).toBe(false);
});
it('should close the panel when tabbing out', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select.panelOpen).toBe(true);
dispatchKeyboardEvent(trigger, 'keydown', TAB);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select.panelOpen).toBe(false);
}));
it('should restore focus to the host before tabbing away', fakeAsync(() => {
const select = fixture.nativeElement.querySelector('.mat-mdc-select');
trigger.click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select.panelOpen).toBe(true);
// Use a spy since focus can be flaky in unit tests.
spyOn(select, 'focus').and.callThrough();
dispatchKeyboardEvent(trigger, 'keydown', TAB);
fixture.detectChanges();
flush();
expect(select.focus).toHaveBeenCalled();
}));
it('should close when tabbing out from inside the panel', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select.panelOpen).toBe(true);
const panel = overlayContainerElement.querySelector('.mat-mdc-select-panel')!;
dispatchKeyboardEvent(panel, 'keydown', TAB);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select.panelOpen).toBe(false);
}));
it('should focus the first option when pressing HOME', fakeAsync(() => {
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
const event = dispatchKeyboardEvent(trigger, 'keydown', HOME);
fixture.detectChanges();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(0);
expect(event.defaultPrevented).toBe(true);
}));
it('should focus the last option when pressing END', fakeAsync(() => {
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
const event = dispatchKeyboardEvent(trigger, 'keydown', END);
fixture.detectChanges();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(7);
expect(event.defaultPrevented).toBe(true);
}));
it('should focus the last option when pressing PAGE_DOWN with less than 10 options', fakeAsync(() => {
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
const event = dispatchKeyboardEvent(trigger, 'keydown', PAGE_DOWN);
fixture.detectChanges();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(7);
expect(event.defaultPrevented).toBe(true);
}));
it('should focus the first option when pressing PAGE_UP with index < 10', fakeAsync(() => {
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBeLessThan(10);
const event = dispatchKeyboardEvent(trigger, 'keydown', PAGE_UP);
fixture.detectChanges();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(0);
expect(event.defaultPrevented).toBe(true);
}));
it('should be able to set extra classes on the panel', () => {
trigger.click();
fixture.detectChanges();
const panel = overlayContainerElement.querySelector('.mat-mdc-select-panel') as HTMLElement;
expect(panel.classList).toContain('custom-one');
expect(panel.classList).toContain('custom-two');
});
it('should update disableRipple properly on each option', () => {
const options = fixture.componentInstance.options.toArray();
expect(options.every(option => option.disableRipple === false))
.withContext('Expected all options to have disableRipple set to false initially.')
.toBeTruthy();
fixture.componentInstance.disableRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(options.every(option => option.disableRipple === true))
.withContext('Expected all options to have disableRipple set to true.')
.toBeTruthy();
});
it('should not show ripples if they were disabled', fakeAsync(() => {
fixture.componentInstance.disableRipple = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
const option = overlayContainerElement.querySelector('mat-option')!;
dispatchFakeEvent(option, 'mousedown');
dispatchFakeEvent(option, 'mouseup');
expect(option.querySelectorAll('.mat-ripple-element').length).toBe(0);
}));
it('should be able to render options inside groups with an ng-container', () => {
fixture.destroy();
const groupFixture = TestBed.createComponent(SelectWithGroupsAndNgContainer);
groupFixture.detectChanges();
trigger = groupFixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
trigger.click();
groupFixture.detectChanges();
expect(document.querySelectorAll('.cdk-overlay-container mat-option').length)
.withContext('Expected at least one option to be rendered.')
.toBeGreaterThan(0);
}); | {
"end_byte": 67246,
"start_byte": 56429,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_67254_68022 | it('should not consider itself as blurred if the trigger loses focus while the panel is still open', fakeAsync(() => {
const selectElement = fixture.nativeElement.querySelector('.mat-mdc-select');
const selectInstance = fixture.componentInstance.select;
dispatchFakeEvent(selectElement, 'focus');
fixture.detectChanges();
expect(selectInstance.focused).withContext('Expected select to be focused.').toBe(true);
selectInstance.open();
fixture.detectChanges();
flush();
dispatchFakeEvent(selectElement, 'blur');
fixture.detectChanges();
expect(selectInstance.focused)
.withContext('Expected select element to remain focused.')
.toBe(true);
}));
}); | {
"end_byte": 68022,
"start_byte": 67254,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_68028_78644 | describe('selection logic', () => {
let fixture: ComponentFixture<BasicSelect>;
let trigger: HTMLElement;
let formField: HTMLElement;
let label: HTMLLabelElement;
beforeEach(() => {
fixture = TestBed.createComponent(BasicSelect);
fixture.detectChanges();
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
formField = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
label = formField.querySelector('label')!;
});
it('should not float label if no option is selected', () => {
expect(label.classList.contains('mat-form-field-should-float'))
.withContext('Label should not be floating')
.toBe(false);
});
it('should focus the first option if no option is selected', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toEqual(0);
}));
it('should select an option when it is clicked', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
let option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
option.click();
fixture.detectChanges();
flush();
trigger.click();
fixture.detectChanges();
flush();
option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
expect(option.classList).toContain('mdc-list-item--selected');
expect(fixture.componentInstance.options.first.selected).toBe(true);
expect(fixture.componentInstance.select.selected).toBe(
fixture.componentInstance.options.first,
);
}));
it('should be able to select an option using the MatOption API', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
const optionInstances = fixture.componentInstance.options.toArray();
const optionNodes: NodeListOf<HTMLElement> =
overlayContainerElement.querySelectorAll('mat-option');
optionInstances[1].select();
fixture.detectChanges();
expect(optionNodes[1].classList).toContain('mdc-list-item--selected');
expect(optionInstances[1].selected).toBe(true);
expect(fixture.componentInstance.select.selected).toBe(optionInstances[1]);
}));
it('should deselect other options when one is selected', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
let options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[0].click();
fixture.detectChanges();
flush();
trigger.click();
fixture.detectChanges();
flush();
options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>;
expect(options[1].classList).not.toContain('mdc-list-item--selected');
expect(options[2].classList).not.toContain('mdc-list-item--selected');
const optionInstances = fixture.componentInstance.options.toArray();
expect(optionInstances[1].selected).toBe(false);
expect(optionInstances[2].selected).toBe(false);
}));
it('should deselect other options when one is programmatically selected', fakeAsync(() => {
let control = fixture.componentInstance.control;
let foods = fixture.componentInstance.foods;
trigger.click();
fixture.detectChanges();
flush();
let options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[0].click();
fixture.detectChanges();
flush();
control.setValue(foods[1].value);
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>;
expect(options[0].classList).not.toContain(
'mdc-list-item--selected',
'Expected first option to no longer be selected',
);
expect(options[1].classList)
.withContext('Expected second option to be selected')
.toContain('mdc-list-item--selected');
const optionInstances = fixture.componentInstance.options.toArray();
expect(optionInstances[0].selected)
.withContext('Expected first option to no longer be selected')
.toBe(false);
expect(optionInstances[1].selected)
.withContext('Expected second option to be selected')
.toBe(true);
}));
it('should remove selection if option has been removed', fakeAsync(() => {
let select = fixture.componentInstance.select;
trigger.click();
fixture.detectChanges();
flush();
let firstOption = overlayContainerElement.querySelectorAll('mat-option')[0] as HTMLElement;
firstOption.click();
fixture.detectChanges();
expect(select.selected)
.withContext('Expected first option to be selected.')
.toBe(select.options.first);
fixture.componentInstance.foods = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(select.selected)
.withContext('Expected selection to be removed when option no longer exists.')
.toBeUndefined();
}));
it('should display the selected option in the trigger', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
const option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
option.click();
fixture.detectChanges();
flush();
const value = fixture.debugElement.query(By.css('.mat-mdc-select-value'))!.nativeElement;
expect(label.classList.contains('mdc-floating-label--float-above'))
.withContext('Label should be floating')
.toBe(true);
expect(value.textContent).toContain('Steak');
}));
it('should focus the selected option if an option is selected', fakeAsync(() => {
// must wait for initial writeValue promise to finish
flush();
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
// must wait for animation to finish
fixture.detectChanges();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toEqual(1);
}));
it('should select an option that was added after initialization', fakeAsync(() => {
fixture.componentInstance.foods.push({viewValue: 'Potatoes', value: 'potatoes-8'});
trigger.click();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[8].click();
fixture.detectChanges();
flush();
expect(trigger.textContent).toContain('Potatoes');
expect(fixture.componentInstance.select.selected).toBe(
fixture.componentInstance.options.last,
);
}));
it('should update the trigger when the selected option label is changed', fakeAsync(() => {
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
expect(trigger.textContent!.trim()).toBe('Pizza');
fixture.componentInstance.foods[1].viewValue = 'Calzone';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(trigger.textContent!.trim()).toBe('Calzone');
}));
it('should update the trigger value if the text as a result of an expression change', fakeAsync(() => {
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
expect(trigger.textContent!.trim()).toBe('Pizza');
fixture.componentInstance.capitalize = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.checkNoChanges();
expect(trigger.textContent!.trim()).toBe('PIZZA');
}));
it('should not select disabled options', () => {
trigger.click();
fixture.detectChanges();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[2].click();
fixture.detectChanges();
expect(fixture.componentInstance.select.panelOpen).toBe(true);
expect(options[2].classList).not.toContain('mdc-list-item--selected');
expect(fixture.componentInstance.select.selected).toBeUndefined();
});
it('should not select options inside a disabled group', () => {
fixture.destroy();
const groupFixture = TestBed.createComponent(SelectWithGroups);
groupFixture.detectChanges();
groupFixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement.click();
groupFixture.detectChanges();
const disabledGroup = overlayContainerElement.querySelectorAll('mat-optgroup')[1];
const options = disabledGroup.querySelectorAll('mat-option');
(options[0] as HTMLElement).click();
groupFixture.detectChanges();
expect(groupFixture.componentInstance.select.panelOpen).toBe(true);
expect(options[0].classList).not.toContain('mdc-list-item--selected');
expect(groupFixture.componentInstance.select.selected).toBeUndefined();
});
it('should not throw if triggerValue accessed with no selected value', fakeAsync(() => {
expect(() => fixture.componentInstance.select.triggerValue).not.toThrow();
}));
it('should emit to `optionSelectionChanges` when an option is selected', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
const spy = jasmine.createSpy('option selection spy');
const subscription = fixture.componentInstance.select.optionSelectionChanges.subscribe(spy);
const option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
option.click();
fixture.detectChanges();
flush();
expect(spy).toHaveBeenCalledWith(jasmine.any(MatOptionSelectionChange));
subscription.unsubscribe();
})); | {
"end_byte": 78644,
"start_byte": 68028,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_78652_81319 | it('should handle accessing `optionSelectionChanges` before the options are initialized', fakeAsync(() => {
fixture.destroy();
fixture = TestBed.createComponent(BasicSelect);
let spy = jasmine.createSpy('option selection spy');
let subscription: Subscription;
expect(fixture.componentInstance.select.options).toBeFalsy();
expect(() => {
subscription = fixture.componentInstance.select.optionSelectionChanges.subscribe(spy);
}).not.toThrow();
fixture.detectChanges();
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
trigger.click();
fixture.detectChanges();
flush();
const option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
option.click();
fixture.detectChanges();
flush();
expect(spy).toHaveBeenCalledWith(jasmine.any(MatOptionSelectionChange));
subscription!.unsubscribe();
}));
it('should emit to `optionSelectionChanges` after the list of options has changed', fakeAsync(() => {
let spy = jasmine.createSpy('option selection spy');
let subscription = fixture.componentInstance.select.optionSelectionChanges.subscribe(spy);
let selectFirstOption = () => {
trigger.click();
fixture.detectChanges();
flush();
const option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
option.click();
fixture.detectChanges();
flush();
};
fixture.componentInstance.foods = [{value: 'salad-8', viewValue: 'Salad'}];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
selectFirstOption();
expect(spy).toHaveBeenCalledTimes(1);
fixture.componentInstance.foods = [{value: 'fruit-9', viewValue: 'Fruit'}];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
selectFirstOption();
expect(spy).toHaveBeenCalledTimes(2);
subscription!.unsubscribe();
}));
it('should not indicate programmatic value changes as user interactions', () => {
const events: MatOptionSelectionChange[] = [];
const subscription = fixture.componentInstance.select.optionSelectionChanges.subscribe(
(event: MatOptionSelectionChange) => events.push(event),
);
fixture.componentInstance.control.setValue('eggs-5');
fixture.detectChanges();
expect(events.map(event => event.isUserInput)).toEqual([false]);
subscription.unsubscribe();
});
}); | {
"end_byte": 81319,
"start_byte": 78652,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_81325_90946 | describe('forms integration', () => {
let fixture: ComponentFixture<BasicSelect>;
let trigger: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(BasicSelect);
fixture.detectChanges();
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
});
it('should take an initial view value with reactive forms', fakeAsync(() => {
fixture.componentInstance.control = new FormControl('pizza-1');
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const value = fixture.debugElement.query(By.css('.mat-mdc-select-value'))!;
expect(value.nativeElement.textContent)
.withContext(`Expected trigger to be populated by the control's initial value.`)
.toContain('Pizza');
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
trigger.click();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
expect(options[1].classList)
.withContext(`Expected option with the control's initial value to be selected.`)
.toContain('mdc-list-item--selected');
}));
it('should set the view value from the form', fakeAsync(() => {
let value = fixture.debugElement.query(By.css('.mat-mdc-select-value'))!;
expect(value.nativeElement.textContent.trim()).toBe('Food');
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
value = fixture.debugElement.query(By.css('.mat-mdc-select-value'))!;
expect(value.nativeElement.textContent)
.withContext(`Expected trigger to be populated by the control's new value.`)
.toContain('Pizza');
trigger.click();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
expect(options[1].classList)
.withContext(`Expected option with the control's new value to be selected.`)
.toContain('mdc-list-item--selected');
}));
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);
trigger.click();
fixture.detectChanges();
flush();
const option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
option.click();
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', fakeAsync(() => {
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
fixture.componentInstance.control.setValue('gibberish');
fixture.detectChanges();
const value = fixture.debugElement.query(By.css('.mat-mdc-select-value'))!;
expect(value.nativeElement.textContent.trim())
.withContext(`Expected trigger to show the placeholder.`)
.toBe('Food');
expect(trigger.textContent).not.toContain(
'Pizza',
`Expected trigger is cleared when option value is not found.`,
);
trigger.click();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
expect(options[1].classList).not.toContain(
'mdc-list-item--selected',
`Expected option w/ the old value not to be selected.`,
);
}));
it('should clear the selection when the control is reset', fakeAsync(() => {
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
fixture.componentInstance.control.reset();
fixture.detectChanges();
const value = fixture.debugElement.query(By.css('.mat-mdc-select-value'))!;
expect(value.nativeElement.textContent.trim())
.withContext(`Expected trigger to show the placeholder.`)
.toBe('Food');
expect(trigger.textContent).not.toContain(
'Pizza',
`Expected trigger is cleared when option value is not found.`,
);
trigger.click();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
expect(options[1].classList).not.toContain(
'mdc-list-item--selected',
`Expected option w/ the old value not to be selected.`,
);
}));
it('should set the control to touched when the select is blurred', fakeAsync(() => {
expect(fixture.componentInstance.control.touched)
.withContext(`Expected the control to start off as untouched.`)
.toEqual(false);
trigger.click();
dispatchFakeEvent(trigger, 'blur');
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.touched)
.withContext(`Expected the control to stay untouched when menu opened.`)
.toEqual(false);
const backdrop = overlayContainerElement.querySelector(
'.cdk-overlay-backdrop',
) as HTMLElement;
backdrop.click();
dispatchFakeEvent(trigger, 'blur');
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.touched)
.withContext(`Expected the control to be touched as soon as focus left the select.`)
.toEqual(true);
}));
it('should set the control to touched when the panel is closed', fakeAsync(() => {
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to start off as untouched.')
.toBe(false);
trigger.click();
dispatchFakeEvent(trigger, 'blur');
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to stay untouched when menu opened.')
.toBe(false);
fixture.componentInstance.select.close();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to be touched when the panel was closed.')
.toBe(true);
}));
it('should not set touched when a disabled select is touched', () => {
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to start off as untouched.')
.toBe(false);
fixture.componentInstance.control.disable();
dispatchFakeEvent(trigger, 'blur');
expect(fixture.componentInstance.control.touched)
.withContext('Expected the control to stay untouched.')
.toBe(false);
});
it('should set the control to dirty when the select value changes in DOM', fakeAsync(() => {
expect(fixture.componentInstance.control.dirty)
.withContext(`Expected control to start out pristine.`)
.toEqual(false);
trigger.click();
fixture.detectChanges();
flush();
const option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
option.click();
fixture.detectChanges();
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 label if control is required', fakeAsync(() => {
const label = fixture.nativeElement.querySelector('.mat-mdc-form-field label');
expect(label.querySelector('.mat-mdc-form-field-required-marker'))
.withContext(`Expected label not to have an asterisk, as control was not required.`)
.toBeFalsy();
fixture.componentInstance.isRequired = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(label.querySelector('.mat-mdc-form-field-required-marker'))
.withContext(`Expected label to have an asterisk, as control was required.`)
.toBeTruthy();
}));
it('should propagate the value set through the `value` property to the form field', fakeAsync(() => {
const control = fixture.componentInstance.control;
expect(control.value).toBeFalsy();
fixture.componentInstance.select.value = 'pizza-1';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(control.value).toBe('pizza-1');
}));
}); | {
"end_byte": 90946,
"start_byte": 81325,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_90952_93085 | describe('disabled behavior', () => {
it('should disable itself when control is disabled programmatically', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelect);
fixture.detectChanges();
fixture.componentInstance.control.disable();
fixture.detectChanges();
let trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
expect(getComputedStyle(trigger).getPropertyValue('cursor'))
.withContext(`Expected cursor to be default arrow on disabled control.`)
.toEqual('default');
trigger.click();
fixture.detectChanges();
flush();
expect(overlayContainerElement.textContent)
.withContext(`Expected select panel to stay closed.`)
.toEqual('');
expect(fixture.componentInstance.select.panelOpen)
.withContext(`Expected select panelOpen property to stay false.`)
.toBe(false);
fixture.componentInstance.control.enable();
fixture.detectChanges();
expect(getComputedStyle(trigger).getPropertyValue('cursor'))
.withContext(`Expected cursor to be a pointer on enabled control.`)
.toEqual('pointer');
trigger.click();
fixture.detectChanges();
flush();
expect(overlayContainerElement.textContent)
.withContext(`Expected select panel to open normally on re-enabled control`)
.toContain('Steak');
expect(fixture.componentInstance.select.panelOpen)
.withContext(`Expected select panelOpen property to become true.`)
.toBe(true);
}));
it('should keep the disabled state in sync if the form group is swapped and disabled at the same time', () => {
const fixture = TestBed.createComponent(SelectInsideDynamicFormGroup);
fixture.detectChanges();
const instance = fixture.componentInstance;
expect(instance.select.disabled).toBe(false);
instance.assignGroup(true);
fixture.detectChanges();
expect(instance.select.disabled).toBe(true);
});
}); | {
"end_byte": 93085,
"start_byte": 90952,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_93091_101887 | describe('keyboard scrolling', () => {
let fixture: ComponentFixture<BasicSelect>;
let host: HTMLElement;
let panel: HTMLElement;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(BasicSelect);
fixture.componentInstance.foods = [];
for (let i = 0; i < 30; i++) {
fixture.componentInstance.foods.push({value: `value-${i}`, viewValue: `Option ${i}`});
}
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
fixture.detectChanges();
host = fixture.debugElement.query(By.css('mat-select'))!.nativeElement;
panel = overlayContainerElement.querySelector('.mat-mdc-select-panel')! as HTMLElement;
}));
it('should not scroll to options that are completely in the view', () => {
const initialScrollPosition = panel.scrollTop;
[1, 2, 3].forEach(() => {
dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW);
});
expect(panel.scrollTop)
.withContext('Expected scroll position not to change')
.toBe(initialScrollPosition);
});
it('should scroll down to the active option', () => {
for (let i = 0; i < 15; i++) {
dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW);
}
// <top padding> + <option index * height> - <panel height> = 8 + 16 * 48 - 275 = 501
expect(panel.scrollTop).withContext('Expected scroll to be at the 16th option.').toBe(501);
});
it('should scroll up to the active option', () => {
// Scroll to the bottom.
for (let i = 0; i < fixture.componentInstance.foods.length; i++) {
dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW);
}
for (let i = 0; i < 20; i++) {
dispatchKeyboardEvent(host, 'keydown', UP_ARROW);
}
// <top padding> + <option index * height> = 8 + 9 * 48 = 440
expect(panel.scrollTop).withContext('Expected scroll to be at the 9th option.').toBe(440);
});
it('should skip option group labels', fakeAsync(() => {
fixture.destroy();
const groupFixture = TestBed.createComponent(SelectWithGroups);
groupFixture.detectChanges();
groupFixture.componentInstance.select.open();
groupFixture.detectChanges();
flush();
host = groupFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
panel = overlayContainerElement.querySelector('.mat-mdc-select-panel')! as HTMLElement;
for (let i = 0; i < 8; i++) {
dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW);
flush();
}
// <top padding> + <(option index + group labels) * height> - <panel height> =
// 8 + (8 + 3) * 48 - 275 = 309
expect(panel.scrollTop).withContext('Expected scroll to be at the 9th option.').toBe(309);
}));
it('should scroll to the top when pressing HOME', () => {
for (let i = 0; i < 20; i++) {
dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW);
fixture.detectChanges();
}
expect(panel.scrollTop)
.withContext('Expected panel to be scrolled down.')
.toBeGreaterThan(0);
dispatchKeyboardEvent(host, 'keydown', HOME);
fixture.detectChanges();
// 8px is the top padding of the panel.
expect(panel.scrollTop).withContext('Expected panel to be scrolled to the top').toBe(8);
});
it('should scroll to the bottom of the panel when pressing END', () => {
dispatchKeyboardEvent(host, 'keydown', END);
fixture.detectChanges();
// <top padding> + <option amount> * <option height> - <panel height> =
// 8 + 30 * 48 - 275 = 1173
expect(panel.scrollTop)
.withContext('Expected panel to be scrolled to the bottom')
.toBe(1173);
});
it('should scroll 10 to the top or to first element when pressing PAGE_UP', () => {
for (let i = 0; i < 18; i++) {
dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW);
fixture.detectChanges();
}
expect(panel.scrollTop)
.withContext('Expected panel to be scrolled down.')
.toBeGreaterThan(0);
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(18);
dispatchKeyboardEvent(host, 'keydown', PAGE_UP);
fixture.detectChanges();
// <top padding> + <option amount> * <option height>
// 8 + 8 × 48
expect(panel.scrollTop).withContext('Expected panel to be scrolled to the top').toBe(392);
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(8);
dispatchKeyboardEvent(host, 'keydown', PAGE_UP);
fixture.detectChanges();
// 8px is the top padding of the panel.
expect(panel.scrollTop).withContext('Expected panel to be scrolled to the top').toBe(8);
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(0);
});
it('should scroll 10 to the bottom of the panel when pressing PAGE_DOWN', () => {
dispatchKeyboardEvent(host, 'keydown', PAGE_DOWN);
fixture.detectChanges();
// <top padding> + <option amount> * <option height> - <panel height> =
// 8 + 11 * 48 - 275 = 261
expect(panel.scrollTop)
.withContext('Expected panel to be scrolled 10 to the bottom')
.toBe(261);
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(10);
dispatchKeyboardEvent(host, 'keydown', PAGE_DOWN);
fixture.detectChanges();
// <top padding> + <option amount> * <option height> - <panel height> =
// 8 + 21 * 48 - 275 = 741
expect(panel.scrollTop)
.withContext('Expected panel to be scrolled 10 to the bottom')
.toBe(741);
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(20);
dispatchKeyboardEvent(host, 'keydown', PAGE_DOWN);
fixture.detectChanges();
// <top padding> + <option amount> * <option height> - <panel height> =
// 8 + 30 * 48 - 275 = 1173
expect(panel.scrollTop)
.withContext('Expected panel to be scrolled 10 to the bottom')
.toBe(1173);
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(29);
});
it('should scroll to the active option when typing', fakeAsync(() => {
for (let i = 0; i < 15; i++) {
// Press the letter 'o' 15 times since all the options are named 'Option <index>'
dispatchEvent(host, createKeyboardEvent('keydown', 79, 'o'));
fixture.detectChanges();
tick(DEFAULT_TYPEAHEAD_DEBOUNCE_INTERVAL);
}
flush();
// <top padding> + <option index * height> - <panel height> = 8 + 16 * 48 - 275 = 501
expect(panel.scrollTop).withContext('Expected scroll to be at the 16th option.').toBe(501);
}));
it('should scroll to top when going to first option in top group', fakeAsync(() => {
fixture.destroy();
const groupFixture = TestBed.createComponent(SelectWithGroups);
groupFixture.detectChanges();
groupFixture.componentInstance.select.open();
groupFixture.detectChanges();
flush();
host = groupFixture.debugElement.query(By.css('mat-select'))!.nativeElement;
panel = overlayContainerElement.querySelector('.mat-mdc-select-panel')! as HTMLElement;
for (let i = 0; i < 5; i++) {
dispatchKeyboardEvent(host, 'keydown', DOWN_ARROW);
}
expect(panel.scrollTop).toBeGreaterThan(0);
for (let i = 0; i < 5; i++) {
dispatchKeyboardEvent(host, 'keydown', UP_ARROW);
flush();
}
expect(panel.scrollTop).toBe(0);
}));
});
});
describe('when initialized without options', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([SelectInitWithoutOptions])));
it('should select the proper option when option list is initialized later', fakeAsync(() => {
const fixture = TestBed.createComponent(SelectInitWithoutOptions);
const instance = fixture.componentInstance;
fixture.detectChanges();
flush();
// Wait for the initial writeValue promise.
expect(instance.select.selected).toBeFalsy();
instance.addOptions();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
// Wait for the next writeValue promise.
expect(instance.select.selected).toBe(instance.options.toArray()[1]);
}));
});
| {
"end_byte": 101887,
"start_byte": 93091,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_101891_111733 | escribe('with a selectionChange event handler', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([SelectWithChangeEvent])));
let fixture: ComponentFixture<SelectWithChangeEvent>;
let trigger: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(SelectWithChangeEvent);
fixture.detectChanges();
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
});
it('should emit an event when the selected option has changed', () => {
trigger.click();
fixture.detectChanges();
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
expect(fixture.componentInstance.changeListener).toHaveBeenCalled();
});
it('should not emit multiple change events for the same option', () => {
trigger.click();
fixture.detectChanges();
const option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
option.click();
option.click();
expect(fixture.componentInstance.changeListener).toHaveBeenCalledTimes(1);
});
it('should only emit one event when pressing arrow keys on closed select', fakeAsync(() => {
const select = fixture.debugElement.query(By.css('mat-select'))!.nativeElement;
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
expect(fixture.componentInstance.changeListener).toHaveBeenCalledTimes(1);
flush();
}));
});
describe('with ngModel', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([NgModelSelect])));
it('should disable itself when control is disabled using the property', fakeAsync(() => {
const fixture = TestBed.createComponent(NgModelSelect);
fixture.detectChanges();
fixture.componentInstance.isDisabled = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
const trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
expect(getComputedStyle(trigger).getPropertyValue('cursor'))
.withContext(`Expected cursor to be default arrow on disabled control.`)
.toEqual('default');
trigger.click();
fixture.detectChanges();
flush();
expect(overlayContainerElement.textContent)
.withContext(`Expected select panel to stay closed.`)
.toEqual('');
expect(fixture.componentInstance.select.panelOpen)
.withContext(`Expected select panelOpen property to stay false.`)
.toBe(false);
fixture.componentInstance.isDisabled = false;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
fixture.detectChanges();
expect(getComputedStyle(trigger).getPropertyValue('cursor'))
.withContext(`Expected cursor to be a pointer on enabled control.`)
.toEqual('pointer');
trigger.click();
fixture.detectChanges();
flush();
expect(overlayContainerElement.textContent)
.withContext(`Expected select panel to open normally on re-enabled control`)
.toContain('Steak');
expect(fixture.componentInstance.select.panelOpen)
.withContext(`Expected select panelOpen property to become true.`)
.toBe(true);
}));
});
describe('with ngIf', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([NgIfSelect])));
it('should handle nesting in an ngIf', fakeAsync(() => {
const fixture = TestBed.createComponent(NgIfSelect);
fixture.detectChanges();
fixture.componentInstance.isShowing = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const formField = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
const trigger = formField.querySelector('.mat-mdc-select-trigger');
formField.style.width = '300px';
trigger.click();
flush();
fixture.detectChanges();
const value = fixture.debugElement.query(By.css('.mat-mdc-select-value'))!;
expect(value.nativeElement.textContent)
.withContext(`Expected trigger to be populated by the control's initial value.`)
.toContain('Pizza');
const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
expect(pane.style.width).toEqual('300px');
expect(fixture.componentInstance.select.panelOpen).toBe(true);
expect(overlayContainerElement.textContent).toContain('Steak');
expect(overlayContainerElement.textContent).toContain('Pizza');
expect(overlayContainerElement.textContent).toContain('Tacos');
}));
});
describe('with multiple mat-select elements in one view', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([ManySelects])));
let fixture: ComponentFixture<ManySelects>;
let triggers: DebugElement[];
let options: NodeListOf<HTMLElement>;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(ManySelects);
fixture.detectChanges();
triggers = fixture.debugElement.queryAll(By.css('.mat-mdc-select-trigger'));
triggers[0].nativeElement.click();
fixture.detectChanges();
flush();
options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>;
}));
it('should set the option id', fakeAsync(() => {
let firstOptionID = options[0].id;
expect(options[0].id)
.withContext(`Expected option ID to have the correct prefix.`)
.toContain('mat-option');
expect(options[0].id).not.toEqual(options[1].id, `Expected option IDs to be unique.`);
const backdrop = overlayContainerElement.querySelector(
'.cdk-overlay-backdrop',
) as HTMLElement;
backdrop.click();
fixture.detectChanges();
flush();
triggers[1].nativeElement.click();
fixture.detectChanges();
flush();
options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>;
expect(options[0].id)
.withContext(`Expected option ID to have the correct prefix.`)
.toContain('mat-option');
expect(options[0].id).not.toEqual(firstOptionID, `Expected option IDs to be unique.`);
expect(options[0].id).not.toEqual(options[1].id, `Expected option IDs to be unique.`);
}));
});
describe('with floatLabel', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([FloatLabelSelect])));
it('should be able to always float the label', () => {
const fixture = TestBed.createComponent(FloatLabelSelect);
fixture.detectChanges();
const label = fixture.nativeElement.querySelector('.mat-mdc-form-field label');
expect(fixture.componentInstance.control.value).toBeFalsy();
fixture.componentInstance.floatLabel = 'always';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(label.classList.contains('mdc-floating-label--float-above'))
.withContext('Label should be floating')
.toBe(true);
});
it('should default to global floating label type', () => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [
MatFormFieldModule,
MatSelectModule,
ReactiveFormsModule,
FormsModule,
NoopAnimationsModule,
],
providers: [{provide: MAT_FORM_FIELD_DEFAULT_OPTIONS, useValue: {floatLabel: 'always'}}],
declarations: [FloatLabelSelect],
});
const fixture = TestBed.createComponent(FloatLabelSelect);
fixture.componentInstance.floatLabel = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const label = fixture.nativeElement.querySelector('.mat-mdc-form-field label');
expect(label.classList.contains('mdc-floating-label--float-above'))
.withContext('Label should be floating')
.toBe(true);
});
it('should float the label on focus if it has a placeholder', () => {
const fixture = TestBed.createComponent(FloatLabelSelect);
fixture.detectChanges();
expect(fixture.componentInstance.placeholder).toBeTruthy();
fixture.componentInstance.floatLabel = 'auto';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
dispatchFakeEvent(fixture.nativeElement.querySelector('.mat-mdc-select'), 'focus');
fixture.detectChanges();
const label = fixture.nativeElement.querySelector('.mat-mdc-form-field label');
expect(label.classList.contains('mdc-floating-label--float-above'))
.withContext('Label should be floating')
.toBe(true);
});
});
describe('with a sibling component that throws an error', () => {
beforeEach(waitForAsync(() =>
configureMatSelectTestingModule([SelectWithErrorSibling, ThrowsErrorOnInit])));
it('should not crash the browser when a sibling throws an error on init', () => {
// Note that this test can be considered successful if the error being thrown didn't
// end up crashing the testing setup altogether.
expect(() => {
TestBed.createComponent(SelectWithErrorSibling).detectChanges();
}).toThrowError(new RegExp('Oh no!', 'g'));
});
});
describe('with tabindex', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([SelectWithPlainTabindex])));
it('should be able to set the tabindex via the native attribute', () => {
const fixture = TestBed.createComponent(SelectWithPlainTabindex);
fixture.detectChanges();
const select = fixture.debugElement.query(By.css('mat-select'))!.nativeElement;
expect(select.getAttribute('tabindex')).toBe('5');
});
});
| {
"end_byte": 111733,
"start_byte": 101891,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_111737_119630 | escribe('change events', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([SelectWithPlainTabindex])));
it('should complete the stateChanges stream on destroy', () => {
const fixture = TestBed.createComponent(SelectWithPlainTabindex);
fixture.detectChanges();
const debugElement = fixture.debugElement.query(By.directive(MatSelect))!;
const select = debugElement.componentInstance;
const spy = jasmine.createSpy('stateChanges complete');
const subscription = select.stateChanges.subscribe(undefined, undefined, spy);
fixture.destroy();
expect(spy).toHaveBeenCalled();
subscription.unsubscribe();
});
});
describe('when initially hidden', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([BasicSelectInitiallyHidden])));
it('should set the width of the overlay if the element was hidden initially', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectInitiallyHidden);
fixture.detectChanges();
const formField = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
const trigger = formField.querySelector('.mat-mdc-select-trigger');
formField.style.width = '300px';
fixture.componentInstance.isVisible = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
expect(pane.style.width).toBe('300px');
}));
});
describe('with no placeholder', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([BasicSelectNoPlaceholder])));
it('should set the width of the overlay if there is no placeholder', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectNoPlaceholder);
fixture.detectChanges();
const trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
trigger.click();
fixture.detectChanges();
flush();
const pane = overlayContainerElement.querySelector('.cdk-overlay-pane') as HTMLElement;
expect(parseInt(pane.style.width as string)).toBeGreaterThan(0);
}));
});
describe('with theming', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([BasicSelectWithTheming])));
let fixture: ComponentFixture<BasicSelectWithTheming>;
beforeEach(() => {
fixture = TestBed.createComponent(BasicSelectWithTheming);
fixture.detectChanges();
});
it('should transfer the theme to the select panel', () => {
fixture.componentInstance.theme = 'warn';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.componentInstance.select.open();
fixture.detectChanges();
const panel = overlayContainerElement.querySelector('.mat-mdc-select-panel')! as HTMLElement;
expect(panel.classList).toContain('mat-warn');
});
});
describe('when invalid inside a form', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([InvalidSelectInForm])));
it('should not throw SelectionModel errors in addition to ngModel errors', () => {
const fixture = TestBed.createComponent(InvalidSelectInForm);
// The first change detection run will throw the "ngModel is missing a name" error.
expect(() => fixture.detectChanges()).toThrowError(/the name attribute must be set/g);
fixture.changeDetectorRef.markForCheck();
// The second run shouldn't throw selection-model related errors.
expect(() => fixture.detectChanges()).not.toThrow();
});
});
describe('with ngModel using compareWith', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([NgModelCompareWithSelect])));
let fixture: ComponentFixture<NgModelCompareWithSelect>;
let instance: NgModelCompareWithSelect;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(NgModelCompareWithSelect);
instance = fixture.componentInstance;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
}));
describe('comparing by value', () => {
it('should have a selection', fakeAsync(() => {
const selectedOption = instance.select.selected as MatOption;
expect(selectedOption.value.value).toEqual('pizza-1');
}));
it('should update when making a new selection', fakeAsync(() => {
instance.options.last._selectViaInteraction();
fixture.detectChanges();
flush();
const selectedOption = instance.select.selected as MatOption;
expect(instance.selectedFood.value).toEqual('tacos-2');
expect(selectedOption.value.value).toEqual('tacos-2');
}));
});
describe('comparing by reference', () => {
beforeEach(fakeAsync(() => {
spyOn(instance, 'compareByReference').and.callThrough();
instance.useCompareByReference();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
}));
it('should use the comparator', () => {
expect(instance.compareByReference).toHaveBeenCalled();
});
it('should initialize with no selection despite having a value', () => {
expect(instance.selectedFood.value).toBe('pizza-1');
expect(instance.select.selected).toBeUndefined();
});
it('should not update the selection if value is copied on change', fakeAsync(() => {
instance.options.first._selectViaInteraction();
fixture.detectChanges();
flush();
expect(instance.selectedFood.value).toEqual('steak-0');
expect(instance.select.selected).toBeUndefined();
}));
it('should throw an error when using a non-function comparator', () => {
instance.useNullComparator();
expect(() => {
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
}).toThrowError(wrappedErrorMessage(getMatSelectNonFunctionValueError()));
});
});
});
describe(`when the select's value is accessed on initialization`, () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([SelectEarlyAccessSibling])));
it('should not throw when trying to access the selected value on init in the view', () => {
expect(() => {
TestBed.createComponent(SelectEarlyAccessSibling).detectChanges();
}).not.toThrow();
});
it('should not throw when reading selected value programmatically in single selection mode', () => {
expect(() => {
const fixture = TestBed.createComponent(SelectEarlyAccessSibling);
const select = fixture.debugElement.query(By.directive(MatSelect)).componentInstance;
// We're checking that accessing the getter won't throw.
select.multiple = false;
return select.selected;
}).not.toThrow();
});
it('should not throw when reading selected value programmatically in multi selection mode', () => {
expect(() => {
const fixture = TestBed.createComponent(SelectEarlyAccessSibling);
const select = fixture.debugElement.query(By.directive(MatSelect)).componentInstance;
// We're checking that accessing the getter won't throw.
select.multiple = true;
return select.selected;
}).not.toThrow();
});
});
describe('with ngIf and mat-label', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([SelectWithNgIfAndLabel])));
it('should not throw when using ngIf on a select with an associated label', () => {
expect(() => {
const fixture = TestBed.createComponent(SelectWithNgIfAndLabel);
fixture.detectChanges();
}).not.toThrow();
});
});
| {
"end_byte": 119630,
"start_byte": 111737,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_119634_129909 | escribe('inside of a form group', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([SelectInsideFormGroup])));
let fixture: ComponentFixture<SelectInsideFormGroup>;
let testComponent: SelectInsideFormGroup;
let select: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(SelectInsideFormGroup);
fixture.detectChanges();
testComponent = fixture.componentInstance;
select = fixture.debugElement.query(By.css('mat-select'))!.nativeElement;
});
it('should not set the invalid class on a clean select', fakeAsync(() => {
expect(testComponent.formGroup.untouched)
.withContext('Expected the form to be untouched.')
.toBe(true);
expect(testComponent.formControl.invalid)
.withContext('Expected form control to be invalid.')
.toBe(true);
expect(select.classList).not.toContain(
'mat-mdc-select-invalid',
'Expected select not to appear invalid.',
);
expect(select.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to false.')
.toBe('false');
}));
it('should appear as invalid if it becomes touched', fakeAsync(() => {
expect(select.classList).not.toContain(
'mat-mdc-select-invalid',
'Expected select not to appear invalid.',
);
expect(select.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to false.')
.toBe('false');
testComponent.formControl.markAsTouched();
fixture.detectChanges();
expect(select.classList)
.withContext('Expected select to appear invalid.')
.toContain('mat-mdc-select-invalid');
expect(select.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to true.')
.toBe('true');
}));
it('should not have the invalid class when the select becomes valid', fakeAsync(() => {
testComponent.formControl.markAsTouched();
fixture.detectChanges();
expect(select.classList)
.withContext('Expected select to appear invalid.')
.toContain('mat-mdc-select-invalid');
expect(select.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to true.')
.toBe('true');
testComponent.formControl.setValue('pizza-1');
fixture.detectChanges();
expect(select.classList).not.toContain(
'mat-mdc-select-invalid',
'Expected select not to appear invalid.',
);
expect(select.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to false.')
.toBe('false');
}));
it('should appear as invalid when the parent form group is submitted', fakeAsync(() => {
expect(select.classList).not.toContain(
'mat-mdc-select-invalid',
'Expected select not to appear invalid.',
);
expect(select.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to false.')
.toBe('false');
dispatchFakeEvent(fixture.debugElement.query(By.css('form'))!.nativeElement, 'submit');
fixture.detectChanges();
expect(select.classList)
.withContext('Expected select to appear invalid.')
.toContain('mat-mdc-select-invalid');
expect(select.getAttribute('aria-invalid'))
.withContext('Expected aria-invalid to be set to true.')
.toBe('true');
}));
it('should render the error messages when the parent form is submitted', fakeAsync(() => {
const debugEl = fixture.debugElement.nativeElement;
expect(debugEl.querySelectorAll('mat-error').length)
.withContext('Expected no error messages')
.toBe(0);
dispatchFakeEvent(fixture.debugElement.query(By.css('form'))!.nativeElement, 'submit');
fixture.detectChanges();
expect(debugEl.querySelectorAll('mat-error').length)
.withContext('Expected one error message')
.toBe(1);
}));
it('should override error matching behavior via injection token', () => {
const errorStateMatcher: ErrorStateMatcher = {
isErrorState: jasmine.createSpy('error state matcher').and.returnValue(true),
};
fixture.destroy();
TestBed.resetTestingModule().configureTestingModule({
imports: [MatSelectModule, ReactiveFormsModule, FormsModule, NoopAnimationsModule],
declarations: [SelectInsideFormGroup],
providers: [{provide: ErrorStateMatcher, useValue: errorStateMatcher}],
});
const errorFixture = TestBed.createComponent(SelectInsideFormGroup);
const component = errorFixture.componentInstance;
errorFixture.detectChanges();
expect(component.select.errorState).toBe(true);
expect(errorStateMatcher.isErrorState).toHaveBeenCalled();
});
it('should notify that the state changed when the options have changed', fakeAsync(() => {
testComponent.formControl.setValue('pizza-1');
fixture.detectChanges();
const spy = jasmine.createSpy('stateChanges spy');
const subscription = testComponent.select.stateChanges.subscribe(spy);
testComponent.options = [];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
tick();
expect(spy).toHaveBeenCalled();
subscription.unsubscribe();
}));
it('should set an asterisk after the label if the FormControl is required', fakeAsync(() => {
const label = fixture.nativeElement.querySelector('.mat-mdc-form-field label');
expect(label.querySelector('.mat-mdc-form-field-required-marker')).toBeTruthy();
}));
});
describe('with custom error behavior', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([CustomErrorBehaviorSelect])));
it('should be able to override the error matching behavior via an @Input', () => {
const fixture = TestBed.createComponent(CustomErrorBehaviorSelect);
const component = fixture.componentInstance;
const matcher = jasmine.createSpy('error state matcher').and.returnValue(true);
fixture.detectChanges();
expect(component.control.invalid).toBe(false);
expect(component.select.errorState).toBe(false);
fixture.componentInstance.errorStateMatcher = {isErrorState: matcher};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(component.select.errorState).toBe(true);
expect(matcher).toHaveBeenCalled();
});
});
describe('with preselected array values', () => {
beforeEach(waitForAsync(() =>
configureMatSelectTestingModule([SingleSelectWithPreselectedArrayValues])));
it('should be able to preselect an array value in single-selection mode', fakeAsync(() => {
const fixture = TestBed.createComponent(SingleSelectWithPreselectedArrayValues);
fixture.detectChanges();
flush();
fixture.detectChanges();
const trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
expect(trigger.textContent).toContain('Pizza');
expect(fixture.componentInstance.options.toArray()[1].selected).toBe(true);
}));
});
describe('with custom value accessor', () => {
beforeEach(waitForAsync(() =>
configureMatSelectTestingModule([CompWithCustomSelect, CustomSelectAccessor])));
it('should support use inside a custom value accessor', () => {
const fixture = TestBed.createComponent(CompWithCustomSelect);
spyOn(fixture.componentInstance.customAccessor, 'writeValue');
fixture.detectChanges();
expect(fixture.componentInstance.customAccessor.select.ngControl)
.withContext('Expected mat-select NOT to inherit control from parent value accessor.')
.toBeFalsy();
expect(fixture.componentInstance.customAccessor.writeValue).toHaveBeenCalled();
});
});
describe('with a falsy value', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([FalsyValueSelect])));
it('should be able to programmatically select a falsy option', fakeAsync(() => {
const fixture = TestBed.createComponent(FalsyValueSelect);
fixture.detectChanges();
fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement.click();
fixture.componentInstance.control.setValue(0);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.options.first.selected)
.withContext('Expected first option to be selected')
.toBe(true);
expect(overlayContainerElement.querySelectorAll('mat-option')[0].classList)
.withContext('Expected first option to be selected')
.toContain('mdc-list-item--selected');
}));
});
describe('with OnPush', () => {
beforeEach(waitForAsync(() =>
configureMatSelectTestingModule([BasicSelectOnPush, BasicSelectOnPushPreselected])));
it('should set the trigger text based on the value when initialized', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectOnPushPreselected);
fixture.detectChanges();
flush();
const trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
fixture.detectChanges();
expect(trigger.textContent).toContain('Pizza');
}));
it('should update the trigger based on the value', () => {
const fixture = TestBed.createComponent(BasicSelectOnPush);
fixture.detectChanges();
const trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
expect(trigger.textContent).toContain('Pizza');
fixture.componentInstance.control.reset();
fixture.detectChanges();
expect(trigger.textContent).not.toContain('Pizza');
});
it('should sync up the form control value with the component value', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectOnPushPreselected);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.value).toBe('pizza-1');
expect(fixture.componentInstance.select.value).toBe('pizza-1');
}));
});
| {
"end_byte": 129909,
"start_byte": 119634,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_129913_136246 | escribe('with custom trigger', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([SelectWithCustomTrigger])));
it('should allow the user to customize the label', () => {
const fixture = TestBed.createComponent(SelectWithCustomTrigger);
fixture.detectChanges();
fixture.componentInstance.control.setValue('pizza-1');
fixture.detectChanges();
const label = fixture.debugElement.query(By.css('.mat-mdc-select-value'))!.nativeElement;
expect(label.textContent)
.withContext('Expected the displayed text to be "Pizza" in reverse.')
.toContain('azziP');
});
});
describe('when reseting the value by setting null or undefined', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([ResetValuesSelect])));
let fixture: ComponentFixture<ResetValuesSelect>;
let trigger: HTMLElement;
let formField: HTMLElement;
let options: NodeListOf<HTMLElement>;
let label: HTMLLabelElement;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(ResetValuesSelect);
fixture.detectChanges();
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
formField = fixture.debugElement.query(By.css('.mat-mdc-form-field'))!.nativeElement;
label = formField.querySelector('label')!;
trigger.click();
fixture.detectChanges();
flush();
options = overlayContainerElement.querySelectorAll('mat-option') as NodeListOf<HTMLElement>;
options[0].click();
fixture.detectChanges();
flush();
}));
it('should reset when an option with an undefined value is selected', fakeAsync(() => {
options[4].click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.value).toBeUndefined();
expect(fixture.componentInstance.select.selected).toBeFalsy();
expect(label.classList).not.toContain('mdc-floating-label--float-above');
expect(trigger.textContent).not.toContain('Undefined');
}));
it('should reset when an option with a null value is selected', fakeAsync(() => {
options[5].click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.value).toBeNull();
expect(fixture.componentInstance.select.selected).toBeFalsy();
expect(label.classList).not.toContain('mdc-floating-label--float-above');
expect(trigger.textContent).not.toContain('Null');
}));
it('should reset when a blank option is selected', fakeAsync(() => {
options[6].click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.value).toBeUndefined();
expect(fixture.componentInstance.select.selected).toBeFalsy();
expect(label.classList).not.toContain('mdc-floating-label--float-above');
expect(trigger.textContent).not.toContain('None');
}));
it('should not mark the reset option as selected ', fakeAsync(() => {
options[5].click();
fixture.detectChanges();
flush();
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
expect(options[5].classList).not.toContain('mdc-list-item--selected');
}));
it('should not reset when any other falsy option is selected', fakeAsync(() => {
options[3].click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.value).toBe(false);
expect(fixture.componentInstance.select.selected).toBeTruthy();
expect(label.classList).toContain('mdc-floating-label--float-above');
expect(trigger.textContent).toContain('Falsy');
}));
it('should not consider the reset values as selected when resetting the form control', () => {
expect(label.classList).toContain('mdc-floating-label--float-above');
fixture.componentInstance.control.reset();
fixture.detectChanges();
expect(fixture.componentInstance.control.value).toBeNull();
expect(fixture.componentInstance.select.selected).toBeFalsy();
expect(label.classList).not.toContain('mdc-floating-label--float-above');
expect(trigger.textContent).not.toContain('Null');
expect(trigger.textContent).not.toContain('Undefined');
});
});
describe('with reset option and a form control', () => {
let fixture: ComponentFixture<SelectWithResetOptionAndFormControl>;
let options: HTMLElement[];
let trigger: HTMLElement;
beforeEach(() => {
configureMatSelectTestingModule([SelectWithResetOptionAndFormControl]);
fixture = TestBed.createComponent(SelectWithResetOptionAndFormControl);
fixture.detectChanges();
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
trigger.click();
fixture.detectChanges();
options = Array.from(overlayContainerElement.querySelectorAll('mat-option'));
});
it('should set the select value', fakeAsync(() => {
fixture.componentInstance.control.setValue('a');
fixture.detectChanges();
expect(fixture.componentInstance.select.value).toBe('a');
}));
it('should reset the control value', fakeAsync(() => {
fixture.componentInstance.control.setValue('a');
fixture.detectChanges();
options[0].click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.control.value).toBeUndefined();
}));
it('should reflect the value in the form control', fakeAsync(() => {
options[1].click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select.value).toBe('a');
expect(fixture.componentInstance.control.value).toBe('a');
}));
it('should deselect the reset option when a value is assigned through the form control', fakeAsync(() => {
expect(options[0].classList).toContain('mat-mdc-option-active');
options[0].click();
fixture.detectChanges();
flush();
fixture.componentInstance.control.setValue('c');
fixture.detectChanges();
trigger.click();
flush();
fixture.detectChanges();
expect(options[0].classList).not.toContain('mat-mdc-option-active');
expect(options[3].classList).toContain('mat-mdc-option-active');
}));
});
| {
"end_byte": 136246,
"start_byte": 129913,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_136250_146893 | escribe('without Angular forms', () => {
beforeEach(waitForAsync(() =>
configureMatSelectTestingModule([
BasicSelectWithoutForms,
BasicSelectWithoutFormsPreselected,
BasicSelectWithoutFormsMultiple,
])));
it('should set the value when options are clicked', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
fixture.detectChanges();
expect(fixture.componentInstance.selectedFood).toBeFalsy();
const trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
trigger.click();
fixture.detectChanges();
flush();
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.selectedFood).toBe('steak-0');
expect(fixture.componentInstance.select.value).toBe('steak-0');
expect(trigger.textContent).toContain('Steak');
trigger.click();
fixture.detectChanges();
flush();
(overlayContainerElement.querySelectorAll('mat-option')[2] as HTMLElement).click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.selectedFood).toBe('sandwich-2');
expect(fixture.componentInstance.select.value).toBe('sandwich-2');
expect(trigger.textContent).toContain('Sandwich');
}));
it('should mark options as selected when the value is set', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
fixture.detectChanges();
fixture.componentInstance.selectedFood = 'sandwich-2';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
expect(trigger.textContent).toContain('Sandwich');
trigger.click();
fixture.detectChanges();
flush();
const option = overlayContainerElement.querySelectorAll('mat-option')[2];
expect(option.classList).toContain('mdc-list-item--selected');
expect(fixture.componentInstance.select.value).toBe('sandwich-2');
}));
it('should reset the label when a null value is set', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
fixture.detectChanges();
expect(fixture.componentInstance.selectedFood).toBeFalsy();
const trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
trigger.click();
fixture.detectChanges();
flush();
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.selectedFood).toBe('steak-0');
expect(fixture.componentInstance.select.value).toBe('steak-0');
expect(trigger.textContent).toContain('Steak');
fixture.componentInstance.selectedFood = null;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(fixture.componentInstance.select.value).toBeNull();
expect(trigger.textContent).not.toContain('Steak');
}));
it('should reflect the preselected value', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutFormsPreselected);
fixture.detectChanges();
flush();
const trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
fixture.detectChanges();
expect(trigger.textContent).toContain('Pizza');
trigger.click();
fixture.detectChanges();
flush();
const option = overlayContainerElement.querySelectorAll('mat-option')[1];
expect(option.classList).toContain('mdc-list-item--selected');
expect(fixture.componentInstance.select.value).toBe('pizza-1');
}));
it('should be able to select multiple values', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutFormsMultiple);
fixture.detectChanges();
expect(fixture.componentInstance.selectedFoods).toBeFalsy();
const trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
trigger.click();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[0].click();
fixture.detectChanges();
expect(fixture.componentInstance.selectedFoods).toEqual(['steak-0']);
expect(fixture.componentInstance.select.value).toEqual(['steak-0']);
expect(trigger.textContent).toContain('Steak');
options[2].click();
fixture.detectChanges();
expect(fixture.componentInstance.selectedFoods).toEqual(['steak-0', 'sandwich-2']);
expect(fixture.componentInstance.select.value).toEqual(['steak-0', 'sandwich-2']);
expect(trigger.textContent).toContain('Steak, Sandwich');
options[1].click();
fixture.detectChanges();
expect(fixture.componentInstance.selectedFoods).toEqual(['steak-0', 'pizza-1', 'sandwich-2']);
expect(fixture.componentInstance.select.value).toEqual(['steak-0', 'pizza-1', 'sandwich-2']);
expect(trigger.textContent).toContain('Steak, Pizza, Sandwich');
}));
it('should restore focus to the host element', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
fixture.detectChanges();
fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement.click();
fixture.detectChanges();
flush();
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
fixture.detectChanges();
flush();
const select = fixture.debugElement.nativeElement.querySelector('mat-select');
expect(document.activeElement).withContext('Expected trigger to be focused.').toBe(select);
}));
it('should not restore focus to the host element when clicking outside', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
const select = fixture.debugElement.nativeElement.querySelector('mat-select');
fixture.detectChanges();
select.focus(); // Focus manually since the programmatic click might not do it.
fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement.click();
fixture.detectChanges();
flush();
expect(document.activeElement).withContext('Expected trigger to be focused.').toBe(select);
select.blur(); // Blur manually since the programmatic click might not do it.
(overlayContainerElement.querySelector('.cdk-overlay-backdrop') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(document.activeElement).not.toBe(select, 'Expected trigger not to be focused.');
}));
it('should update the data binding before emitting the change event', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
const instance = fixture.componentInstance;
const spy = jasmine.createSpy('change spy');
fixture.detectChanges();
instance.select.selectionChange.subscribe(() => spy(instance.selectedFood));
expect(instance.selectedFood).toBeFalsy();
fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement.click();
fixture.detectChanges();
flush();
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(instance.selectedFood).toBe('steak-0');
expect(spy).toHaveBeenCalledWith('steak-0');
}));
it('should select the active option when tabbing away while open', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
fixture.detectChanges();
const select = fixture.nativeElement.querySelector('.mat-mdc-select');
expect(fixture.componentInstance.selectedFood).toBeFalsy();
const trigger = fixture.nativeElement.querySelector('.mat-mdc-select-trigger');
trigger.click();
fixture.detectChanges();
flush();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
fixture.detectChanges();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
fixture.detectChanges();
dispatchKeyboardEvent(select, 'keydown', TAB);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.selectedFood).toBe('sandwich-2');
expect(fixture.componentInstance.select.value).toBe('sandwich-2');
expect(trigger.textContent).toContain('Sandwich');
}));
it('should not select the active option when tabbing away while close', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
fixture.detectChanges();
const select = fixture.nativeElement.querySelector('.mat-mdc-select');
expect(fixture.componentInstance.selectedFood).toBeFalsy();
const trigger = fixture.nativeElement.querySelector('.mat-mdc-select-trigger');
trigger.click();
fixture.detectChanges();
flush();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
fixture.detectChanges();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
fixture.detectChanges();
dispatchKeyboardEvent(select, 'keydown', ESCAPE);
fixture.detectChanges();
dispatchKeyboardEvent(select, 'keydown', TAB);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.selectedFood).toBeFalsy();
}));
it('should not change the multiple value selection when tabbing away', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutFormsMultiple);
fixture.detectChanges();
expect(fixture.componentInstance.selectedFoods)
.withContext('Expected no value on init.')
.toBeFalsy();
const select = fixture.nativeElement.querySelector('.mat-mdc-select');
const trigger = fixture.nativeElement.querySelector('.mat-mdc-select-trigger');
trigger.click();
fixture.detectChanges();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
fixture.detectChanges();
dispatchKeyboardEvent(select, 'keydown', DOWN_ARROW);
fixture.detectChanges();
dispatchKeyboardEvent(select, 'keydown', TAB);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.selectedFoods)
.withContext('Expected no value after tabbing away.')
.toBeFalsy();
}));
| {
"end_byte": 146893,
"start_byte": 136250,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_146899_152601 | t('should emit once when a reset value is selected', fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
const instance = fixture.componentInstance;
const spy = jasmine.createSpy('change spy');
instance.selectedFood = 'sandwich-2';
instance.foods[0].value = null;
fixture.detectChanges();
const subscription = instance.select.selectionChange.subscribe(spy);
fixture.debugElement.query(By.css('.mat-mdc-select-trigger')).nativeElement.click();
fixture.detectChanges();
flush();
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(spy).toHaveBeenCalledTimes(1);
subscription.unsubscribe();
}));
it(
'should not emit the change event multiple times when a reset option is ' +
'selected twice in a row',
fakeAsync(() => {
const fixture = TestBed.createComponent(BasicSelectWithoutForms);
const instance = fixture.componentInstance;
const spy = jasmine.createSpy('change spy');
instance.foods[0].value = null;
fixture.detectChanges();
const subscription = instance.select.selectionChange.subscribe(spy);
fixture.debugElement.query(By.css('.mat-mdc-select-trigger')).nativeElement.click();
fixture.detectChanges();
flush();
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(spy).not.toHaveBeenCalled();
fixture.debugElement.query(By.css('.mat-mdc-select-trigger')).nativeElement.click();
fixture.detectChanges();
flush();
(overlayContainerElement.querySelector('mat-option') as HTMLElement).click();
fixture.detectChanges();
flush();
expect(spy).not.toHaveBeenCalled();
subscription.unsubscribe();
}),
);
});
describe('with option centering disabled', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([SelectWithoutOptionCentering])));
let fixture: ComponentFixture<SelectWithoutOptionCentering>;
let trigger: HTMLElement;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(SelectWithoutOptionCentering);
fixture.detectChanges();
flush();
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
}));
it('should not align the active option with the trigger if centering is disabled', fakeAsync(() => {
trigger.click();
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
const scrollContainer = document.querySelector('.cdk-overlay-pane .mat-mdc-select-panel')!;
// The panel should be scrolled to 0 because centering the option disabled.
// The panel should be scrolled to 0 because centering the option disabled.
expect(scrollContainer.scrollTop)
.withContext(`Expected panel not to be scrolled.`)
.toEqual(0);
// The trigger should contain 'Pizza' because it was preselected
expect(trigger.textContent).toContain('Pizza');
// The selected index should be 1 because it was preselected
expect(fixture.componentInstance.options.toArray()[1].selected).toBe(true);
}));
});
describe('positioning', () => {
beforeEach(waitForAsync(() => configureMatSelectTestingModule([BasicSelect])));
let fixture: ComponentFixture<BasicSelect>;
let trigger: HTMLElement;
let formField: HTMLElement;
let formFieldWrapper: HTMLElement;
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(BasicSelect);
fixture.detectChanges();
flush();
formField = fixture.nativeElement.querySelector('.mat-mdc-form-field');
formFieldWrapper = formField.querySelector('.mat-mdc-text-field-wrapper') as HTMLElement;
trigger = formFieldWrapper.querySelector('.mat-mdc-select-trigger') as HTMLElement;
}));
it('should position the panel under the form field by default', fakeAsync(() => {
formField.style.position = 'fixed';
formField.style.left = formField.style.top = '10%';
trigger.click();
fixture.detectChanges();
flush();
const panel = overlayContainerElement.querySelector('.cdk-overlay-pane')!;
const paneRect = panel.getBoundingClientRect();
const formFieldWrapperRect = formFieldWrapper.getBoundingClientRect();
expect(panel.classList).not.toContain('mat-mdc-select-panel-above');
expect(Math.floor(paneRect.width)).toBe(Math.floor(formFieldWrapperRect.width));
expect(Math.floor(paneRect.left)).toBe(Math.floor(formFieldWrapperRect.left));
expect(Math.floor(paneRect.top)).toBe(Math.floor(formFieldWrapperRect.bottom));
}));
it('should position the panel under the form field by default', fakeAsync(() => {
formField.style.position = 'fixed';
formField.style.left = '10%';
formField.style.bottom = '0';
trigger.click();
fixture.detectChanges();
flush();
const panel = overlayContainerElement.querySelector('.cdk-overlay-pane')!;
const paneRect = panel.getBoundingClientRect();
const formFieldWrapperRect = formFieldWrapper.getBoundingClientRect();
expect(panel.classList).toContain('mat-mdc-select-panel-above');
expect(Math.floor(paneRect.width)).toBe(Math.floor(formFieldWrapperRect.width));
expect(Math.floor(paneRect.left)).toBe(Math.floor(formFieldWrapperRect.left));
expect(Math.floor(paneRect.bottom)).toBe(Math.floor(formFieldWrapperRect.top));
}));
});
| {
"end_byte": 152601,
"start_byte": 146899,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_152605_161412 | escribe('with multiple selection', () => {
beforeEach(waitForAsync(() =>
configureMatSelectTestingModule([MultiSelect, MultiSelectWithLotsOfOptions])));
let fixture: ComponentFixture<MultiSelect>;
let testInstance: MultiSelect;
let trigger: HTMLElement;
beforeEach(() => {
fixture = TestBed.createComponent(MultiSelect);
testInstance = fixture.componentInstance;
fixture.detectChanges();
trigger = fixture.debugElement.query(By.css('.mat-mdc-select-trigger'))!.nativeElement;
});
it('should be able to select multiple values', () => {
trigger.click();
fixture.detectChanges();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[0].click();
options[2].click();
options[5].click();
fixture.detectChanges();
expect(testInstance.control.value).toEqual(['steak-0', 'tacos-2', 'eggs-5']);
});
it('should be able to toggle an option on and off', () => {
trigger.click();
fixture.detectChanges();
const option = overlayContainerElement.querySelector('mat-option') as HTMLElement;
option.click();
fixture.detectChanges();
expect(testInstance.control.value).toEqual(['steak-0']);
option.click();
fixture.detectChanges();
expect(testInstance.control.value).toEqual([]);
});
it('should update the label', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[0].click();
options[2].click();
options[5].click();
fixture.detectChanges();
expect(trigger.textContent).toContain('Steak, Tacos, Eggs');
options[2].click();
fixture.detectChanges();
expect(trigger.textContent).toContain('Steak, Eggs');
}));
it('should be able to set the selected value by taking an array', () => {
trigger.click();
testInstance.control.setValue(['steak-0', 'eggs-5']);
fixture.detectChanges();
const optionNodes = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
const optionInstances = testInstance.options.toArray();
expect(optionNodes[0].classList).toContain('mdc-list-item--selected');
expect(optionNodes[5].classList).toContain('mdc-list-item--selected');
expect(optionInstances[0].selected).toBe(true);
expect(optionInstances[5].selected).toBe(true);
});
it('should override the previously-selected value when setting an array', () => {
trigger.click();
fixture.detectChanges();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[0].click();
fixture.detectChanges();
expect(options[0].classList).toContain('mdc-list-item--selected');
testInstance.control.setValue(['eggs-5']);
fixture.detectChanges();
expect(options[0].classList).not.toContain('mdc-list-item--selected');
expect(options[5].classList).toContain('mdc-list-item--selected');
});
it('should not close the panel when clicking on options', () => {
trigger.click();
fixture.detectChanges();
expect(testInstance.select.panelOpen).toBe(true);
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[0].click();
options[1].click();
fixture.detectChanges();
expect(testInstance.select.panelOpen).toBe(true);
});
it('should sort the selected options based on their order in the panel', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[2].click();
options[0].click();
options[1].click();
fixture.detectChanges();
expect(trigger.textContent).toContain('Steak, Pizza, Tacos');
expect(fixture.componentInstance.control.value).toEqual(['steak-0', 'pizza-1', 'tacos-2']);
}));
it('should sort the selected options in reverse in rtl', fakeAsync(() => {
dir.value = 'rtl';
trigger.click();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[2].click();
options[0].click();
options[1].click();
fixture.detectChanges();
expect(trigger.textContent).toContain('Tacos, Pizza, Steak');
expect(fixture.componentInstance.control.value).toEqual(['steak-0', 'pizza-1', 'tacos-2']);
}));
it('should be able to customize the value sorting logic', fakeAsync(() => {
fixture.componentInstance.sortComparator = (a, b, optionsArray) => {
return optionsArray.indexOf(b) - optionsArray.indexOf(a);
};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
flush();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
for (let i = 0; i < 3; i++) {
options[i].click();
}
fixture.detectChanges();
// Expect the items to be in reverse order.
expect(trigger.textContent).toContain('Tacos, Pizza, Steak');
expect(fixture.componentInstance.control.value).toEqual(['tacos-2', 'pizza-1', 'steak-0']);
}));
it('should sort the values that get set via the model based on the panel order', () => {
trigger.click();
fixture.detectChanges();
testInstance.control.setValue(['tacos-2', 'steak-0', 'pizza-1']);
fixture.detectChanges();
expect(trigger.textContent).toContain('Steak, Pizza, Tacos');
});
it('should reverse sort the values, that get set via the model in rtl', () => {
dir.value = 'rtl';
trigger.click();
fixture.detectChanges();
testInstance.control.setValue(['tacos-2', 'steak-0', 'pizza-1']);
fixture.detectChanges();
expect(trigger.textContent).toContain('Tacos, Pizza, Steak');
});
it('should throw an exception when trying to set a non-array value', () => {
expect(() => {
testInstance.control.setValue('not-an-array' as any);
}).toThrowError(wrappedErrorMessage(getMatSelectNonArrayValueError()));
});
it('should throw an exception when trying to change multiple mode after init', () => {
expect(() => {
testInstance.select.multiple = false;
}).toThrowError(wrappedErrorMessage(getMatSelectDynamicMultipleError()));
});
it('should pass the `multiple` value to all of the option instances', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
expect(testInstance.options.toArray().every(option => !!option.multiple))
.withContext('Expected `multiple` to have been added to initial set of options.')
.toBe(true);
testInstance.foods.push({value: 'cake-8', viewValue: 'Cake'});
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(testInstance.options.toArray().every(option => !!option.multiple))
.withContext('Expected `multiple` to have been set on dynamically-added option.')
.toBe(true);
}));
it('should update the active item index on click', fakeAsync(() => {
trigger.click();
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(0);
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[2].click();
fixture.detectChanges();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(2);
}));
it('should be to select an option with a `null` value', () => {
fixture.componentInstance.foods = [
{value: null, viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: null, viewValue: 'Tacos'},
];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
const options = overlayContainerElement.querySelectorAll(
'mat-option',
) as NodeListOf<HTMLElement>;
options[0].click();
options[1].click();
options[2].click();
fixture.detectChanges();
expect(testInstance.control.value).toEqual([null!, 'pizza-1', null!]);
});
| {
"end_byte": 161412,
"start_byte": 152605,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_161418_169905 | t('should select all options when pressing ctrl + a', () => {
const selectElement = fixture.nativeElement.querySelector('mat-select');
const options = fixture.componentInstance.options.toArray();
expect(testInstance.control.value).toBeFalsy();
expect(options.every(option => option.selected)).toBe(false);
fixture.componentInstance.select.open();
fixture.detectChanges();
const event = createKeyboardEvent('keydown', A, undefined, {control: true});
dispatchEvent(selectElement, event);
fixture.detectChanges();
expect(options.every(option => option.selected)).toBe(true);
expect(testInstance.control.value).toEqual([
'steak-0',
'pizza-1',
'tacos-2',
'sandwich-3',
'chips-4',
'eggs-5',
'pasta-6',
'sushi-7',
]);
});
it('should skip disabled options when using ctrl + a', () => {
const selectElement = fixture.nativeElement.querySelector('mat-select');
const options = fixture.componentInstance.options.toArray();
for (let i = 0; i < 3; i++) {
options[i].disabled = true;
}
expect(testInstance.control.value).toBeFalsy();
fixture.componentInstance.select.open();
fixture.detectChanges();
const event = createKeyboardEvent('keydown', A, undefined, {control: true});
dispatchEvent(selectElement, event);
fixture.detectChanges();
expect(testInstance.control.value).toEqual([
'sandwich-3',
'chips-4',
'eggs-5',
'pasta-6',
'sushi-7',
]);
});
it('should select all options when pressing ctrl + a when some options are selected', () => {
const selectElement = fixture.nativeElement.querySelector('mat-select');
const options = fixture.componentInstance.options.toArray();
options[0].select();
fixture.detectChanges();
expect(testInstance.control.value).toEqual(['steak-0']);
expect(options.some(option => option.selected)).toBe(true);
fixture.componentInstance.select.open();
fixture.detectChanges();
const event = createKeyboardEvent('keydown', A, undefined, {control: true});
dispatchEvent(selectElement, event);
fixture.detectChanges();
expect(options.every(option => option.selected)).toBe(true);
expect(testInstance.control.value).toEqual([
'steak-0',
'pizza-1',
'tacos-2',
'sandwich-3',
'chips-4',
'eggs-5',
'pasta-6',
'sushi-7',
]);
});
it('should deselect all options with ctrl + a if all options are selected', () => {
const selectElement = fixture.nativeElement.querySelector('mat-select');
const options = fixture.componentInstance.options.toArray();
options.forEach(option => option.select());
fixture.detectChanges();
expect(testInstance.control.value).toEqual([
'steak-0',
'pizza-1',
'tacos-2',
'sandwich-3',
'chips-4',
'eggs-5',
'pasta-6',
'sushi-7',
]);
expect(options.every(option => option.selected)).toBe(true);
fixture.componentInstance.select.open();
fixture.detectChanges();
const event = createKeyboardEvent('keydown', A, undefined, {control: true});
dispatchEvent(selectElement, event);
fixture.detectChanges();
expect(options.some(option => option.selected)).toBe(false);
expect(testInstance.control.value).toEqual([]);
});
it('should not throw when selecting a large amount of options', fakeAsync(() => {
fixture.destroy();
const lotsOfOptionsFixture = TestBed.createComponent(MultiSelectWithLotsOfOptions);
expect(() => {
lotsOfOptionsFixture.componentInstance.checkAll();
lotsOfOptionsFixture.detectChanges();
flush();
}).not.toThrow();
}));
it('should be able to programmatically set an array with duplicate values', () => {
testInstance.foods = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'pizza-1', viewValue: 'Pizza'},
];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
testInstance.control.setValue(['steak-0', 'pizza-1', 'pizza-1', 'pizza-1']);
fixture.detectChanges();
trigger.click();
fixture.detectChanges();
const optionNodes = Array.from(overlayContainerElement.querySelectorAll('mat-option'));
const optionInstances = testInstance.options.toArray();
expect(optionNodes.map(node => node.classList.contains('mdc-list-item--selected'))).toEqual([
true,
true,
true,
true,
false,
false,
]);
expect(optionInstances.map(instance => instance.selected)).toEqual([
true,
true,
true,
true,
false,
false,
]);
});
it('should update the option selected state if the same array is mutated and passed back in', () => {
const value: string[] = [];
trigger.click();
testInstance.control.setValue(value);
fixture.detectChanges();
const optionNodes = Array.from<HTMLElement>(
overlayContainerElement.querySelectorAll('mat-option'),
);
const optionInstances = testInstance.options.toArray();
expect(
optionNodes.some(option => {
return option.classList.contains('mdc-list-item--selected');
}),
).toBe(false);
expect(optionInstances.some(option => option.selected)).toBe(false);
value.push('eggs-5');
testInstance.control.setValue(value);
fixture.detectChanges();
expect(optionNodes[5].classList).toContain('mdc-list-item--selected');
expect(optionInstances[5].selected).toBe(true);
});
});
it('should be able to provide default values through an injection token', fakeAsync(() => {
configureMatSelectTestingModule(
[NgModelSelect],
[
{
provide: MAT_SELECT_CONFIG,
useValue: {
disableOptionCentering: true,
typeaheadDebounceInterval: 1337,
overlayPanelClass: 'test-panel-class',
panelWidth: null,
} as MatSelectConfig,
},
],
);
const fixture = TestBed.createComponent(NgModelSelect);
fixture.detectChanges();
const select = fixture.componentInstance.select;
select.open();
fixture.detectChanges();
flush();
expect(select.disableOptionCentering).toBe(true);
expect(select.typeaheadDebounceInterval).toBe(1337);
expect(document.querySelector('.cdk-overlay-pane')?.classList).toContain('test-panel-class');
expect(select.panelWidth).toBeNull();
}));
it('should be able to hide checkmark icon through an injection token', () => {
const matSelectConfig: MatSelectConfig = {hideSingleSelectionIndicator: true};
configureMatSelectTestingModule(
[NgModelSelect],
[
{
provide: MAT_SELECT_CONFIG,
useValue: matSelectConfig,
},
],
);
const fixture = TestBed.createComponent(NgModelSelect);
fixture.detectChanges();
const select = fixture.componentInstance.select;
fixture.componentInstance.select.value = fixture.componentInstance.foods[0].value;
fixture.changeDetectorRef.markForCheck();
select.open();
fixture.detectChanges();
// Select the first value to ensure selection state is displayed. That way this test ensures
// that the selection state hides the checkmark icon, rather than hiding the checkmark icon
// because nothing is selected.
expect(document.querySelector('mat-option[aria-selected="true"]'))
.withContext('expecting selection state to be displayed')
.not.toBeNull();
const pseudoCheckboxes = document.querySelectorAll('.mat-pseudo-checkbox');
expect(pseudoCheckboxes.length)
.withContext('expecting not to display a pseudo-checkbox')
.toBe(0);
});
it('should not not throw if the select is inside an ng-container with ngIf', () => {
configureMatSelectTestingModule([SelectInNgContainer]);
const fixture = TestBed.createComponent(SelectInNgContainer);
expect(() => fixture.detectChanges()).not.toThrow();
});
| {
"end_byte": 169905,
"start_byte": 161418,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_169909_177383 | escribe('page up/down with disabled options', () => {
let fixture: ComponentFixture<BasicSelectWithFirstAndLastOptionDisabled>;
let host: HTMLElement;
beforeEach(waitForAsync(() =>
configureMatSelectTestingModule([BasicSelectWithFirstAndLastOptionDisabled])));
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(BasicSelectWithFirstAndLastOptionDisabled);
fixture.detectChanges();
fixture.componentInstance.select.open();
fixture.detectChanges();
flush();
fixture.detectChanges();
host = fixture.debugElement.query(By.css('mat-select'))!.nativeElement;
}));
it('should be able to scroll to disabled option when pressing PAGE_UP', fakeAsync(() => {
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(1);
dispatchKeyboardEvent(host, 'keydown', PAGE_UP);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(0);
dispatchKeyboardEvent(host, 'keydown', PAGE_UP);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(0);
}));
it('should be able to scroll to disabled option when pressing PAGE_DOWN', fakeAsync(() => {
dispatchKeyboardEvent(host, 'keydown', PAGE_DOWN);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(7);
dispatchKeyboardEvent(host, 'keydown', PAGE_DOWN);
fixture.detectChanges();
flush();
expect(fixture.componentInstance.select._keyManager.activeItemIndex).toBe(7);
}));
});
});
@Component({
selector: 'basic-select',
template: `
<div [style.height.px]="heightAbove"></div>
<mat-form-field>
@if (hasLabel) {
<mat-label>Select a food</mat-label>
}
<mat-select placeholder="Food" [formControl]="control" [required]="isRequired"
[tabIndex]="tabIndexOverride" [aria-describedby]="ariaDescribedBy"
[aria-label]="ariaLabel" [aria-labelledby]="ariaLabelledby"
[panelClass]="panelClass" [disableRipple]="disableRipple"
[typeaheadDebounceInterval]="typeaheadDebounceInterval"
[panelWidth]="panelWidth">
@for (food of foods; track food) {
<mat-option [value]="food.value" [disabled]="food.disabled">
{{ capitalize ? food.viewValue.toUpperCase() : food.viewValue }}
</mat-option>
}
</mat-select>
@if (hint) {
<mat-hint>{{ hint }}</mat-hint>
}
</mat-form-field>
<div [style.height.px]="heightBelow"></div>
`,
standalone: false,
})
class BasicSelect {
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;
heightAbove = 0;
heightBelow = 0;
hasLabel = true;
hint: string;
tabIndexOverride: number;
ariaDescribedBy: string;
ariaLabel: string;
ariaLabelledby: string;
panelClass = ['custom-one', 'custom-two'];
disableRipple: boolean;
typeaheadDebounceInterval: number;
capitalize = false;
panelWidth: string | null | number = 'auto';
@ViewChild(MatSelect, {static: true}) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
}
@Component({
selector: 'ng-model-select',
template: `
<mat-form-field>
<mat-select placeholder="Food" ngModel [disabled]="isDisabled">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class NgModelSelect {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
];
isDisabled: boolean;
@ViewChild(MatSelect) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
}
@Component({
selector: 'many-selects',
template: `
<mat-form-field>
<mat-select placeholder="First">
<mat-option value="one">one</mat-option>
<mat-option value="two">two</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-select placeholder="Second">
<mat-option value="three">three</mat-option>
<mat-option value="four">four</mat-option>
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class ManySelects {}
@Component({
selector: 'ng-if-select',
template: `
@if (isShowing) {
<div>
<mat-form-field>
<mat-select placeholder="Food I want to eat right now" [formControl]="control">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
}
`,
standalone: false,
})
class NgIfSelect {
isShowing = false;
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
];
control = new FormControl('pizza-1');
@ViewChild(MatSelect) select: MatSelect;
}
@Component({
selector: 'select-with-change-event',
template: `
<mat-form-field>
<mat-select (selectionChange)="changeListener($event)">
@for (food of foods; track food) {
<mat-option [value]="food">{{ food }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class SelectWithChangeEvent {
foods: string[] = [
'steak-0',
'pizza-1',
'tacos-2',
'sandwich-3',
'chips-4',
'eggs-5',
'pasta-6',
'sushi-7',
];
changeListener = jasmine.createSpy('MatSelect change listener');
}
@Component({
selector: 'select-init-without-options',
template: `
<mat-form-field>
<mat-select placeholder="Food I want to eat right now" [formControl]="control">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class SelectInitWithoutOptions {
foods: any[];
control = new FormControl('pizza-1');
@ViewChild(MatSelect) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
addOptions() {
this.foods = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
];
}
}
@Component({
selector: 'custom-select-accessor',
template: `<mat-form-field><mat-select></mat-select></mat-form-field>`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: CustomSelectAccessor,
multi: true,
},
],
standalone: false,
})
class CustomSelectAccessor implements ControlValueAccessor {
@ViewChild(MatSelect) select: MatSelect;
writeValue: (value?: any) => void = () => {};
registerOnChange: (changeFn?: (value: any) => void) => void = () => {};
registerOnTouched: (touchedFn?: () => void) => void = () => {};
}
| {
"end_byte": 177383,
"start_byte": 169909,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_177385_184302 | Component({
selector: 'comp-with-custom-select',
template: `<custom-select-accessor [formControl]="ctrl"></custom-select-accessor>`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: CustomSelectAccessor,
multi: true,
},
],
standalone: false,
})
class CompWithCustomSelect {
ctrl = new FormControl('initial value');
@ViewChild(CustomSelectAccessor, {static: true}) customAccessor: CustomSelectAccessor;
}
@Component({
selector: 'select-infinite-loop',
template: `
<mat-form-field>
<mat-select [(ngModel)]="value"></mat-select>
</mat-form-field>
<throws-error-on-init></throws-error-on-init>
`,
standalone: false,
})
class SelectWithErrorSibling {
value: string;
}
@Component({
selector: 'throws-error-on-init',
template: '',
standalone: false,
})
class ThrowsErrorOnInit implements OnInit {
ngOnInit() {
throw Error('Oh no!');
}
}
@Component({
selector: 'basic-select-on-push',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<mat-form-field>
<mat-select placeholder="Food" [formControl]="control">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class BasicSelectOnPush {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
];
control = new FormControl('');
}
@Component({
selector: 'basic-select-on-push-preselected',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<mat-form-field>
<mat-select placeholder="Food" [formControl]="control">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class BasicSelectOnPushPreselected {
@ViewChild(MatSelect) select: MatSelect;
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
];
control = new FormControl('pizza-1');
}
@Component({
selector: 'floating-label-select',
template: `
<mat-form-field [floatLabel]="floatLabel">
<mat-label>Select a food</mat-label>
<mat-select [placeholder]="placeholder" [formControl]="control">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class FloatLabelSelect {
floatLabel: FloatLabelType | null = 'auto';
control = new FormControl('');
placeholder = 'Food I want to eat right now';
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
];
@ViewChild(MatSelect) select: MatSelect;
}
@Component({
selector: 'multi-select',
template: `
<mat-form-field>
<mat-select multiple placeholder="Food" [formControl]="control"
[sortComparator]="sortComparator">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class MultiSelect {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
{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);
@ViewChild(MatSelect) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
sortComparator: (a: MatOption, b: MatOption, options: MatOption[]) => number;
}
@Component({
selector: 'select-with-plain-tabindex',
template: `<mat-form-field><mat-select tabindex="5"></mat-select></mat-form-field>`,
standalone: false,
})
class SelectWithPlainTabindex {}
@Component({
selector: 'select-early-sibling-access',
template: `
<mat-form-field>
<mat-select #select="matSelect"></mat-select>
</mat-form-field>
@if (select.selected) {
<div></div>
}
`,
standalone: false,
})
class SelectEarlyAccessSibling {}
@Component({
selector: 'basic-select-initially-hidden',
template: `
<mat-form-field>
<mat-select [style.display]="isVisible ? 'block' : 'none'">
<mat-option value="value">There are no other options</mat-option>
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class BasicSelectInitiallyHidden {
isVisible = false;
}
@Component({
selector: 'basic-select-no-placeholder',
template: `
<mat-form-field>
<mat-select>
<mat-option value="value">There are no other options</mat-option>
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class BasicSelectNoPlaceholder {}
@Component({
selector: 'basic-select-with-theming',
template: `
<mat-form-field [color]="theme">
<mat-select placeholder="Food">
<mat-option value="steak-0">Steak</mat-option>
<mat-option value="pizza-1">Pizza</mat-option>
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class BasicSelectWithTheming {
@ViewChild(MatSelect) select: MatSelect;
theme: string;
}
@Component({
selector: 'reset-values-select',
template: `
<mat-form-field>
<mat-label>Select a food</mat-label>
<mat-select [formControl]="control">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
<mat-option>None</mat-option>
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class ResetValuesSelect {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
{value: false, viewValue: 'Falsy'},
{viewValue: 'Undefined'},
{value: null, viewValue: 'Null'},
];
control = new FormControl('' as string | boolean | null);
@ViewChild(MatSelect) select: MatSelect;
}
@Component({
template: `
<mat-form-field>
<mat-select [formControl]="control">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class FalsyValueSelect {
foods: any[] = [
{value: 0, viewValue: 'Steak'},
{value: 1, viewValue: 'Pizza'},
];
control = new FormControl<number | null>(null);
@ViewChildren(MatOption) options: QueryList<MatOption>;
}
| {
"end_byte": 184302,
"start_byte": 177385,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_184304_191483 | Component({
selector: 'select-with-groups',
template: `
<mat-form-field>
<mat-select placeholder="Pokemon" [formControl]="control">
@for (group of pokemonTypes; track group) {
<mat-optgroup [label]="group.name" [disabled]="group.disabled">
@for (pokemon of group.pokemon; track pokemon) {
<mat-option [value]="pokemon.value">{{ pokemon.viewValue }}</mat-option>
}
</mat-optgroup>
}
<mat-option value="mime-11">Mr. Mime</mat-option>
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class SelectWithGroups {
control = new FormControl('');
pokemonTypes = [
{
name: 'Grass',
pokemon: [
{value: 'bulbasaur-0', viewValue: 'Bulbasaur'},
{value: 'oddish-1', viewValue: 'Oddish'},
{value: 'bellsprout-2', viewValue: 'Bellsprout'},
],
},
{
name: 'Water',
disabled: true,
pokemon: [
{value: 'squirtle-3', viewValue: 'Squirtle'},
{value: 'psyduck-4', viewValue: 'Psyduck'},
{value: 'horsea-5', viewValue: 'Horsea'},
],
},
{
name: 'Fire',
pokemon: [
{value: 'charmander-6', viewValue: 'Charmander'},
{value: 'vulpix-7', viewValue: 'Vulpix'},
{value: 'flareon-8', viewValue: 'Flareon'},
],
},
{
name: 'Psychic',
pokemon: [
{value: 'mew-9', viewValue: 'Mew'},
{value: 'mewtwo-10', viewValue: 'Mewtwo'},
],
},
];
@ViewChild(MatSelect) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
}
@Component({
selector: 'select-with-groups',
template: `
<mat-form-field>
<mat-select placeholder="Pokemon" [formControl]="control">
@for (group of pokemonTypes; track group) {
<mat-optgroup [label]="group.name">
@for (pokemon of group.pokemon; track pokemon) {
<mat-option [value]="pokemon.value">{{ pokemon.viewValue }}</mat-option>
}
</mat-optgroup>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class SelectWithGroupsAndNgContainer {
control = new FormControl('');
pokemonTypes = [
{
name: 'Grass',
pokemon: [{value: 'bulbasaur-0', viewValue: 'Bulbasaur'}],
},
];
}
@Component({
template: `
<form>
<mat-form-field>
<mat-select [(ngModel)]="value"></mat-select>
</mat-form-field>
</form>
`,
standalone: false,
})
class InvalidSelectInForm {
value: any;
}
@Component({
template: `
<form [formGroup]="formGroup">
<mat-form-field>
<mat-label>Food</mat-label>
<mat-select formControlName="food">
@for (option of options; track option) {
<mat-option [value]="option.value">{{option.viewValue}}</mat-option>
}
</mat-select>
<mat-error>This field is required</mat-error>
</mat-form-field>
</form>
`,
standalone: false,
})
class SelectInsideFormGroup {
@ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective;
@ViewChild(MatSelect) select: MatSelect;
options = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
];
formControl = new FormControl('', Validators.required);
formGroup = new FormGroup({
food: this.formControl,
});
}
@Component({
template: `
<mat-form-field>
<mat-select placeholder="Food" [(value)]="selectedFood">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class BasicSelectWithoutForms {
selectedFood: string | null;
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'sandwich-2', viewValue: 'Sandwich'},
];
@ViewChild(MatSelect) select: MatSelect;
}
@Component({
template: `
<mat-form-field>
<mat-select placeholder="Food" [(value)]="selectedFood">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class BasicSelectWithoutFormsPreselected {
selectedFood = 'pizza-1';
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
];
@ViewChild(MatSelect) select: MatSelect;
}
@Component({
template: `
<mat-form-field>
<mat-select placeholder="Food" [(value)]="selectedFoods" multiple>
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class BasicSelectWithoutFormsMultiple {
selectedFoods: string[];
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'sandwich-2', viewValue: 'Sandwich'},
];
@ViewChild(MatSelect) select: MatSelect;
}
@Component({
selector: 'select-with-custom-trigger',
template: `
<mat-form-field>
<mat-select placeholder="Food" [formControl]="control" #select="matSelect">
<mat-select-trigger>
{{ select.selected?.viewValue.split('').reverse().join('') }}
</mat-select-trigger>
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class SelectWithCustomTrigger {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
];
control = new FormControl('');
}
@Component({
selector: 'ng-model-compare-with',
template: `
<mat-form-field>
<mat-select [ngModel]="selectedFood" (ngModelChange)="setFoodByCopy($event)"
[compareWith]="comparator">
@for (food of foods; track food) {
<mat-option [value]="food">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class NgModelCompareWithSelect {
foods: {value: string; viewValue: string}[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
];
selectedFood: {value: string; viewValue: string} = {value: 'pizza-1', viewValue: 'Pizza'};
comparator: ((f1: any, f2: any) => boolean) | null = this.compareByValue;
@ViewChild(MatSelect) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
useCompareByValue() {
this.comparator = this.compareByValue;
}
useCompareByReference() {
this.comparator = this.compareByReference;
}
useNullComparator() {
this.comparator = null;
}
compareByValue(f1: any, f2: any) {
return f1 && f2 && f1.value === f2.value;
}
compareByReference(f1: any, f2: any) {
return f1 === f2;
}
setFoodByCopy(newValue: {value: string; viewValue: string}) {
this.selectedFood = {...{}, ...newValue};
}
}
| {
"end_byte": 191483,
"start_byte": 184304,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_191485_198417 | Component({
template: `
<mat-select placeholder="Food" [formControl]="control" [errorStateMatcher]="errorStateMatcher">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
`,
standalone: false,
})
class CustomErrorBehaviorSelect {
@ViewChild(MatSelect) select: MatSelect;
control = new FormControl('');
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
];
errorStateMatcher: ErrorStateMatcher;
}
@Component({
template: `
<mat-form-field>
<mat-select placeholder="Food" [(ngModel)]="selectedFoods">
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class SingleSelectWithPreselectedArrayValues {
foods: any[] = [
{value: ['steak-0', 'steak-1'], viewValue: 'Steak'},
{value: ['pizza-1', 'pizza-2'], viewValue: 'Pizza'},
{value: ['tacos-2', 'tacos-3'], viewValue: 'Tacos'},
];
selectedFoods = this.foods[1].value;
@ViewChild(MatSelect) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
}
@Component({
selector: 'select-without-option-centering',
template: `
<mat-form-field>
<mat-select placeholder="Food" [formControl]="control" disableOptionCentering>
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class SelectWithoutOptionCentering {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
{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('pizza-1');
@ViewChild(MatSelect) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
}
@Component({
template: `
<mat-form-field>
<mat-label>Select a thing</mat-label>
<mat-select [placeholder]="placeholder">
<mat-option value="thing">A thing</mat-option>
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class SelectWithFormFieldLabel {
placeholder: string;
}
@Component({
template: `
<mat-form-field appearance="fill">
<mat-label>Select something</mat-label>
@if (showSelect) {
<mat-select>
<mat-option value="1">One</mat-option>
</mat-select>
}
</mat-form-field>
`,
standalone: false,
})
class SelectWithNgIfAndLabel {
showSelect = true;
}
@Component({
template: `
<mat-form-field>
<mat-select multiple [ngModel]="value">
@for (item of items; track item) {
<mat-option [value]="item">{{item}}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class MultiSelectWithLotsOfOptions {
items = new Array(100).fill(0).map((_, i) => i);
value: number[] = [];
checkAll() {
this.value = [...this.items];
}
uncheckAll() {
this.value = [];
}
}
@Component({
selector: 'basic-select-with-reset',
template: `
<mat-form-field>
<mat-select [formControl]="control">
<mat-option>Reset</mat-option>
<mat-option value="a">A</mat-option>
<mat-option value="b">B</mat-option>
<mat-option value="c">C</mat-option>
</mat-select>
</mat-form-field>
`,
standalone: false,
})
class SelectWithResetOptionAndFormControl {
@ViewChild(MatSelect) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
control = new FormControl('');
}
@Component({
selector: 'select-with-placeholder-in-ngcontainer-with-ngIf',
template: `
<mat-form-field>
@if (true) {
<mat-select placeholder="Product Area">
<mat-option value="a">A</mat-option>
<mat-option value="b">B</mat-option>
<mat-option value="c">C</mat-option>
</mat-select>
}
</mat-form-field>
`,
standalone: false,
})
class SelectInNgContainer {}
@Component({
template: `
<form [formGroup]="form">
<mat-form-field>
<mat-select formControlName="control">
<mat-option value="1">One</mat-option>
</mat-select>
</mat-form-field>
</form>
`,
standalone: false,
})
class SelectInsideDynamicFormGroup {
private _formBuilder = inject(FormBuilder);
@ViewChild(MatSelect) select: MatSelect;
form: FormGroup;
private readonly _changeDetectorRef = inject(ChangeDetectorRef);
constructor() {
this.assignGroup(false);
}
assignGroup(isDisabled: boolean) {
this.form = this._formBuilder.group({
control: {value: '', disabled: isDisabled},
});
this._changeDetectorRef.markForCheck();
}
}
@Component({
selector: 'basic-select',
template: `
<div [style.height.px]="heightAbove"></div>
<mat-form-field>
@if (hasLabel) {
<mat-label>Select a food</mat-label>
}
<mat-select placeholder="Food" [formControl]="control" [required]="isRequired"
[tabIndex]="tabIndexOverride" [aria-describedby]="ariaDescribedBy"
[aria-label]="ariaLabel" [aria-labelledby]="ariaLabelledby"
[panelClass]="panelClass" [disableRipple]="disableRipple"
[typeaheadDebounceInterval]="typeaheadDebounceInterval">
@for (food of foods; track food) {
<mat-option [value]="food.value" [disabled]="food.disabled">
{{ food.viewValue }}
</mat-option>
}
</mat-select>
@if (hint) {
<mat-hint>{{ hint }}</mat-hint>
}
</mat-form-field>
<div [style.height.px]="heightBelow"></div>
`,
standalone: false,
})
class BasicSelectWithFirstAndLastOptionDisabled {
foods: any[] = [
{value: 'steak-0', viewValue: 'Steak', disabled: true},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
{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', disabled: true},
];
control = new FormControl<string | null>(null);
isRequired: boolean;
heightAbove = 0;
heightBelow = 0;
hasLabel = true;
hint: string;
tabIndexOverride: number;
ariaDescribedBy: string;
ariaLabel: string;
ariaLabelledby: string;
panelClass = ['custom-one', 'custom-two'];
disableRipple: boolean;
typeaheadDebounceInterval: number;
@ViewChild(MatSelect, {static: true}) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
}
| {
"end_byte": 198417,
"start_byte": 191485,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.spec.ts_198419_199431 | Component({
selector: 'select-inside-a-modal',
template: `
<button cdkOverlayOrigin #trigger="cdkOverlayOrigin">open dialog</button>
<ng-template cdkConnectedOverlay [cdkConnectedOverlayOpen]="true"
[cdkConnectedOverlayOrigin]="trigger">
<div role="dialog" [attr.aria-modal]="'true'" #modal>
<mat-form-field>
<mat-label>Select a food</mat-label>
<mat-select placeholder="Food" ngModel>
@for (food of foods; track food) {
<mat-option [value]="food.value">{{ food.viewValue }}</mat-option>
}
</mat-select>
</mat-form-field>
</div>
</ng-template>
`,
standalone: false,
})
class SelectInsideAModal {
foods = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'},
];
@ViewChild(MatSelect) select: MatSelect;
@ViewChildren(MatOption) options: QueryList<MatOption>;
@ViewChild('modal') modal: ElementRef;
}
| {
"end_byte": 199431,
"start_byte": 198419,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.spec.ts"
} |
components/src/material/select/select.ts_0_6022 | /**
* @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 {
ActiveDescendantKeyManager,
addAriaReferencedId,
LiveAnnouncer,
removeAriaReferencedId,
} from '@angular/cdk/a11y';
import {Directionality} from '@angular/cdk/bidi';
import {SelectionModel} from '@angular/cdk/collections';
import {
A,
DOWN_ARROW,
ENTER,
hasModifierKey,
LEFT_ARROW,
RIGHT_ARROW,
SPACE,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {
CdkConnectedOverlay,
CdkOverlayOrigin,
ConnectedPosition,
Overlay,
ScrollStrategy,
} from '@angular/cdk/overlay';
import {ViewportRuler} from '@angular/cdk/scrolling';
import {
AfterContentInit,
booleanAttribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ContentChildren,
Directive,
DoCheck,
ElementRef,
EventEmitter,
inject,
InjectionToken,
Input,
numberAttribute,
OnChanges,
OnDestroy,
OnInit,
Output,
QueryList,
SimpleChanges,
ViewChild,
ViewEncapsulation,
HostAttributeToken,
} from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
FormGroupDirective,
NgControl,
NgForm,
Validators,
} from '@angular/forms';
import {
_countGroupLabelsBeforeOption,
_ErrorStateTracker,
_getOptionScrollPosition,
ErrorStateMatcher,
MAT_OPTGROUP,
MAT_OPTION_PARENT_COMPONENT,
MatOptgroup,
MatOption,
MatOptionSelectionChange,
} from '@angular/material/core';
import {MAT_FORM_FIELD, MatFormField, MatFormFieldControl} from '@angular/material/form-field';
import {defer, merge, Observable, Subject} from 'rxjs';
import {
distinctUntilChanged,
filter,
map,
startWith,
switchMap,
take,
takeUntil,
} from 'rxjs/operators';
import {matSelectAnimations} from './select-animations';
import {
getMatSelectDynamicMultipleError,
getMatSelectNonArrayValueError,
getMatSelectNonFunctionValueError,
} from './select-errors';
import {NgClass} from '@angular/common';
let nextUniqueId = 0;
/** Injection token that determines the scroll handling while a select is open. */
export const MAT_SELECT_SCROLL_STRATEGY = new InjectionToken<() => ScrollStrategy>(
'mat-select-scroll-strategy',
{
providedIn: 'root',
factory: () => {
const overlay = inject(Overlay);
return () => overlay.scrollStrategies.reposition();
},
},
);
/** @docs-private */
export function MAT_SELECT_SCROLL_STRATEGY_PROVIDER_FACTORY(
overlay: Overlay,
): () => ScrollStrategy {
return () => overlay.scrollStrategies.reposition();
}
/** Object that can be used to configure the default options for the select module. */
export interface MatSelectConfig {
/** Whether option centering should be disabled. */
disableOptionCentering?: boolean;
/** Time to wait in milliseconds after the last keystroke before moving focus to an item. */
typeaheadDebounceInterval?: number;
/** Class or list of classes to be applied to the menu's overlay panel. */
overlayPanelClass?: string | string[];
/** Wheter icon indicators should be hidden for single-selection. */
hideSingleSelectionIndicator?: boolean;
/**
* Width of the panel. If set to `auto`, the panel will match the trigger width.
* If set to null or an empty string, the panel will grow to match the longest option's text.
*/
panelWidth?: string | number | null;
}
/** Injection token that can be used to provide the default options the select module. */
export const MAT_SELECT_CONFIG = new InjectionToken<MatSelectConfig>('MAT_SELECT_CONFIG');
/** @docs-private */
export const MAT_SELECT_SCROLL_STRATEGY_PROVIDER = {
provide: MAT_SELECT_SCROLL_STRATEGY,
deps: [Overlay],
useFactory: MAT_SELECT_SCROLL_STRATEGY_PROVIDER_FACTORY,
};
/**
* Injection token that can be used to reference instances of `MatSelectTrigger`. It serves as
* alternative token to the actual `MatSelectTrigger` class which could cause unnecessary
* retention of the class and its directive metadata.
*/
export const MAT_SELECT_TRIGGER = new InjectionToken<MatSelectTrigger>('MatSelectTrigger');
/** Change event object that is emitted when the select value has changed. */
export class MatSelectChange {
constructor(
/** Reference to the select that emitted the change event. */
public source: MatSelect,
/** Current value of the select that emitted the event. */
public value: any,
) {}
}
@Component({
selector: 'mat-select',
exportAs: 'matSelect',
templateUrl: 'select.html',
styleUrl: 'select.css',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'role': 'combobox',
'aria-haspopup': 'listbox',
'class': 'mat-mdc-select',
'[attr.id]': 'id',
'[attr.tabindex]': 'disabled ? -1 : tabIndex',
'[attr.aria-controls]': 'panelOpen ? id + "-panel" : null',
'[attr.aria-expanded]': 'panelOpen',
'[attr.aria-label]': 'ariaLabel || null',
'[attr.aria-required]': 'required.toString()',
'[attr.aria-disabled]': 'disabled.toString()',
'[attr.aria-invalid]': 'errorState',
'[attr.aria-activedescendant]': '_getAriaActiveDescendant()',
'[class.mat-mdc-select-disabled]': 'disabled',
'[class.mat-mdc-select-invalid]': 'errorState',
'[class.mat-mdc-select-required]': 'required',
'[class.mat-mdc-select-empty]': 'empty',
'[class.mat-mdc-select-multiple]': 'multiple',
'(keydown)': '_handleKeydown($event)',
'(focus)': '_onFocus()',
'(blur)': '_onBlur()',
},
animations: [matSelectAnimations.transformPanel],
providers: [
{provide: MatFormFieldControl, useExisting: MatSelect},
{provide: MAT_OPTION_PARENT_COMPONENT, useExisting: MatSelect},
],
imports: [CdkOverlayOrigin, CdkConnectedOverlay, NgClass],
})
export class MatSelect
implements
AfterContentInit,
OnChanges,
OnDestroy,
OnInit,
DoCheck,
ControlValueAccessor,
MatFormFieldControl<any> | {
"end_byte": 6022,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.ts"
} |
components/src/material/select/select.ts_6023_14418 | {
protected _viewportRuler = inject(ViewportRuler);
protected _changeDetectorRef = inject(ChangeDetectorRef);
readonly _elementRef = inject(ElementRef);
private _dir = inject(Directionality, {optional: true});
protected _parentFormField = inject<MatFormField>(MAT_FORM_FIELD, {optional: true});
ngControl = inject(NgControl, {self: true, optional: true})!;
private _liveAnnouncer = inject(LiveAnnouncer);
protected _defaultOptions = inject(MAT_SELECT_CONFIG, {optional: true});
/** All of the defined select options. */
@ContentChildren(MatOption, {descendants: true}) options: QueryList<MatOption>;
// TODO(crisbeto): this is only necessary for the non-MDC select, but it's technically a
// public API so we have to keep it. It should be deprecated and removed eventually.
/** All of the defined groups of options. */
@ContentChildren(MAT_OPTGROUP, {descendants: true}) optionGroups: QueryList<MatOptgroup>;
/** User-supplied override of the trigger element. */
@ContentChild(MAT_SELECT_TRIGGER) customTrigger: MatSelectTrigger;
/**
* This position config ensures that the top "start" corner of the overlay
* is aligned with with the top "start" of the origin by default (overlapping
* the trigger completely). If the panel cannot fit below the trigger, it
* will fall back to a position above the trigger.
*/
_positions: ConnectedPosition[] = [
{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top',
},
{
originX: 'end',
originY: 'bottom',
overlayX: 'end',
overlayY: 'top',
},
{
originX: 'start',
originY: 'top',
overlayX: 'start',
overlayY: 'bottom',
panelClass: 'mat-mdc-select-panel-above',
},
{
originX: 'end',
originY: 'top',
overlayX: 'end',
overlayY: 'bottom',
panelClass: 'mat-mdc-select-panel-above',
},
];
/** Scrolls a particular option into the view. */
_scrollOptionIntoView(index: number): void {
const option = this.options.toArray()[index];
if (option) {
const panel: HTMLElement = this.panel.nativeElement;
const labelCount = _countGroupLabelsBeforeOption(index, this.options, this.optionGroups);
const element = option._getHostElement();
if (index === 0 && labelCount === 1) {
// If we've got one group label before the option and we're at the top option,
// scroll the list to the top. This is better UX than scrolling the list to the
// top of the option, because it allows the user to read the top group's label.
panel.scrollTop = 0;
} else {
panel.scrollTop = _getOptionScrollPosition(
element.offsetTop,
element.offsetHeight,
panel.scrollTop,
panel.offsetHeight,
);
}
}
}
/** Called when the panel has been opened and the overlay has settled on its final position. */
private _positioningSettled() {
this._scrollOptionIntoView(this._keyManager.activeItemIndex || 0);
}
/** Creates a change event object that should be emitted by the select. */
private _getChangeEvent(value: any) {
return new MatSelectChange(this, value);
}
/** Factory function used to create a scroll strategy for this select. */
private _scrollStrategyFactory = inject(MAT_SELECT_SCROLL_STRATEGY);
/** Whether or not the overlay panel is open. */
private _panelOpen = false;
/** Comparison function to specify which option is displayed. Defaults to object equality. */
private _compareWith = (o1: any, o2: any) => o1 === o2;
/** Unique id for this input. */
private _uid = `mat-select-${nextUniqueId++}`;
/** Current `aria-labelledby` value for the select trigger. */
private _triggerAriaLabelledBy: string | null = null;
/**
* Keeps track of the previous form control assigned to the select.
* Used to detect if it has changed.
*/
private _previousControl: AbstractControl | null | undefined;
/** Emits whenever the component is destroyed. */
protected readonly _destroy = new Subject<void>();
/** Tracks the error state of the select. */
private _errorStateTracker: _ErrorStateTracker;
/**
* Emits whenever the component state changes and should cause the parent
* form-field to update. Implemented as part of `MatFormFieldControl`.
* @docs-private
*/
readonly stateChanges = new Subject<void>();
/**
* Disable the automatic labeling to avoid issues like #27241.
* @docs-private
*/
readonly disableAutomaticLabeling = true;
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
@Input('aria-describedby') userAriaDescribedBy: string;
/** Deals with the selection logic. */
_selectionModel: SelectionModel<MatOption>;
/** Manages keyboard events for options in the panel. */
_keyManager: ActiveDescendantKeyManager<MatOption>;
/** Ideal origin for the overlay panel. */
_preferredOverlayOrigin: CdkOverlayOrigin | ElementRef | undefined;
/** Width of the overlay panel. */
_overlayWidth: string | number;
/** `View -> model callback called when value changes` */
_onChange: (value: any) => void = () => {};
/** `View -> model callback called when select has been touched` */
_onTouched = () => {};
/** ID for the DOM node containing the select's value. */
_valueId = `mat-select-value-${nextUniqueId++}`;
/** Emits when the panel element is finished transforming in. */
readonly _panelDoneAnimatingStream = new Subject<string>();
/** Strategy that will be used to handle scrolling while the select panel is open. */
_scrollStrategy: ScrollStrategy;
_overlayPanelClass: string | string[] = this._defaultOptions?.overlayPanelClass || '';
/** Whether the select is focused. */
get focused(): boolean {
return this._focused || this._panelOpen;
}
private _focused = false;
/** A name for this control that can be used by `mat-form-field`. */
controlType = 'mat-select';
/** Trigger that opens the select. */
@ViewChild('trigger') trigger: ElementRef;
/** Panel containing the select options. */
@ViewChild('panel') panel: ElementRef;
/** Overlay pane containing the options. */
@ViewChild(CdkConnectedOverlay)
protected _overlayDir: CdkConnectedOverlay;
/** Classes to be passed to the select panel. Supports the same syntax as `ngClass`. */
@Input() panelClass: string | string[] | Set<string> | {[key: string]: any};
/** Whether the select is disabled. */
@Input({transform: booleanAttribute})
disabled: boolean = false;
/** Whether ripples in the select are disabled. */
@Input({transform: booleanAttribute})
disableRipple: boolean = false;
/** Tab index of the select. */
@Input({
transform: (value: unknown) => (value == null ? 0 : numberAttribute(value)),
})
tabIndex: number = 0;
/** Whether checkmark indicator for single-selection options is hidden. */
@Input({transform: booleanAttribute})
get hideSingleSelectionIndicator(): boolean {
return this._hideSingleSelectionIndicator;
}
set hideSingleSelectionIndicator(value: boolean) {
this._hideSingleSelectionIndicator = value;
this._syncParentProperties();
}
private _hideSingleSelectionIndicator: boolean =
this._defaultOptions?.hideSingleSelectionIndicator ?? false;
/** Placeholder to be shown if no value has been selected. */
@Input()
get placeholder(): string {
return this._placeholder;
}
set placeholder(value: string) {
this._placeholder = value;
this.stateChanges.next();
}
private _placeholder: string;
/** Whether the component is required. */
@Input({transform: booleanAttribute})
get required(): boolean {
return this._required ?? this.ngControl?.control?.hasValidator(Validators.required) ?? false;
}
set required(value: boolean) {
this._required = value;
this.stateChanges.next();
}
private _required: boolean | undefined;
/** Whether the user should be allowed to select multiple options. */
@Input({transform: booleanAttribute})
get multiple(): boolean {
return this._multiple;
}
set multiple(value: boolean) {
if (this._selectionModel && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw getMatSelectDynamicMultipleError();
}
this._multiple = value;
}
private _multiple: boolean = false; | {
"end_byte": 14418,
"start_byte": 6023,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.ts"
} |
components/src/material/select/select.ts_14422_22851 | /** Whether to center the active option over the trigger. */
@Input({transform: booleanAttribute})
disableOptionCentering = this._defaultOptions?.disableOptionCentering ?? false;
/**
* 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()
get compareWith() {
return this._compareWith;
}
set compareWith(fn: (o1: any, o2: any) => boolean) {
if (typeof fn !== 'function' && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw getMatSelectNonFunctionValueError();
}
this._compareWith = fn;
if (this._selectionModel) {
// A different comparator means the selection could change.
this._initializeSelection();
}
}
/** Value of the select control. */
@Input()
get value(): any {
return this._value;
}
set value(newValue: any) {
const hasAssigned = this._assignValue(newValue);
if (hasAssigned) {
this._onChange(newValue);
}
}
private _value: any;
/** Aria label of the select. */
@Input('aria-label') ariaLabel: string = '';
/** Input that can be used to specify the `aria-labelledby` attribute. */
@Input('aria-labelledby') ariaLabelledby: string;
/** Object used to control when error messages are shown. */
@Input()
get errorStateMatcher() {
return this._errorStateTracker.matcher;
}
set errorStateMatcher(value: ErrorStateMatcher) {
this._errorStateTracker.matcher = value;
}
/** Time to wait in milliseconds after the last keystroke before moving focus to an item. */
@Input({transform: numberAttribute})
typeaheadDebounceInterval: number;
/**
* Function used to sort the values in a select in multiple mode.
* Follows the same logic as `Array.prototype.sort`.
*/
@Input() sortComparator: (a: MatOption, b: MatOption, options: MatOption[]) => number;
/** Unique id of the element. */
@Input()
get id(): string {
return this._id;
}
set id(value: string) {
this._id = value || this._uid;
this.stateChanges.next();
}
private _id: string;
/** Whether the select is in an error state. */
get errorState() {
return this._errorStateTracker.errorState;
}
set errorState(value: boolean) {
this._errorStateTracker.errorState = value;
}
/**
* Width of the panel. If set to `auto`, the panel will match the trigger width.
* If set to null or an empty string, the panel will grow to match the longest option's text.
*/
@Input() panelWidth: string | number | null =
this._defaultOptions && typeof this._defaultOptions.panelWidth !== 'undefined'
? this._defaultOptions.panelWidth
: 'auto';
private _initialized = new Subject();
/** Combined stream of all of the child options' change events. */
readonly optionSelectionChanges: Observable<MatOptionSelectionChange> = defer(() => {
const options = this.options;
if (options) {
return options.changes.pipe(
startWith(options),
switchMap(() => merge(...options.map(option => option.onSelectionChange))),
);
}
return this._initialized.pipe(switchMap(() => this.optionSelectionChanges));
});
/** Event emitted when the select panel has been toggled. */
@Output() readonly openedChange: EventEmitter<boolean> = new EventEmitter<boolean>();
/** Event emitted when the select has been opened. */
@Output('opened') readonly _openedStream: Observable<void> = this.openedChange.pipe(
filter(o => o),
map(() => {}),
);
/** Event emitted when the select has been closed. */
@Output('closed') readonly _closedStream: Observable<void> = this.openedChange.pipe(
filter(o => !o),
map(() => {}),
);
/** Event emitted when the selected value has been changed by the user. */
@Output() readonly selectionChange = new EventEmitter<MatSelectChange>();
/**
* Event that emits whenever the raw value of the select 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>();
constructor(...args: unknown[]);
constructor() {
const defaultErrorStateMatcher = inject(ErrorStateMatcher);
const parentForm = inject(NgForm, {optional: true});
const parentFormGroup = inject(FormGroupDirective, {optional: true});
const tabIndex = inject(new HostAttributeToken('tabindex'), {optional: true});
if (this.ngControl) {
// Note: we provide the value accessor through here, instead of
// the `providers` to avoid running into a circular import.
this.ngControl.valueAccessor = this;
}
// Note that we only want to set this when the defaults pass it in, otherwise it should
// stay as `undefined` so that it falls back to the default in the key manager.
if (this._defaultOptions?.typeaheadDebounceInterval != null) {
this.typeaheadDebounceInterval = this._defaultOptions.typeaheadDebounceInterval;
}
this._errorStateTracker = new _ErrorStateTracker(
defaultErrorStateMatcher,
this.ngControl,
parentFormGroup,
parentForm,
this.stateChanges,
);
this._scrollStrategy = this._scrollStrategyFactory();
this.tabIndex = tabIndex == null ? 0 : parseInt(tabIndex) || 0;
// Force setter to be called in case id was not specified.
this.id = this.id;
}
ngOnInit() {
this._selectionModel = new SelectionModel<MatOption>(this.multiple);
this.stateChanges.next();
// We need `distinctUntilChanged` here, because some browsers will
// fire the animation end event twice for the same animation. See:
// https://github.com/angular/angular/issues/24084
this._panelDoneAnimatingStream
.pipe(distinctUntilChanged(), takeUntil(this._destroy))
.subscribe(() => this._panelDoneAnimating(this.panelOpen));
this._viewportRuler
.change()
.pipe(takeUntil(this._destroy))
.subscribe(() => {
if (this.panelOpen) {
this._overlayWidth = this._getOverlayWidth(this._preferredOverlayOrigin);
this._changeDetectorRef.detectChanges();
}
});
}
ngAfterContentInit() {
this._initialized.next();
this._initialized.complete();
this._initKeyManager();
this._selectionModel.changed.pipe(takeUntil(this._destroy)).subscribe(event => {
event.added.forEach(option => option.select());
event.removed.forEach(option => option.deselect());
});
this.options.changes.pipe(startWith(null), takeUntil(this._destroy)).subscribe(() => {
this._resetOptions();
this._initializeSelection();
});
}
ngDoCheck() {
const newAriaLabelledby = this._getTriggerAriaLabelledby();
const ngControl = this.ngControl;
// We have to manage setting the `aria-labelledby` ourselves, because part of its value
// is computed as a result of a content query which can cause this binding to trigger a
// "changed after checked" error.
if (newAriaLabelledby !== this._triggerAriaLabelledBy) {
const element: HTMLElement = this._elementRef.nativeElement;
this._triggerAriaLabelledBy = newAriaLabelledby;
if (newAriaLabelledby) {
element.setAttribute('aria-labelledby', newAriaLabelledby);
} else {
element.removeAttribute('aria-labelledby');
}
}
if (ngControl) {
// The disabled state might go out of sync if the form group is swapped out. See #17860.
if (this._previousControl !== ngControl.control) {
if (
this._previousControl !== undefined &&
ngControl.disabled !== null &&
ngControl.disabled !== this.disabled
) {
this.disabled = ngControl.disabled;
}
this._previousControl = ngControl.control;
}
this.updateErrorState();
}
}
ngOnChanges(changes: SimpleChanges) {
// Updating the disabled state is handled by the input, but we need to additionally let
// the parent form field know to run change detection when the disabled state changes.
if (changes['disabled'] || changes['userAriaDescribedBy']) {
this.stateChanges.next();
}
if (changes['typeaheadDebounceInterval'] && this._keyManager) {
this._keyManager.withTypeAhead(this.typeaheadDebounceInterval);
}
} | {
"end_byte": 22851,
"start_byte": 14422,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.ts"
} |
components/src/material/select/select.ts_22855_31125 | ngOnDestroy() {
this._keyManager?.destroy();
this._destroy.next();
this._destroy.complete();
this.stateChanges.complete();
this._clearFromModal();
}
/** Toggles the overlay panel open or closed. */
toggle(): void {
this.panelOpen ? this.close() : this.open();
}
/** Opens the overlay panel. */
open(): void {
if (!this._canOpen()) {
return;
}
// It's important that we read this as late as possible, because doing so earlier will
// return a different element since it's based on queries in the form field which may
// not have run yet. Also this needs to be assigned before we measure the overlay width.
if (this._parentFormField) {
this._preferredOverlayOrigin = this._parentFormField.getConnectedOverlayOrigin();
}
this._overlayWidth = this._getOverlayWidth(this._preferredOverlayOrigin);
this._applyModalPanelOwnership();
this._panelOpen = true;
this._keyManager.withHorizontalOrientation(null);
this._highlightCorrectOption();
this._changeDetectorRef.markForCheck();
// Required for the MDC form field to pick up when the overlay has been opened.
this.stateChanges.next();
}
/**
* Track which modal we have modified the `aria-owns` attribute of. When the combobox trigger is
* inside an aria-modal, we apply aria-owns to the parent modal with the `id` of the options
* panel. Track the modal we have changed so we can undo the changes on destroy.
*/
private _trackedModal: Element | null = null;
/**
* If the autocomplete trigger is inside of an `aria-modal` element, connect
* that modal to the options panel with `aria-owns`.
*
* For some browser + screen reader combinations, when navigation is inside
* of an `aria-modal` element, the screen reader treats everything outside
* of that modal as hidden or invisible.
*
* This causes a problem when the combobox trigger is _inside_ of a modal, because the
* options panel is rendered _outside_ of that modal, preventing screen reader navigation
* from reaching the panel.
*
* We can work around this issue by applying `aria-owns` to the modal with the `id` of
* the options panel. This effectively communicates to assistive technology that the
* options panel is part of the same interaction as the modal.
*
* At time of this writing, this issue is present in VoiceOver.
* See https://github.com/angular/components/issues/20694
*/
private _applyModalPanelOwnership() {
// TODO(http://github.com/angular/components/issues/26853): consider de-duplicating this with
// the `LiveAnnouncer` and any other usages.
//
// Note that the selector here is limited to CDK overlays at the moment in order to reduce the
// section of the DOM we need to look through. This should cover all the cases we support, but
// the selector can be expanded if it turns out to be too narrow.
const modal = this._elementRef.nativeElement.closest(
'body > .cdk-overlay-container [aria-modal="true"]',
);
if (!modal) {
// Most commonly, the autocomplete trigger is not inside a modal.
return;
}
const panelId = `${this.id}-panel`;
if (this._trackedModal) {
removeAriaReferencedId(this._trackedModal, 'aria-owns', panelId);
}
addAriaReferencedId(modal, 'aria-owns', panelId);
this._trackedModal = modal;
}
/** Clears the reference to the listbox overlay element from the modal it was added to. */
private _clearFromModal() {
if (!this._trackedModal) {
// Most commonly, the autocomplete trigger is not used inside a modal.
return;
}
const panelId = `${this.id}-panel`;
removeAriaReferencedId(this._trackedModal, 'aria-owns', panelId);
this._trackedModal = null;
}
/** Closes the overlay panel and focuses the host element. */
close(): void {
if (this._panelOpen) {
this._panelOpen = false;
this._keyManager.withHorizontalOrientation(this._isRtl() ? 'rtl' : 'ltr');
this._changeDetectorRef.markForCheck();
this._onTouched();
// Required for the MDC form field to pick up when the overlay has been closed.
this.stateChanges.next();
}
}
/**
* Sets the select's value. Part of the ControlValueAccessor interface
* required to integrate with Angular's core forms API.
*
* @param value New value to be written to the model.
*/
writeValue(value: any): void {
this._assignValue(value);
}
/**
* Saves a callback function to be invoked when the select's value
* changes from user input. Part of the ControlValueAccessor interface
* required to integrate with Angular's core forms API.
*
* @param fn Callback to be triggered when the value changes.
*/
registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}
/**
* Saves a callback function to be invoked when the select is blurred
* by the user. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param fn Callback to be triggered when the component has been touched.
*/
registerOnTouched(fn: () => {}): void {
this._onTouched = fn;
}
/**
* Disables the select. Part of the ControlValueAccessor interface required
* to integrate with Angular's core forms API.
*
* @param isDisabled Sets whether the component is disabled.
*/
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
this._changeDetectorRef.markForCheck();
this.stateChanges.next();
}
/** Whether or not the overlay panel is open. */
get panelOpen(): boolean {
return this._panelOpen;
}
/** The currently selected option. */
get selected(): MatOption | MatOption[] {
return this.multiple ? this._selectionModel?.selected || [] : this._selectionModel?.selected[0];
}
/** The value displayed in the trigger. */
get triggerValue(): string {
if (this.empty) {
return '';
}
if (this._multiple) {
const selectedOptions = this._selectionModel.selected.map(option => option.viewValue);
if (this._isRtl()) {
selectedOptions.reverse();
}
// TODO(crisbeto): delimiter should be configurable for proper localization.
return selectedOptions.join(', ');
}
return this._selectionModel.selected[0].viewValue;
}
/** Refreshes the error state of the select. */
updateErrorState() {
this._errorStateTracker.updateErrorState();
}
/** Whether the element is in RTL mode. */
_isRtl(): boolean {
return this._dir ? this._dir.value === 'rtl' : false;
}
/** Handles all keydown events on the select. */
_handleKeydown(event: KeyboardEvent): void {
if (!this.disabled) {
this.panelOpen ? this._handleOpenKeydown(event) : this._handleClosedKeydown(event);
}
}
/** Handles keyboard events while the select is closed. */
private _handleClosedKeydown(event: KeyboardEvent): void {
const keyCode = event.keyCode;
const isArrowKey =
keyCode === DOWN_ARROW ||
keyCode === UP_ARROW ||
keyCode === LEFT_ARROW ||
keyCode === RIGHT_ARROW;
const isOpenKey = keyCode === ENTER || keyCode === SPACE;
const manager = this._keyManager;
// Open the select on ALT + arrow key to match the native <select>
if (
(!manager.isTyping() && isOpenKey && !hasModifierKey(event)) ||
((this.multiple || event.altKey) && isArrowKey)
) {
event.preventDefault(); // prevents the page from scrolling down when pressing space
this.open();
} else if (!this.multiple) {
const previouslySelectedOption = this.selected;
manager.onKeydown(event);
const selectedOption = this.selected;
// Since the value has changed, we need to announce it ourselves.
if (selectedOption && previouslySelectedOption !== selectedOption) {
// We set a duration on the live announcement, because we want the live element to be
// cleared after a while so that users can't navigate to it using the arrow keys.
this._liveAnnouncer.announce((selectedOption as MatOption).viewValue, 10000);
}
}
}
/** Handles keyboard events when the selected is open. */ | {
"end_byte": 31125,
"start_byte": 22855,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.ts"
} |
components/src/material/select/select.ts_31128_38779 | private _handleOpenKeydown(event: KeyboardEvent): void {
const manager = this._keyManager;
const keyCode = event.keyCode;
const isArrowKey = keyCode === DOWN_ARROW || keyCode === UP_ARROW;
const isTyping = manager.isTyping();
if (isArrowKey && event.altKey) {
// Close the select on ALT + arrow key to match the native <select>
event.preventDefault();
this.close();
// Don't do anything in this case if the user is typing,
// because the typing sequence can include the space key.
} else if (
!isTyping &&
(keyCode === ENTER || keyCode === SPACE) &&
manager.activeItem &&
!hasModifierKey(event)
) {
event.preventDefault();
manager.activeItem._selectViaInteraction();
} else if (!isTyping && this._multiple && keyCode === A && event.ctrlKey) {
event.preventDefault();
const hasDeselectedOptions = this.options.some(opt => !opt.disabled && !opt.selected);
this.options.forEach(option => {
if (!option.disabled) {
hasDeselectedOptions ? option.select() : option.deselect();
}
});
} else {
const previouslyFocusedIndex = manager.activeItemIndex;
manager.onKeydown(event);
if (
this._multiple &&
isArrowKey &&
event.shiftKey &&
manager.activeItem &&
manager.activeItemIndex !== previouslyFocusedIndex
) {
manager.activeItem._selectViaInteraction();
}
}
}
_onFocus() {
if (!this.disabled) {
this._focused = true;
this.stateChanges.next();
}
}
/**
* Calls the touched callback only if the panel is closed. Otherwise, the trigger will
* "blur" to the panel when it opens, causing a false positive.
*/
_onBlur() {
this._focused = false;
this._keyManager?.cancelTypeahead();
if (!this.disabled && !this.panelOpen) {
this._onTouched();
this._changeDetectorRef.markForCheck();
this.stateChanges.next();
}
}
/**
* Callback that is invoked when the overlay panel has been attached.
*/
_onAttached(): void {
this._overlayDir.positionChange.pipe(take(1)).subscribe(() => {
this._changeDetectorRef.detectChanges();
this._positioningSettled();
});
}
/** Returns the theme to be used on the panel. */
_getPanelTheme(): string {
return this._parentFormField ? `mat-${this._parentFormField.color}` : '';
}
/** Whether the select has a value. */
get empty(): boolean {
return !this._selectionModel || this._selectionModel.isEmpty();
}
private _initializeSelection(): void {
// Defer setting the value in order to avoid the "Expression
// has changed after it was checked" errors from Angular.
Promise.resolve().then(() => {
if (this.ngControl) {
this._value = this.ngControl.value;
}
this._setSelectionByValue(this._value);
this.stateChanges.next();
});
}
/**
* Sets the selected option based on a value. If no option can be
* found with the designated value, the select trigger is cleared.
*/
private _setSelectionByValue(value: any | any[]): void {
this.options.forEach(option => option.setInactiveStyles());
this._selectionModel.clear();
if (this.multiple && value) {
if (!Array.isArray(value) && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw getMatSelectNonArrayValueError();
}
value.forEach((currentValue: any) => this._selectOptionByValue(currentValue));
this._sortValues();
} else {
const correspondingOption = this._selectOptionByValue(value);
// Shift focus to the active item. Note that we shouldn't do this in multiple
// mode, because we don't know what option the user interacted with last.
if (correspondingOption) {
this._keyManager.updateActiveItem(correspondingOption);
} else if (!this.panelOpen) {
// Otherwise reset the highlighted option. Note that we only want to do this while
// closed, because doing it while open can shift the user's focus unnecessarily.
this._keyManager.updateActiveItem(-1);
}
}
this._changeDetectorRef.markForCheck();
}
/**
* Finds and selects and option based on its value.
* @returns Option that has the corresponding value.
*/
private _selectOptionByValue(value: any): MatOption | undefined {
const correspondingOption = this.options.find((option: MatOption) => {
// Skip options that are already in the model. This allows us to handle cases
// where the same primitive value is selected multiple times.
if (this._selectionModel.isSelected(option)) {
return false;
}
try {
// Treat null as a special reset value.
return option.value != null && this._compareWith(option.value, value);
} catch (error) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
// Notify developers of errors in their comparator.
console.warn(error);
}
return false;
}
});
if (correspondingOption) {
this._selectionModel.select(correspondingOption);
}
return correspondingOption;
}
/** Assigns a specific value to the select. Returns whether the value has changed. */
private _assignValue(newValue: any | any[]): boolean {
// Always re-assign an array, because it might have been mutated.
if (newValue !== this._value || (this._multiple && Array.isArray(newValue))) {
if (this.options) {
this._setSelectionByValue(newValue);
}
this._value = newValue;
return true;
}
return false;
}
// `skipPredicate` determines if key manager should avoid putting a given option in the tab
// order. Allow disabled list items to receive focus via keyboard to align with WAI ARIA
// recommendation.
//
// Normally WAI ARIA's instructions are to exclude disabled items from the tab order, but it
// makes a few exceptions for compound widgets.
//
// From [Developing a Keyboard Interface](
// https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/):
// "For the following composite widget elements, keep them focusable when disabled: Options in a
// Listbox..."
//
// The user can focus disabled options using the keyboard, but the user cannot click disabled
// options.
private _skipPredicate = (option: MatOption) => {
if (this.panelOpen) {
// Support keyboard focusing disabled options in an ARIA listbox.
return false;
}
// When the panel is closed, skip over disabled options. Support options via the UP/DOWN arrow
// keys on a closed select. ARIA listbox interaction pattern is less relevant when the panel is
// closed.
return option.disabled;
};
/** Gets how wide the overlay panel should be. */
private _getOverlayWidth(
preferredOrigin: ElementRef<ElementRef> | CdkOverlayOrigin | undefined,
): string | number {
if (this.panelWidth === 'auto') {
const refToMeasure =
preferredOrigin instanceof CdkOverlayOrigin
? preferredOrigin.elementRef
: preferredOrigin || this._elementRef;
return refToMeasure.nativeElement.getBoundingClientRect().width;
}
return this.panelWidth === null ? '' : this.panelWidth;
}
/** Syncs the parent state with the individual options. */
_syncParentProperties(): void {
if (this.options) {
for (const option of this.options) {
option._changeDetectorRef.markForCheck();
}
}
}
/** Sets up a key manager to listen to keyboard events on the overlay panel. */ | {
"end_byte": 38779,
"start_byte": 31128,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.ts"
} |
components/src/material/select/select.ts_38782_46786 | private _initKeyManager() {
this._keyManager = new ActiveDescendantKeyManager<MatOption>(this.options)
.withTypeAhead(this.typeaheadDebounceInterval)
.withVerticalOrientation()
.withHorizontalOrientation(this._isRtl() ? 'rtl' : 'ltr')
.withHomeAndEnd()
.withPageUpDown()
.withAllowedModifierKeys(['shiftKey'])
.skipPredicate(this._skipPredicate);
this._keyManager.tabOut.subscribe(() => {
if (this.panelOpen) {
// Select the active item when tabbing away. This is consistent with how the native
// select behaves. Note that we only want to do this in single selection mode.
if (!this.multiple && this._keyManager.activeItem) {
this._keyManager.activeItem._selectViaInteraction();
}
// Restore focus to the trigger before closing. Ensures that the focus
// position won't be lost if the user got focus into the overlay.
this.focus();
this.close();
}
});
this._keyManager.change.subscribe(() => {
if (this._panelOpen && this.panel) {
this._scrollOptionIntoView(this._keyManager.activeItemIndex || 0);
} else if (!this._panelOpen && !this.multiple && this._keyManager.activeItem) {
this._keyManager.activeItem._selectViaInteraction();
}
});
}
/** Drops current option subscriptions and IDs and resets from scratch. */
private _resetOptions(): void {
const changedOrDestroyed = merge(this.options.changes, this._destroy);
this.optionSelectionChanges.pipe(takeUntil(changedOrDestroyed)).subscribe(event => {
this._onSelect(event.source, event.isUserInput);
if (event.isUserInput && !this.multiple && this._panelOpen) {
this.close();
this.focus();
}
});
// Listen to changes in the internal state of the options and react accordingly.
// Handles cases like the labels of the selected options changing.
merge(...this.options.map(option => option._stateChanges))
.pipe(takeUntil(changedOrDestroyed))
.subscribe(() => {
// `_stateChanges` can fire as a result of a change in the label's DOM value which may
// be the result of an expression changing. We have to use `detectChanges` in order
// to avoid "changed after checked" errors (see #14793).
this._changeDetectorRef.detectChanges();
this.stateChanges.next();
});
}
/** Invoked when an option is clicked. */
private _onSelect(option: MatOption, isUserInput: boolean): void {
const wasSelected = this._selectionModel.isSelected(option);
if (option.value == null && !this._multiple) {
option.deselect();
this._selectionModel.clear();
if (this.value != null) {
this._propagateChanges(option.value);
}
} else {
if (wasSelected !== option.selected) {
option.selected
? this._selectionModel.select(option)
: this._selectionModel.deselect(option);
}
if (isUserInput) {
this._keyManager.setActiveItem(option);
}
if (this.multiple) {
this._sortValues();
if (isUserInput) {
// In case the user selected the option with their mouse, we
// want to restore focus back to the trigger, in order to
// prevent the select keyboard controls from clashing with
// the ones from `mat-option`.
this.focus();
}
}
}
if (wasSelected !== this._selectionModel.isSelected(option)) {
this._propagateChanges();
}
this.stateChanges.next();
}
/** Sorts the selected values in the selected based on their order in the panel. */
private _sortValues() {
if (this.multiple) {
const options = this.options.toArray();
this._selectionModel.sort((a, b) => {
return this.sortComparator
? this.sortComparator(a, b, options)
: options.indexOf(a) - options.indexOf(b);
});
this.stateChanges.next();
}
}
/** Emits change event to set the model value. */
private _propagateChanges(fallbackValue?: any): void {
let valueToEmit: any;
if (this.multiple) {
valueToEmit = (this.selected as MatOption[]).map(option => option.value);
} else {
valueToEmit = this.selected ? (this.selected as MatOption).value : fallbackValue;
}
this._value = valueToEmit;
this.valueChange.emit(valueToEmit);
this._onChange(valueToEmit);
this.selectionChange.emit(this._getChangeEvent(valueToEmit));
this._changeDetectorRef.markForCheck();
}
/**
* Highlights the selected item. If no option is selected, it will highlight
* the first *enabled* option.
*/
private _highlightCorrectOption(): void {
if (this._keyManager) {
if (this.empty) {
// Find the index of the first *enabled* option. Avoid calling `_keyManager.setActiveItem`
// because it activates the first option that passes the skip predicate, rather than the
// first *enabled* option.
let firstEnabledOptionIndex = -1;
for (let index = 0; index < this.options.length; index++) {
const option = this.options.get(index)!;
if (!option.disabled) {
firstEnabledOptionIndex = index;
break;
}
}
this._keyManager.setActiveItem(firstEnabledOptionIndex);
} else {
this._keyManager.setActiveItem(this._selectionModel.selected[0]);
}
}
}
/** Whether the panel is allowed to open. */
protected _canOpen(): boolean {
return !this._panelOpen && !this.disabled && this.options?.length > 0;
}
/** Focuses the select element. */
focus(options?: FocusOptions): void {
this._elementRef.nativeElement.focus(options);
}
/** Gets the aria-labelledby for the select panel. */
_getPanelAriaLabelledby(): string | null {
if (this.ariaLabel) {
return null;
}
const labelId = this._parentFormField?.getLabelId() || null;
const labelExpression = labelId ? labelId + ' ' : '';
return this.ariaLabelledby ? labelExpression + this.ariaLabelledby : labelId;
}
/** Determines the `aria-activedescendant` to be set on the host. */
_getAriaActiveDescendant(): string | null {
if (this.panelOpen && this._keyManager && this._keyManager.activeItem) {
return this._keyManager.activeItem.id;
}
return null;
}
/** Gets the aria-labelledby of the select component trigger. */
private _getTriggerAriaLabelledby(): string | null {
if (this.ariaLabel) {
return null;
}
const labelId = this._parentFormField?.getLabelId();
let value = (labelId ? labelId + ' ' : '') + this._valueId;
if (this.ariaLabelledby) {
value += ' ' + this.ariaLabelledby;
}
return value;
}
/** Called when the overlay panel is done animating. */
protected _panelDoneAnimating(isOpen: boolean) {
this.openedChange.emit(isOpen);
}
/**
* 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() {
this.focus();
this.open();
}
/**
* Implemented as part of MatFormFieldControl.
* @docs-private
*/
get shouldLabelFloat(): boolean {
// Since the panel doesn't overlap the trigger, we
// want the label to only float when there's a value.
return this.panelOpen || !this.empty || (this.focused && !!this.placeholder);
}
}
/**
* Allows the user to customize the trigger that is displayed when the select has a value.
*/
@Directive({
selector: 'mat-select-trigger',
providers: [{provide: MAT_SELECT_TRIGGER, useExisting: MatSelectTrigger}],
})
export class MatSelectTrigger {} | {
"end_byte": 46786,
"start_byte": 38782,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.ts"
} |
components/src/material/select/select.scss_0_7757 | @use 'sass:math';
@use '@angular/cdk';
@use '../core/style/vendor-prefixes';
@use '../core/style/variables';
@use '../core/tokens/token-utils';
@use '../core/tokens/m2/mat/select' as tokens-mat-select;
$mat-select-arrow-size: 5px !default;
$mat-select-arrow-margin: 4px !default;
$mat-select-panel-max-height: 275px !default;
$mat-select-placeholder-arrow-space: 2 *
($mat-select-arrow-size + $mat-select-arrow-margin);
$leading-width: 12px !default;
$scale: 0.75 !default;
.mat-mdc-select {
display: inline-block;
width: 100%;
outline: none;
@include token-utils.use-tokens(
tokens-mat-select.$prefix, tokens-mat-select.get-token-slots()) {
@include vendor-prefixes.smooth-font();
@include token-utils.create-token-slot(color, enabled-trigger-text-color);
@include token-utils.create-token-slot(font-family, trigger-text-font);
@include token-utils.create-token-slot(line-height, trigger-text-line-height);
@include token-utils.create-token-slot(font-size, trigger-text-size);
@include token-utils.create-token-slot(font-weight, trigger-text-weight);
@include token-utils.create-token-slot(letter-spacing, trigger-text-tracking);
}
}
@include token-utils.use-tokens(tokens-mat-select.$prefix, tokens-mat-select.get-token-slots()) {
div.mat-mdc-select-panel {
@include token-utils.create-token-slot(box-shadow, container-elevation-shadow);
}
}
.mat-mdc-select-disabled {
@include token-utils.use-tokens(
tokens-mat-select.$prefix, tokens-mat-select.get-token-slots()) {
@include token-utils.create-token-slot(color, disabled-trigger-text-color);
}
}
.mat-mdc-select-trigger {
display: inline-flex;
align-items: center;
cursor: pointer;
position: relative;
box-sizing: border-box;
width: 100%;
.mat-mdc-select-disabled & {
@include vendor-prefixes.user-select(none);
cursor: default;
}
}
.mat-mdc-select-value {
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mat-mdc-select-value-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.mat-mdc-select-arrow-wrapper {
height: 24px;
flex-shrink: 0;
display: inline-flex;
align-items: center;
.mat-form-field-appearance-fill .mdc-text-field--no-label & {
transform: none;
}
}
.mat-mdc-form-field .mat-mdc-select.mat-mdc-select-invalid .mat-mdc-select-arrow,
.mat-form-field-invalid:not(.mat-form-field-disabled) .mat-mdc-form-field-infix::after {
@include token-utils.use-tokens(tokens-mat-select.$prefix, tokens-mat-select.get-token-slots()) {
@include token-utils.create-token-slot(color, invalid-arrow-color);
}
}
.mat-mdc-select-arrow {
width: $mat-select-arrow-size * 2;
height: $mat-select-arrow-size;
position: relative;
@include token-utils.use-tokens(
tokens-mat-select.$prefix, tokens-mat-select.get-token-slots()) {
@include token-utils.create-token-slot(color, enabled-arrow-color);
.mat-mdc-form-field.mat-focused & {
@include token-utils.create-token-slot(color, focused-arrow-color);
}
.mat-mdc-form-field .mat-mdc-select.mat-mdc-select-disabled & {
@include token-utils.create-token-slot(color, disabled-arrow-color);
}
}
svg {
fill: currentColor;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
@include cdk.high-contrast {
// On Chromium browsers the `currentColor` blends in with the
// background for SVGs so we have to fall back to `CanvasText`.
fill: CanvasText;
.mat-mdc-select-disabled & {
fill: GrayText;
}
}
}
}
// Even though we don't use the MDC styles, we need to keep the classes in the
// DOM for the Gmat versions to work. We need to bump up the specificity here
// so that it's higher than MDC's styles.
div.mat-mdc-select-panel {
width: 100%; // Ensures that the panel matches the overlay width.
max-height: $mat-select-panel-max-height;
outline: 0;
overflow: auto;
padding: 8px 0;
border-radius: 4px;
box-sizing: border-box;
// Workaround in case other MDC menu surface styles bleed in.
position: static;
@include token-utils.use-tokens(
tokens-mat-select.$prefix, tokens-mat-select.get-token-slots()) {
@include token-utils.create-token-slot(background-color, panel-background-color);
}
@include cdk.high-contrast {
outline: solid 1px;
}
.cdk-overlay-pane:not(.mat-mdc-select-panel-above) & {
border-top-left-radius: 0;
border-top-right-radius: 0;
transform-origin: top center;
}
.mat-mdc-select-panel-above & {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
transform-origin: bottom center;
}
.mat-mdc-option {
--mdc-list-list-item-container-color: var(--mat-select-panel-background-color);
}
}
.mat-mdc-select-placeholder {
// Delay the transition until the label has animated about a third of the way through, in
// order to prevent the placeholder from overlapping for a split second.
transition: color variables.$swift-ease-out-duration
math.div(variables.$swift-ease-out-duration, 3)
variables.$swift-ease-out-timing-function;
@include token-utils.use-tokens(
tokens-mat-select.$prefix, tokens-mat-select.get-token-slots()) {
@include token-utils.create-token-slot(color, placeholder-text-color);
}
._mat-animation-noopable & {
transition: none;
}
.mat-form-field-hide-placeholder & {
color: transparent;
// Overwrite browser specific CSS properties that can overwrite the `color` property.
// Some developers seem to use this approach to easily overwrite the placeholder / label color.
-webkit-text-fill-color: transparent;
// Remove the transition to prevent the placeholder
// from overlapping when the label comes back down.
transition: none;
// Prevents the '...' from showing on the parent element.
display: block;
}
}
// Our MDC form field implementation is based on the MDC text field which doesn't include styles
// for select. The select specific styles are not present as they don't use their text field as a
// container. Below are the styles to account for the select arrow icon at the end.
.mat-mdc-form-field-type-mat-select {
&:not(.mat-form-field-disabled) .mat-mdc-text-field-wrapper {
cursor: pointer;
}
&.mat-form-field-appearance-fill {
.mat-mdc-floating-label {
max-width: calc(100% - #{$mat-select-placeholder-arrow-space});
}
.mdc-floating-label--float-above {
$arrow-scale: math.div($mat-select-placeholder-arrow-space, $scale);
max-width: calc(100% / #{$scale} - #{$arrow-scale});
}
}
&.mat-form-field-appearance-outline {
.mdc-notched-outline__notch {
max-width: calc(100% - #{2 * ($mat-select-placeholder-arrow-space + $leading-width)});
}
.mdc-text-field--label-floating .mdc-notched-outline__notch {
max-width: calc(100% - #{$leading-width * 2});
}
}
}
// Used to prevent inline elements from collapsing if their text bindings
// become empty. This is preferrable to inserting a blank space, because the
// space can be read out by screen readers (see #21725).
.mat-mdc-select-min-line:empty::before {
content: ' ';
white-space: pre;
width: 1px;
display: inline-block;
// Prevents some browsers from rendering the element in high contrast mode. Use `visibility`
// instead of `opacity` since VoiceOver + Chrome still reads out the space with the latter.
visibility: hidden;
}
@include token-utils.use-tokens(tokens-mat-select.$prefix, tokens-mat-select.get-token-slots()) {
.mat-form-field-appearance-fill .mat-mdc-select-arrow-wrapper {
@include token-utils.create-token-slot(transform, arrow-transform);
}
}
| {
"end_byte": 7757,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.scss"
} |
components/src/material/select/module.ts_0_922 | /**
* @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 {OverlayModule} from '@angular/cdk/overlay';
import {NgModule} from '@angular/core';
import {MatCommonModule, MatOptionModule} from '@angular/material/core';
import {MatFormFieldModule} from '@angular/material/form-field';
import {CdkScrollableModule} from '@angular/cdk/scrolling';
import {MatSelect, MatSelectTrigger, MAT_SELECT_SCROLL_STRATEGY_PROVIDER} from './select';
@NgModule({
imports: [OverlayModule, MatOptionModule, MatCommonModule, MatSelect, MatSelectTrigger],
exports: [
CdkScrollableModule,
MatFormFieldModule,
MatSelect,
MatSelectTrigger,
MatOptionModule,
MatCommonModule,
],
providers: [MAT_SELECT_SCROLL_STRATEGY_PROVIDER],
})
export class MatSelectModule {}
| {
"end_byte": 922,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/module.ts"
} |
components/src/material/select/public-api.ts_0_631 | /**
* @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 './module';
export * from './select';
export * from './select-animations';
// Re-export these since they're required to be used together with `mat-select`.
// Also they used to be provided implicitly with `MatSelectModule`.
export {MatOption, MatOptgroup} from '@angular/material/core';
export {
MatFormField,
MatLabel,
MatHint,
MatError,
MatPrefix,
MatSuffix,
} from '@angular/material/form-field';
| {
"end_byte": 631,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/public-api.ts"
} |
components/src/material/select/select.md_0_8873 | `<mat-select>` is a form control for selecting a value from a set of options, similar to the native
`<select>` element. You can read more about selects in the
[Material Design spec](https://material.io/design/components/menus.html). It is designed to work
inside of a [`<mat-form-field>`](https://material.angular.io/components/form-field/overview)
element.
To add options to the select, add `<mat-option>` elements to the `<mat-select>`. Each `<mat-option>`
has a `value` property that can be used to set the value that will be selected if the user chooses
this option. The content of the `<mat-option>` is what will be shown to the user.
Angular Material also supports use of the native `<select>` element inside of
`<mat-form-field>`. The native control has several performance, accessibility,
and usability advantages. See [the documentation for
form-field](https://material.angular.io/components/form-field) for more information.
To use a native select inside `<mat-form-field>`, import `MatInputModule` and add the
`matNativeControl` attribute to the `<select>` element.
<!-- example(select-overview) -->
### Getting and setting the select value
The `<mat-select>` supports 2-way binding to the `value` property without the need for Angular
forms.
<!-- example(select-value-binding) -->
Both`<mat-select>` and `<select>` support all of the form directives from the core `FormsModule` (`NgModel`) and
`ReactiveFormsModule` (`FormControl`, `FormGroup`, etc.) As with native `<select>`, `<mat-select>`
also supports a `compareWith` function. (Additional information about using a custom `compareWith`
function can be found in the
[Angular forms documentation](https://angular.dev/api/forms/SelectControlValueAccessor#compareWith)).
<!-- example(select-form) -->
### Form field features
There are a number of `<mat-form-field>` features that can be used with both `<select>` and `<mat-select>`. These
include error messages, hint text, prefix & suffix, and theming. For additional information about
these features, see the
[form field documentation](https://material.angular.io/components/form-field/overview).
<!-- example(select-hint-error) -->
### Setting a static placeholder
The placeholder is text shown when the `<mat-form-field>` label is floating but the `<mat-select>`
is empty. It is used to give the user an additional hint about the value they should select. The
placeholder can be specified by setting the `placeholder` attribute on the `<mat-select>` element.
In some cases that `<mat-form-field>` may use the placeholder as the label (see the
[form field label documentation](https://material.angular.io/components/form-field/overview#floating-label)).
### Disabling the select or individual options
It is possible to disable the entire select or individual options in the select by using the
disabled property on the `<select>` or `<mat-select>` and the `<option>` or `<mat-option>` elements respectively.
When working with Reactive Forms, the select component can be disabled/enabled via form controls.
This can be accomplished by creating a `FormControl` with the disabled property
`FormControl({value: '', disabled: true})` or using `FormControl.enable()`, `FormControl.disable()`.
<!-- example(select-disabled) -->
### Resetting the select value
If you want one of your options to reset the select's value, you can omit specifying its value.
<!-- example(select-reset) -->
### Creating groups of options
The `<mat-optgroup>` element can be used to group common options under a subheading. The name of the
group can be set using the `label` property of `<mat-optgroup>`. Like individual `<mat-option>`
elements, an entire `<mat-optgroup>` can be disabled or enabled by setting the `disabled` property
on the group.
<!-- example(select-optgroup) -->
### Multiple selection
`<mat-select>` defaults to single-selection mode, but can be configured to allow multiple selection
by setting the `multiple` property. This will allow the user to select multiple values at once. When
using the `<mat-select>` in multiple selection mode, its value will be a sorted list of all selected
values rather than a single value.
Using multiple selection with a native select element (`<select multiple>`) is discouraged
inside `<mat-form-field>`, as the inline listbox appearance is inconsistent with other
Material Design components.
<!-- example(select-multiple) -->
### Customizing the trigger label
If you want to display a custom trigger label inside a `<mat-select>`, you can use the
`<mat-select-trigger>` element.
<!-- example(select-custom-trigger) -->
### Disabling the ripple effect
By default, when a user clicks on a `<mat-option>`, a ripple animation is shown. This can be disabled
by setting the `disableRipple` property on `<mat-select>`.
<!-- example(select-no-ripple) -->
### Adding custom styles to the dropdown panel
In order to facilitate easily styling the dropdown panel, `<mat-select>` has a `panelClass` property
which can be used to apply additional CSS classes to the dropdown panel.
<!-- example(select-panel-class) -->
### Changing when error messages are shown
The `<mat-form-field>` allows you to
[associate error messages](https://material.angular.io/components/form-field/overview#error-messages)
with your `<select>` or `<mat-select>`. By default, these error messages are shown when the control is invalid and
either the user has interacted with (touched) the element or the parent form has been submitted. If
you wish to override this behavior (e.g. to show the error as soon as the invalid control is dirty
or when a parent form group is invalid), you can use the `errorStateMatcher` property of the
`<mat-select>`. The property takes an instance of an `ErrorStateMatcher` object. An
`ErrorStateMatcher` must implement a single method `isErrorState` which takes the `FormControl` for
this `<mat-select>` as well as the parent form and returns a boolean indicating whether errors
should be shown. (`true` indicating that they should be shown, and `false` indicating that they
should not.)
<!-- example(select-error-state-matcher) -->
A global error state matcher can be specified by setting the `ErrorStateMatcher` provider. This
applies to all inputs. For convenience, `ShowOnDirtyErrorStateMatcher` is available in order to
globally cause input errors to show when the input is dirty and invalid.
```ts
@NgModule({
providers: [
{provide: ErrorStateMatcher, useClass: ShowOnDirtyErrorStateMatcher}
]
})
```
### Keyboard interaction
| Keyboard shortcut | Action |
|----------------------------------------|-----------------------------------------------------------------------|
| <kbd>Down Arrow</kbd> | Navigate to the next option. |
| <kbd>Up Arrow</kbd> | Navigate to the previous option. |
| <kbd>Enter</kbd> | If closed, open the select panel. If open, selects the active option. |
| <kbd>Escape</kbd> | Close the select panel. |
| <kbd>Alt</kbd> + <kbd>Up Arrow</kbd> | Close the select panel. |
| <kbd>Alt</kbd> + <kbd>Down Arrow</kbd> | Open the select panel if there are any matching options. |
### Accessibility
When possible, prefer a native `<select>` element over `MatSelect`. The native control
provides the most accessible experience across the widest range of platforms.
`MatSelect` implements the combobox pattern detailed in the [1.2 version of the ARIA
specification](https://www.w3.org/TR/wai-aria-1.2). The combobox trigger controls a `role="listbox"`
element opened in a pop-up. Previous versions of the ARIA specification
required that `role="combobox"` apply to a text input control, but the 1.2 version of the
specification supports a wider variety of interaction patterns. This newer usage of ARIA works
in all browser and screen-reader combinations supported by Angular Material.
Because the pop-up uses the `role="listbox"` pattern, you should _not_ put other interactive
controls, such as buttons or checkboxes, inside a select option. Nesting interactive controls like
this interferes with most assistive technology.
Always provide an accessible label for the select. This can be done by adding a `<mat-label>`
inside of `<mat-form-field>`, the `aria-label` attribute, or the `aria-labelledby` attribute.
By default, `MatSelect` displays a checkmark to identify selected items. While you can hide the
checkmark indicator for single-selection via `hideSingleSelectionIndicator`, this makes the
component less accessible by making it harder or impossible for users to visually identify selected
items.
| {
"end_byte": 8873,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.md"
} |
components/src/material/select/select.md_8873_10026 | ### Troubleshooting
#### Error: Cannot change `multiple` mode of select after initialization
This error is thrown if you attempt to bind the `multiple` property on `<mat-select>` to a dynamic
value. (e.g. `[multiple]="isMultiple"` where the value of `isMultiple` changes over the course of
the component's lifetime). If you need to change this dynamically, use `@if` or `@switch` instead:
```html
@if (isMultiple) {
<mat-select multiple>
...
</mat-select>
} @else {
<mat-select>
...
</mat-select>
}
```
#### Error: Value must be an array in multiple-selection mode
This error is thrown if you attempt to assign a value other than `null`, `undefined`, or an array to
a `<mat-select multiple>`. For example, something like `mySelect.value = 'option1'`. What you likely
meant to do was `mySelect.value = ['option1']`.
#### Error: `compareWith` must be a function
This error occurs if you attempt to assign something other than a function to the `compareWith`
property. For more information on proper usage of `compareWith` see the
[Angular forms documentation](https://angular.dev/api/forms/SelectControlValueAccessor#compareWith)).
| {
"end_byte": 10026,
"start_byte": 8873,
"url": "https://github.com/angular/components/blob/main/src/material/select/select.md"
} |
components/src/material/select/README.md_0_97 | Please see the official documentation at https://material.angular.io/components/component/select
| {
"end_byte": 97,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/README.md"
} |
components/src/material/select/select-errors.ts_0_1350 | /**
* @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
*/
// Note that these have been copied over verbatim from
// `material/select` so that we don't have to expose them publicly.
/**
* Returns an exception to be thrown when attempting to change a select's `multiple` option
* after initialization.
* @docs-private
*/
export function getMatSelectDynamicMultipleError(): Error {
return Error('Cannot change `multiple` mode of select after initialization.');
}
/**
* Returns an exception to be thrown when attempting to assign a non-array value to a select
* in `multiple` mode. Note that `undefined` and `null` are still valid values to allow for
* resetting the value.
* @docs-private
*/
export function getMatSelectNonArrayValueError(): Error {
return Error('Value must be an array in multiple-selection mode.');
}
/**
* Returns an exception to be thrown when assigning a non-function value to the comparator
* used to determine if a value corresponds to an option. Note that whether the function
* actually takes two values and returns a boolean is not checked.
*/
export function getMatSelectNonFunctionValueError(): Error {
return Error('`compareWith` must be a function.');
}
| {
"end_byte": 1350,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/select-errors.ts"
} |
components/src/material/select/BUILD.bazel_0_1975 | 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 = "select",
srcs = glob(
["**/*.ts"],
exclude = [
"**/*.spec.ts",
],
),
assets = [":select_scss"] + glob(["**/*.html"]),
deps = [
"//src:dev_mode_types",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/collections",
"//src/cdk/keycodes",
"//src/cdk/overlay",
"//src/cdk/scrolling",
"//src/material/core",
"//src/material/form-field",
"@npm//@angular/animations",
"@npm//@angular/common",
"@npm//@angular/core",
"@npm//@angular/forms",
"@npm//rxjs",
],
)
sass_library(
name = "select_scss_lib",
srcs = glob(["**/_*.scss"]),
deps = [
"//src/material/core:core_scss_lib",
],
)
sass_binary(
name = "select_scss",
src = "select.scss",
deps = [
"//src/cdk:sass_lib",
"//src/material:sass_lib",
],
)
ng_test_library(
name = "select_tests_lib",
srcs = glob(
["**/*.spec.ts"],
),
deps = [
":select",
"//src/cdk/a11y",
"//src/cdk/bidi",
"//src/cdk/keycodes",
"//src/cdk/overlay",
"//src/cdk/scrolling",
"//src/cdk/testing/private",
"//src/material/core",
"//src/material/form-field",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
"@npm//rxjs",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":select_tests_lib",
],
)
markdown_to_html(
name = "overview",
srcs = [":select.md"],
)
extract_tokens(
name = "tokens",
srcs = [":select_scss_lib"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
| {
"end_byte": 1975,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/BUILD.bazel"
} |
components/src/material/select/select-animations.ts_0_1739 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
animate,
animateChild,
AnimationTriggerMetadata,
query,
state,
style,
transition,
trigger,
} from '@angular/animations';
/**
* The following are all the animations for the mat-select component, with each
* const containing the metadata for one animation.
*
* The values below match the implementation of the AngularJS Material mat-select animation.
* @docs-private
*/
export const matSelectAnimations: {
/**
* @deprecated No longer being used. To be removed.
* @breaking-change 12.0.0
*/
readonly transformPanelWrap: AnimationTriggerMetadata;
readonly transformPanel: AnimationTriggerMetadata;
} = {
/**
* This animation ensures the select's overlay panel animation (transformPanel) is called when
* closing the select.
* This is needed due to https://github.com/angular/angular/issues/23302
*/
transformPanelWrap: trigger('transformPanelWrap', [
transition('* => void', query('@transformPanel', [animateChild()], {optional: true})),
]),
/** This animation transforms the select's overlay panel on and off the page. */
transformPanel: trigger('transformPanel', [
state(
'void',
style({
opacity: 0,
transform: 'scale(1, 0.8)',
}),
),
transition(
'void => showing',
animate(
'120ms cubic-bezier(0, 0, 0.2, 1)',
style({
opacity: 1,
transform: 'scale(1, 1)',
}),
),
),
transition('* => void', animate('100ms linear', style({opacity: 0}))),
]),
};
| {
"end_byte": 1739,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/select-animations.ts"
} |
components/src/material/select/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/select/index.ts"
} |
components/src/material/select/_select-theme.scss_0_4865 | @use '../core/tokens/m2/mat/select' as tokens-mat-select;
@use '../core/tokens/token-utils';
@use '../core/style/sass-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-select.
/// @param {Map} $theme The theme to generate base styles for.
@mixin base($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, base));
} @else {
@include sass-utils.current-selector-or-root() {
$mat-tokens: tokens-mat-select.get-unthemable-tokens();
@include token-utils.create-token-values(tokens-mat-select.$prefix, $mat-tokens);
}
}
}
/// Outputs color theme styles for the mat-select.
/// @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 select arrow: primary, secondary, tertiary,
/// or error (If not specified, default primary color will be used).
@mixin color($theme, $options...) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color), $options...);
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-select.$prefix,
tokens-mat-select.get-color-tokens($theme)
);
.mat-mdc-form-field.mat-accent {
@include token-utils.create-token-values(
tokens-mat-select.$prefix,
tokens-mat-select.get-color-tokens($theme, accent)
);
}
.mat-mdc-form-field.mat-warn {
@include token-utils.create-token-values(
tokens-mat-select.$prefix,
tokens-mat-select.get-color-tokens($theme, warn)
);
}
}
}
}
/// Outputs typography theme styles for the mat-select.
/// @param {Map} $theme The theme to generate typography styles for.
@mixin typography($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, typography));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-select.$prefix,
tokens-mat-select.get-typography-tokens($theme)
);
}
}
}
/// Outputs typography theme styles for the mat-select.
/// @param {Map} $theme The theme to generate density styles for.
@mixin density($theme) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, density));
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-select.$prefix,
tokens-mat-select.get-density-tokens($theme)
);
}
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-select.$prefix,
tokens: tokens-mat-select.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-icon.
/// @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 select arrow: primary, secondary, tertiary,
/// or error (If not specified, default primary color will be used).
@mixin theme($theme, $options...) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-select') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...);
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens, $options...) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
$mat-select-tokens: token-utils.get-tokens-for($tokens, tokens-mat-select.$prefix, $options...);
@include token-utils.create-token-values(tokens-mat-select.$prefix, $mat-select-tokens);
}
| {
"end_byte": 4865,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/_select-theme.scss"
} |
components/src/material/select/testing/select-harness.spec.ts_0_9135 | import {Component, signal} from '@angular/core';
import {ComponentFixture, inject, TestBed} from '@angular/core/testing';
import {OverlayContainer} from '@angular/cdk/overlay';
import {HarnessLoader, parallel} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {FormControl, ReactiveFormsModule, Validators} from '@angular/forms';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatSelectModule} from '@angular/material/select';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatSelectHarness} from './select-harness';
describe('MatSelectHarness', () => {
let fixture: ComponentFixture<SelectHarnessTest>;
let loader: HarnessLoader;
let overlayContainer: OverlayContainer;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
MatSelectModule,
MatFormFieldModule,
NoopAnimationsModule,
ReactiveFormsModule,
SelectHarnessTest,
],
});
fixture = TestBed.createComponent(SelectHarnessTest);
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
inject([OverlayContainer], (oc: OverlayContainer) => {
overlayContainer = oc;
})();
});
afterEach(() => {
// Angular won't call this for us so we need to do it ourselves to avoid leaks.
overlayContainer.ngOnDestroy();
overlayContainer = null!;
});
it('should load all select harnesses', async () => {
const selects = await loader.getAllHarnesses(MatSelectHarness);
expect(selects.length).toBe(4);
});
it('should filter by whether a select is disabled', async () => {
let enabledSelects = await loader.getAllHarnesses(MatSelectHarness.with({disabled: false}));
let disabledSelects = await loader.getAllHarnesses(MatSelectHarness.with({disabled: true}));
expect(enabledSelects.length).toBe(4);
expect(disabledSelects.length).toBe(0);
fixture.componentInstance.isDisabled.set(true);
fixture.detectChanges();
enabledSelects = await loader.getAllHarnesses(MatSelectHarness.with({disabled: false}));
disabledSelects = await loader.getAllHarnesses(MatSelectHarness.with({disabled: true}));
expect(enabledSelects.length).toBe(3);
expect(disabledSelects.length).toBe(1);
});
it('should be able to check whether a select is in multi-selection mode', async () => {
const singleSelection = await loader.getHarness(
MatSelectHarness.with({
selector: '#single-selection',
}),
);
const multipleSelection = await loader.getHarness(
MatSelectHarness.with({selector: '#multiple-selection'}),
);
expect(await singleSelection.isMultiple()).toBe(false);
expect(await multipleSelection.isMultiple()).toBe(true);
});
it('should get disabled state', async () => {
const singleSelection = await loader.getHarness(
MatSelectHarness.with({
selector: '#single-selection',
}),
);
const multipleSelection = await loader.getHarness(
MatSelectHarness.with({selector: '#multiple-selection'}),
);
expect(await singleSelection.isDisabled()).toBe(false);
expect(await multipleSelection.isDisabled()).toBe(false);
fixture.componentInstance.isDisabled.set(true);
fixture.detectChanges();
expect(await singleSelection.isDisabled()).toBe(true);
expect(await multipleSelection.isDisabled()).toBe(false);
});
it('should get required state', async () => {
const singleSelection = await loader.getHarness(
MatSelectHarness.with({
selector: '#single-selection',
}),
);
const multipleSelection = await loader.getHarness(
MatSelectHarness.with({selector: '#multiple-selection'}),
);
expect(await singleSelection.isRequired()).toBe(false);
expect(await multipleSelection.isRequired()).toBe(false);
fixture.componentInstance.isRequired.set(true);
fixture.detectChanges();
expect(await singleSelection.isRequired()).toBe(true);
expect(await multipleSelection.isRequired()).toBe(false);
});
it('should get valid state', async () => {
const singleSelection = await loader.getHarness(
MatSelectHarness.with({
selector: '#single-selection',
}),
);
const withFormControl = await loader.getHarness(
MatSelectHarness.with({
selector: '#with-form-control',
}),
);
expect(await singleSelection.isValid()).toBe(true);
expect(await withFormControl.isValid()).toBe(false);
});
it('should focus and blur a select', async () => {
const select = await loader.getHarness(MatSelectHarness.with({selector: '#single-selection'}));
expect(await select.isFocused()).toBe(false);
await select.focus();
expect(await select.isFocused()).toBe(true);
await select.blur();
expect(await select.isFocused()).toBe(false);
});
it('should be able to open and close a single-selection select', async () => {
const select = await loader.getHarness(MatSelectHarness.with({selector: '#single-selection'}));
expect(await select.isOpen()).toBe(false);
await select.open();
expect(await select.isOpen()).toBe(true);
await select.close();
expect(await select.isOpen()).toBe(false);
});
it('should be able to open and close a multi-selection select', async () => {
const select = await loader.getHarness(
MatSelectHarness.with({selector: '#multiple-selection'}),
);
expect(await select.isOpen()).toBe(false);
await select.open();
expect(await select.isOpen()).toBe(true);
await select.close();
expect(await select.isOpen()).toBe(false);
});
it('should be able to get the select options', async () => {
const select = await loader.getHarness(MatSelectHarness.with({selector: '#single-selection'}));
await select.open();
const options = await select.getOptions();
expect(options.length).toBe(11);
expect(await options[5].getText()).toBe('New York');
});
it('should be able to get the select panel groups', async () => {
const select = await loader.getHarness(MatSelectHarness.with({selector: '#grouped'}));
await select.open();
const groups = await select.getOptionGroups();
const options = await select.getOptions();
expect(groups.length).toBe(3);
expect(options.length).toBe(14);
});
it('should be able to get the select options when there are multiple open selects', async () => {
const singleSelect = await loader.getHarness(
MatSelectHarness.with({
selector: '#single-selection',
}),
);
await singleSelect.open();
const groupedSelect = await loader.getHarness(MatSelectHarness.with({selector: '#grouped'}));
await groupedSelect.open();
const [singleOptions, groupedOptions] = await parallel(() => [
singleSelect.getOptions(),
groupedSelect.getOptions(),
]);
expect(await singleOptions[0].getText()).toBe('Alabama');
expect(singleOptions.length).toBe(11);
expect(await groupedOptions[0].getText()).toBe('Iowa');
expect(groupedOptions.length).toBe(14);
});
it('should be able to get the value text from a single-selection select', async () => {
const select = await loader.getHarness(MatSelectHarness.with({selector: '#single-selection'}));
await select.open();
const options = await select.getOptions();
await options[3].click();
expect(await select.getValueText()).toBe('Kansas');
});
it('should be able to get the value text from a multi-selection select', async () => {
const select = await loader.getHarness(
MatSelectHarness.with({selector: '#multiple-selection'}),
);
await select.open();
const options = await select.getOptions();
await options[3].click();
await options[5].click();
expect(await select.getValueText()).toBe('Kansas, New York');
});
it('should be able to get whether a single-selection select is empty', async () => {
const select = await loader.getHarness(MatSelectHarness.with({selector: '#single-selection'}));
expect(await select.isEmpty()).toBe(true);
await select.open();
const options = await select.getOptions();
await options[3].click();
expect(await select.isEmpty()).toBe(false);
});
it('should be able to get whether a multi-selection select is empty', async () => {
const select = await loader.getHarness(
MatSelectHarness.with({selector: '#multiple-selection'}),
);
expect(await select.isEmpty()).toBe(true);
await select.open();
const options = await select.getOptions();
await options[3].click();
await options[5].click();
expect(await select.isEmpty()).toBe(false);
});
it('should be able to click an option', async () => {
const control = fixture.componentInstance.formControl;
const select = await loader.getHarness(MatSelectHarness.with({selector: '#with-form-control'}));
expect(control.value).toBeFalsy();
await select.open();
await (await select.getOptions())[1].click();
expect(control.value).toBe('CA');
});
}); | {
"end_byte": 9135,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/testing/select-harness.spec.ts"
} |
components/src/material/select/testing/select-harness.spec.ts_9137_11773 | @Component({
template: `
<mat-form-field>
<mat-select [disabled]="isDisabled()" [required]="isRequired()" id="single-selection">
@for (state of states; track state) {
<mat-option [value]="state.code">{{ state.name }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-select multiple id="multiple-selection">
@for (state of states; track state) {
<mat-option [value]="state.code">{{ state.name }}</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-select id="grouped">
@for (group of stateGroups; track group) {
<mat-optgroup [label]="group.name">
@for (state of group.states; track state) {
<mat-option [value]="state.code">{{ state.name }}</mat-option>
}
</mat-optgroup>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-select [formControl]="formControl" id="with-form-control">
@for (state of states; track state) {
<mat-option [value]="state.code">{{ state.name }}</mat-option>
}
</mat-select>
</mat-form-field>
`,
standalone: true,
imports: [MatSelectModule, MatFormFieldModule, ReactiveFormsModule],
})
class SelectHarnessTest {
formControl = new FormControl(undefined as string | undefined, [Validators.required]);
isDisabled = signal(false);
isRequired = signal(false);
states = [
{code: 'AL', name: 'Alabama'},
{code: 'CA', name: 'California'},
{code: 'FL', name: 'Florida'},
{code: 'KS', name: 'Kansas'},
{code: 'MA', name: 'Massachusetts'},
{code: 'NY', name: 'New York'},
{code: 'OR', name: 'Oregon'},
{code: 'PA', name: 'Pennsylvania'},
{code: 'TN', name: 'Tennessee'},
{code: 'VA', name: 'Virginia'},
{code: 'WY', name: 'Wyoming'},
];
stateGroups = [
{
name: 'One',
states: [
{code: 'IA', name: 'Iowa'},
{code: 'KS', name: 'Kansas'},
{code: 'KY', name: 'Kentucky'},
{code: 'LA', name: 'Louisiana'},
{code: 'ME', name: 'Maine'},
],
},
{
name: 'Two',
states: [
{code: 'RI', name: 'Rhode Island'},
{code: 'SC', name: 'South Carolina'},
{code: 'SD', name: 'South Dakota'},
{code: 'TN', name: 'Tennessee'},
{code: 'TX', name: 'Texas'},
],
},
{
name: 'Three',
states: [
{code: 'UT', name: 'Utah'},
{code: 'WA', name: 'Washington'},
{code: 'WV', name: 'West Virginia'},
{code: 'WI', name: 'Wisconsin'},
],
},
];
} | {
"end_byte": 11773,
"start_byte": 9137,
"url": "https://github.com/angular/components/blob/main/src/material/select/testing/select-harness.spec.ts"
} |
components/src/material/select/testing/public-api.ts_0_280 | /**
* @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 './select-harness';
export * from './select-harness-filters';
| {
"end_byte": 280,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/testing/public-api.ts"
} |
components/src/material/select/testing/BUILD.bazel_0_926 | 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/core/testing",
"//src/material/form-field/testing/control",
],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
ng_test_library(
name = "unit_tests_lib",
srcs = glob(["**/*.spec.ts"]),
deps = [
":testing",
"//src/cdk/overlay",
"//src/cdk/testing",
"//src/cdk/testing/testbed",
"//src/material/form-field",
"//src/material/select",
"@npm//@angular/forms",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [
":unit_tests_lib",
],
)
| {
"end_byte": 926,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/testing/BUILD.bazel"
} |
components/src/material/select/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/select/testing/index.ts"
} |
components/src/material/select/testing/select-harness.ts_0_5868 | /**
* @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, parallel} from '@angular/cdk/testing';
import {
MatOptionHarness,
MatOptgroupHarness,
OptionHarnessFilters,
OptgroupHarnessFilters,
} from '@angular/material/core/testing';
import {MatFormFieldControlHarness} from '@angular/material/form-field/testing/control';
import {SelectHarnessFilters} from './select-harness-filters';
/** Harness for interacting with a mat-select in tests. */
export class MatSelectHarness extends MatFormFieldControlHarness {
static hostSelector = '.mat-mdc-select';
private _prefix = 'mat-mdc';
private _optionClass = MatOptionHarness;
private _optionGroupClass = MatOptgroupHarness;
private _documentRootLocator = this.documentRootLocatorFactory();
private _backdrop = this._documentRootLocator.locatorFor('.cdk-overlay-backdrop');
/**
* Gets a `HarnessPredicate` that can be used to search for a select with specific attributes.
* @param options Options for filtering which select instances are considered a match.
* @return a `HarnessPredicate` configured with the given options.
*/
static with<T extends MatSelectHarness>(
this: ComponentHarnessConstructor<T>,
options: SelectHarnessFilters = {},
): HarnessPredicate<T> {
return new HarnessPredicate(this, options).addOption(
'disabled',
options.disabled,
async (harness, disabled) => {
return (await harness.isDisabled()) === disabled;
},
);
}
/** Gets a boolean promise indicating if the select is disabled. */
async isDisabled(): Promise<boolean> {
return (await this.host()).hasClass(`${this._prefix}-select-disabled`);
}
/** Gets a boolean promise indicating if the select is valid. */
async isValid(): Promise<boolean> {
return !(await (await this.host()).hasClass('ng-invalid'));
}
/** Gets a boolean promise indicating if the select is required. */
async isRequired(): Promise<boolean> {
return (await this.host()).hasClass(`${this._prefix}-select-required`);
}
/** Gets a boolean promise indicating if the select is empty (no value is selected). */
async isEmpty(): Promise<boolean> {
return (await this.host()).hasClass(`${this._prefix}-select-empty`);
}
/** Gets a boolean promise indicating if the select is in multi-selection mode. */
async isMultiple(): Promise<boolean> {
return (await this.host()).hasClass(`${this._prefix}-select-multiple`);
}
/** Gets a promise for the select's value text. */
async getValueText(): Promise<string> {
const value = await this.locatorFor(`.${this._prefix}-select-value`)();
return value.text();
}
/** Focuses the select and returns a void promise that indicates when the action is complete. */
async focus(): Promise<void> {
return (await this.host()).focus();
}
/** Blurs the select and returns a void promise that indicates when the action is complete. */
async blur(): Promise<void> {
return (await this.host()).blur();
}
/** Whether the select is focused. */
async isFocused(): Promise<boolean> {
return (await this.host()).isFocused();
}
/** Gets the options inside the select panel. */
async getOptions(filter?: Omit<OptionHarnessFilters, 'ancestor'>): Promise<MatOptionHarness[]> {
return this._documentRootLocator.locatorForAll(
this._optionClass.with({
...(filter || {}),
ancestor: await this._getPanelSelector(),
} as OptionHarnessFilters),
)();
}
/** Gets the groups of options inside the panel. */
async getOptionGroups(
filter?: Omit<OptgroupHarnessFilters, 'ancestor'>,
): Promise<MatOptgroupHarness[]> {
return this._documentRootLocator.locatorForAll(
this._optionGroupClass.with({
...(filter || {}),
ancestor: await this._getPanelSelector(),
} as OptgroupHarnessFilters),
)() as Promise<MatOptgroupHarness[]>;
}
/** Gets whether the select is open. */
async isOpen(): Promise<boolean> {
return !!(await this._documentRootLocator.locatorForOptional(await this._getPanelSelector())());
}
/** Opens the select's panel. */
async open(): Promise<void> {
if (!(await this.isOpen())) {
const trigger = await this.locatorFor(`.${this._prefix}-select-trigger`)();
return trigger.click();
}
}
/**
* Clicks the options that match the passed-in filter. If the select is in multi-selection
* mode all options will be clicked, otherwise the harness will pick the first matching option.
*/
async clickOptions(filter?: OptionHarnessFilters): Promise<void> {
await this.open();
const [isMultiple, options] = await parallel(() => [
this.isMultiple(),
this.getOptions(filter),
]);
if (options.length === 0) {
throw Error('Select does not have options matching the specified filter');
}
if (isMultiple) {
await parallel(() => options.map(option => option.click()));
} else {
await options[0].click();
}
}
/** Closes the select's panel. */
async close(): Promise<void> {
if (await this.isOpen()) {
// This is the most consistent way that works both in both single and multi-select modes,
// but it assumes that only one overlay is open at a time. We should be able to make it
// a bit more precise after #16645 where we can dispatch an ESCAPE press to the host instead.
return (await this._backdrop()).click();
}
}
/** Gets the selector that should be used to find this select's panel. */
private async _getPanelSelector(): Promise<string> {
const id = await (await this.host()).getAttribute('id');
return `#${id}-panel`;
}
}
| {
"end_byte": 5868,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/testing/select-harness.ts"
} |
components/src/material/select/testing/select-harness-filters.ts_0_512 | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {BaseHarnessFilters} from '@angular/cdk/testing';
/** A set of criteria that can be used to filter a list of `MatSelectHarness` instances. */
export interface SelectHarnessFilters extends BaseHarnessFilters {
/** Only find instances which match the given disabled state. */
disabled?: boolean;
}
| {
"end_byte": 512,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/select/testing/select-harness-filters.ts"
} |
components/src/material/icon/_icon-theme.scss_0_4278 | @use '../core/theming/theming';
@use '../core/theming/inspection';
@use '../core/theming/validation';
@use '../core/tokens/m2/mat/icon' as tokens-mat-icon;
@use '../core/tokens/token-utils';
@use '../core/style/sass-utils';
@mixin _palette-colors($theme, $palette-name) {
$color: inspection.get-theme-color($theme, $palette-name, text);
$tokens: tokens-mat-icon.private-get-icon-color-tokens($color);
@include token-utils.create-token-values(tokens-mat-icon.$prefix, $tokens);
}
/// Outputs base theme styles (styles not dependent on the color, typography, or density settings)
/// for the mat-icon.
/// @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 {
}
}
/// Outputs color theme styles for the mat-icon.
/// @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 icon: primary, secondary, tertiary, or error
/// (If not specified, default neutral color will be used).
@mixin color($theme, $options...) {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme, color), $options...);
} @else {
@include sass-utils.current-selector-or-root() {
@include token-utils.create-token-values(
tokens-mat-icon.$prefix,
tokens-mat-icon.get-color-tokens($theme)
);
}
.mat-icon {
&.mat-primary {
@include _palette-colors($theme, primary);
}
&.mat-accent {
@include _palette-colors($theme, accent);
}
&.mat-warn {
@include _palette-colors($theme, warn);
}
}
}
}
/// Outputs typography theme styles for the mat-icon.
/// @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 {
}
}
/// Outputs density theme styles for the mat-icon.
/// @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 {
}
}
/// Defines the tokens that will be available in the `overrides` mixin and for docs extraction.
@function _define-overrides() {
@return (
(
namespace: tokens-mat-icon.$prefix,
tokens: tokens-mat-icon.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-icon.
/// @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 icon: surface, primary, secondary, tertiary,
/// or error (If not specified, default surface color will be used).
@mixin theme($theme, $options...) {
@include theming.private-check-duplicate-theme-styles($theme, 'mat-icon') {
@if inspection.get-theme-version($theme) == 1 {
@include _theme-from-tokens(inspection.get-theme-tokens($theme), $options...);
} @else {
@include base($theme);
@if inspection.theme-has($theme, color) {
@include color($theme);
}
@if inspection.theme-has($theme, density) {
@include density($theme);
}
@if inspection.theme-has($theme, typography) {
@include typography($theme);
}
}
}
}
@mixin _theme-from-tokens($tokens, $options...) {
@include validation.selector-defined(
'Calls to Angular Material theme mixins with an M3 theme must be wrapped in a selector'
);
$mat-icon-tokens: token-utils.get-tokens-for($tokens, tokens-mat-icon.$prefix, $options...);
@include token-utils.create-token-values(tokens-mat-icon.$prefix, $mat-icon-tokens);
}
| {
"end_byte": 4278,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/icon/_icon-theme.scss"
} |
components/src/material/icon/icon.scss_0_2030 | @use '../core/style/vendor-prefixes';
@use '../core/tokens/m2/mat/icon' as tokens-mat-icon;
@use '../core/tokens/token-utils';
// The width/height of the icon element.
$size: 24px !default;
// Note that here we target the `mat-icon` tag name with the `color`, instead of `.mat-icon` to
// avoid breaking any existing overrides. It's common to customize the color of icons by setting a
// `color` on the root node. This was easy before the tokens API, because `.mat-icon` doesn't have
// any `color` and users could easily specify it. By adding support for tokens, we have to set a
// `color` so the CSS variable declaration works, but by doing so we can break existing overrides.
// We mitigate against it by targeting the tag name which has the lowest possible specificity.
// Note that this means that we also have to re-declare the property for `primary`, `accent` and
// `warn` because there we want the additional specificity.
mat-icon {
&, &.mat-primary, &.mat-accent, &.mat-warn {
@include token-utils.use-tokens(tokens-mat-icon.$prefix, tokens-mat-icon.get-token-slots()) {
@include token-utils.create-token-slot(color, color);
}
}
}
.mat-icon {
@include vendor-prefixes.user-select(none);
background-repeat: no-repeat;
display: inline-block;
fill: currentColor;
height: $size;
width: $size;
// In some cases the icon elements may extend beyond the container. Clip these cases
// in order to avoid weird overflows and click areas. See #11826.
overflow: hidden;
&.mat-icon-inline {
font-size: inherit;
height: inherit;
line-height: inherit;
width: inherit;
}
&.mat-ligature-font[fontIcon]::before {
content: attr(fontIcon);
}
}
// Icons that will be mirrored in RTL.
[dir='rtl'] .mat-icon-rtl-mirror {
transform: scale(-1, 1);
}
.mat-form-field:not(.mat-form-field-appearance-legacy) {
.mat-form-field-prefix,
.mat-form-field-suffix {
.mat-icon {
display: block;
}
.mat-icon-button .mat-icon {
margin: auto;
}
}
}
| {
"end_byte": 2030,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/icon/icon.scss"
} |
components/src/material/icon/public-api.ts_0_292 | /**
* @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 './icon-module';
export * from './icon';
export * from './icon-registry';
| {
"end_byte": 292,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/icon/public-api.ts"
} |
components/src/material/icon/README.md_0_95 | Please see the official documentation at https://material.angular.io/components/component/icon
| {
"end_byte": 95,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/icon/README.md"
} |
components/src/material/icon/icon.spec.ts_0_9018 | import {wrappedErrorMessage} from '@angular/cdk/testing/private';
import {
HttpClientTestingModule,
HttpTestingController,
TestRequest,
} from '@angular/common/http/testing';
import {Component, ErrorHandler, Provider, Type, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, inject, tick, waitForAsync} from '@angular/core/testing';
import {DomSanitizer, SafeHtml, SafeResourceUrl} from '@angular/platform-browser';
import {FAKE_SVGS} from './fake-svgs';
import {MatIcon} from './icon';
import {MatIconRegistry, getMatIconNoHttpProviderError} from './icon-registry';
import {MAT_ICON_DEFAULT_OPTIONS, MAT_ICON_LOCATION, MatIconModule} from './index';
/** Returns the CSS classes assigned to an element as a sorted array. */
function sortedClassNames(element: Element): string[] {
return element.className.split(' ').sort();
}
/**
* Verifies that an element contains a single `<svg>` child element, and returns that child.
*/
function verifyAndGetSingleSvgChild(element: SVGElement): SVGElement {
expect(element.id).toBeFalsy();
expect(element.childNodes.length).toBe(1);
const svgChild = element.childNodes[0] as SVGElement;
expect(svgChild.tagName.toLowerCase()).toBe('svg');
return svgChild;
}
/**
* Verifies that an element contains a single `<path>` child element whose "id" attribute has
* the specified value.
*/
function verifyPathChildElement(element: Element, attributeValue: string): void {
expect(element.childNodes.length).toBe(1);
const pathElement = element.childNodes[0] as SVGPathElement;
expect(pathElement.tagName.toLowerCase()).toBe('path');
// The testing data SVGs have the name attribute set for verification.
expect(pathElement.getAttribute('name')).toBe(attributeValue);
}
/** Creates a test component fixture. */
function createComponent<T>(component: Type<T>, providers: Provider[] = []) {
TestBed.configureTestingModule({
imports: [MatIconModule, component],
providers: [...providers],
});
return TestBed.createComponent<T>(component);
}
describe('MatIcon', () => {
let fakePath: string;
let iconRegistry: MatIconRegistry;
let http: HttpTestingController;
let sanitizer: DomSanitizer;
let errorHandler: ErrorHandler;
beforeEach(waitForAsync(() => {
// The $ prefix tells Karma not to try to process the
// request so that we don't get warnings in our logs.
fakePath = '/$fake-path';
TestBed.configureTestingModule({
imports: [
HttpClientTestingModule,
MatIconModule,
IconWithColor,
IconWithLigature,
IconWithLigatureByAttribute,
IconWithCustomFontCss,
IconFromSvgName,
IconWithAriaHiddenFalse,
IconWithBindingAndNgIf,
InlineIcon,
SvgIconWithUserContent,
IconWithLigatureAndSvgBinding,
BlankIcon,
],
providers: [
{
provide: MAT_ICON_LOCATION,
useValue: {getPathname: () => fakePath},
},
],
});
iconRegistry = TestBed.inject(MatIconRegistry);
http = TestBed.inject(HttpTestingController);
sanitizer = TestBed.inject(DomSanitizer);
errorHandler = TestBed.inject(ErrorHandler);
}));
it('should apply the correct role', () => {
const fixture = TestBed.createComponent(IconWithColor);
const icon = fixture.debugElement.nativeElement.querySelector('mat-icon');
expect(icon.getAttribute('role')).toBe('img');
});
it('should include notranslate class by default', () => {
const fixture = TestBed.createComponent(IconWithColor);
const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
expect(matIconElement.classList.contains('notranslate'))
.withContext('Expected the mat-icon element to include the notranslate class')
.toBeTruthy();
});
it('should apply class based on color attribute', () => {
const fixture = TestBed.createComponent(IconWithColor);
const testComponent = fixture.componentInstance;
const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
testComponent.iconName = 'home';
testComponent.iconColor = 'primary';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(sortedClassNames(matIconElement)).toEqual([
'mat-icon',
'mat-ligature-font',
'mat-primary',
'material-icons',
'notranslate',
]);
});
it('should apply a class if there is no color', () => {
const fixture = TestBed.createComponent(IconWithColor);
const testComponent = fixture.componentInstance;
const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
testComponent.iconName = 'home';
testComponent.iconColor = '';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(sortedClassNames(matIconElement)).toEqual([
'mat-icon',
'mat-icon-no-color',
'mat-ligature-font',
'material-icons',
'notranslate',
]);
});
it('should mark mat-icon as aria-hidden by default', () => {
const fixture = TestBed.createComponent(IconWithLigature);
const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
expect(iconElement.getAttribute('aria-hidden'))
.withContext('Expected the mat-icon element has aria-hidden="true" by default')
.toBe('true');
});
it('should not override a user-provided aria-hidden attribute', () => {
const fixture = TestBed.createComponent(IconWithAriaHiddenFalse);
const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
expect(iconElement.getAttribute('aria-hidden'))
.withContext('Expected the mat-icon element has the user-provided aria-hidden value')
.toBe('false');
});
it('should apply inline styling', () => {
const fixture = TestBed.createComponent(InlineIcon);
const iconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
expect(iconElement.classList.contains('mat-icon-inline'))
.withContext('Expected the mat-icon element to not include the inline styling class')
.toBeFalsy();
fixture.debugElement.componentInstance.inline = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(iconElement.classList.contains('mat-icon-inline'))
.withContext('Expected the mat-icon element to include the inline styling class')
.toBeTruthy();
});
describe('Ligature icons', () => {
it('should add material-icons and mat-ligature-font class by default', () => {
const fixture = TestBed.createComponent(IconWithLigature);
const testComponent = fixture.componentInstance;
const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
testComponent.iconName = 'home';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(sortedClassNames(matIconElement)).toEqual([
'mat-icon',
'mat-icon-no-color',
'mat-ligature-font',
'material-icons',
'notranslate',
]);
});
it('should use alternate icon font if set', () => {
iconRegistry.setDefaultFontSetClass('myfont', 'mat-ligature-font');
const fixture = TestBed.createComponent(IconWithLigature);
const testComponent = fixture.componentInstance;
const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
testComponent.iconName = 'home';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(sortedClassNames(matIconElement)).toEqual([
'mat-icon',
'mat-icon-no-color',
'mat-ligature-font',
'myfont',
'notranslate',
]);
});
it('should not clear the text of a ligature icon if the svgIcon is bound to something falsy', () => {
const fixture = TestBed.createComponent(IconWithLigatureAndSvgBinding);
const testComponent = fixture.componentInstance;
const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
testComponent.iconName = undefined;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(matIconElement.textContent.trim()).toBe('house');
});
it('should be able to provide multiple alternate icon set classes', () => {
iconRegistry.setDefaultFontSetClass('myfont', 'mat-ligature-font', 'myfont-48x48');
let fixture = TestBed.createComponent(IconWithLigature);
const testComponent = fixture.componentInstance;
const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
testComponent.iconName = 'home';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(sortedClassNames(matIconElement)).toEqual([
'mat-icon',
'mat-icon-no-color',
'mat-ligature-font',
'myfont',
'myfont-48x48',
'notranslate',
]);
});
}); | {
"end_byte": 9018,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material/icon/icon.spec.ts"
} |
components/src/material/icon/icon.spec.ts_9022_11731 | describe('Ligature icons by attribute', () => {
it('should forward the fontIcon attribute', () => {
const fixture = TestBed.createComponent(IconWithLigatureByAttribute);
const testComponent = fixture.componentInstance;
const icon = fixture.debugElement.nativeElement.querySelector('mat-icon');
testComponent.iconName = 'home';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(icon.getAttribute('fontIcon')).toBe('home');
testComponent.iconName = 'house';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(icon.getAttribute('fontIcon')).toBe('house');
});
it('should add material-icons and mat-ligature-font class by default', () => {
const fixture = TestBed.createComponent(IconWithLigatureByAttribute);
const testComponent = fixture.componentInstance;
const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
testComponent.iconName = 'home';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(sortedClassNames(matIconElement)).toEqual([
'mat-icon',
'mat-icon-no-color',
'mat-ligature-font',
'material-icons',
'notranslate',
]);
});
it('should use alternate icon font if set', () => {
iconRegistry.setDefaultFontSetClass('myfont', 'mat-ligature-font');
const fixture = TestBed.createComponent(IconWithLigatureByAttribute);
const testComponent = fixture.componentInstance;
const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
testComponent.iconName = 'home';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(sortedClassNames(matIconElement)).toEqual([
'mat-icon',
'mat-icon-no-color',
'mat-ligature-font',
'myfont',
'notranslate',
]);
});
it('should be able to provide multiple alternate icon set classes', () => {
iconRegistry.setDefaultFontSetClass('myfont', 'mat-ligature-font', 'myfont-48x48');
let fixture = TestBed.createComponent(IconWithLigatureByAttribute);
const testComponent = fixture.componentInstance;
const matIconElement = fixture.debugElement.nativeElement.querySelector('mat-icon');
testComponent.iconName = 'home';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(sortedClassNames(matIconElement)).toEqual([
'mat-icon',
'mat-icon-no-color',
'mat-ligature-font',
'myfont',
'myfont-48x48',
'notranslate',
]);
});
}); | {
"end_byte": 11731,
"start_byte": 9022,
"url": "https://github.com/angular/components/blob/main/src/material/icon/icon.spec.ts"
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.