_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/material-moment-adapter/index.ts_0_234
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/index.ts"
}
|
components/src/material-moment-adapter/adapter/moment-date-formats.ts_0_557
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {MatDateFormats} from '@angular/material/core';
export const MAT_MOMENT_DATE_FORMATS: MatDateFormats = {
parse: {
dateInput: 'l',
timeInput: 'LT',
},
display: {
dateInput: 'l',
timeInput: 'LT',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
timeOptionLabel: 'LT',
},
};
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 557,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/adapter/moment-date-formats.ts"
}
|
components/src/material-moment-adapter/adapter/moment-date-adapter.ts_0_2148
|
/**
* @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 {Injectable, InjectionToken, inject} from '@angular/core';
import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core';
// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
// TODO(mmalerba): See if we can clean this up at some point.
import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment, Moment, MomentFormatSpecification, MomentInput} from 'moment';
const moment = _rollupMoment || _moment;
/** Configurable options for MomentDateAdapter. */
export interface MatMomentDateAdapterOptions {
/**
* When enabled, the dates have to match the format exactly.
* See https://momentjs.com/guides/#/parsing/strict-mode/.
*/
strict?: boolean;
/**
* Turns the use of utc dates on or off.
* Changing this will change how Angular Material components like DatePicker output dates.
* Defaults to `false`.
*/
useUtc?: boolean;
}
/** InjectionToken for moment date adapter to configure options. */
export const MAT_MOMENT_DATE_ADAPTER_OPTIONS = new InjectionToken<MatMomentDateAdapterOptions>(
'MAT_MOMENT_DATE_ADAPTER_OPTIONS',
{
providedIn: 'root',
factory: MAT_MOMENT_DATE_ADAPTER_OPTIONS_FACTORY,
},
);
/** @docs-private */
export function MAT_MOMENT_DATE_ADAPTER_OPTIONS_FACTORY(): MatMomentDateAdapterOptions {
return {
useUtc: false,
};
}
/** Creates an array and fills it with values. */
function range<T>(length: number, valueFunction: (index: number) => T): T[] {
const valuesArray = Array(length);
for (let i = 0; i < length; i++) {
valuesArray[i] = valueFunction(i);
}
return valuesArray;
}
/** Adapts Moment.js Dates for use with Angular Material. */
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2148,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/adapter/moment-date-adapter.ts"
}
|
components/src/material-moment-adapter/adapter/moment-date-adapter.ts_2149_9474
|
@Injectable()
export class MomentDateAdapter extends DateAdapter<Moment> {
private _options = inject<MatMomentDateAdapterOptions>(MAT_MOMENT_DATE_ADAPTER_OPTIONS, {
optional: true,
});
// Note: all of the methods that accept a `Moment` input parameter immediately call `this.clone`
// on it. This is to ensure that we're working with a `Moment` that has the correct locale setting
// while avoiding mutating the original object passed to us. Just calling `.locale(...)` on the
// input would mutate the object.
private _localeData: {
firstDayOfWeek: number;
longMonths: string[];
shortMonths: string[];
dates: string[];
longDaysOfWeek: string[];
shortDaysOfWeek: string[];
narrowDaysOfWeek: string[];
};
constructor(...args: unknown[]);
constructor() {
super();
const dateLocale = inject<string>(MAT_DATE_LOCALE, {optional: true});
this.setLocale(dateLocale || moment.locale());
}
override setLocale(locale: string) {
super.setLocale(locale);
let momentLocaleData = moment.localeData(locale);
this._localeData = {
firstDayOfWeek: momentLocaleData.firstDayOfWeek(),
longMonths: momentLocaleData.months(),
shortMonths: momentLocaleData.monthsShort(),
dates: range(31, i => this.createDate(2017, 0, i + 1).format('D')),
longDaysOfWeek: momentLocaleData.weekdays(),
shortDaysOfWeek: momentLocaleData.weekdaysShort(),
narrowDaysOfWeek: momentLocaleData.weekdaysMin(),
};
}
getYear(date: Moment): number {
return this.clone(date).year();
}
getMonth(date: Moment): number {
return this.clone(date).month();
}
getDate(date: Moment): number {
return this.clone(date).date();
}
getDayOfWeek(date: Moment): number {
return this.clone(date).day();
}
getMonthNames(style: 'long' | 'short' | 'narrow'): string[] {
// Moment.js doesn't support narrow month names, so we just use short if narrow is requested.
return style == 'long' ? this._localeData.longMonths : this._localeData.shortMonths;
}
getDateNames(): string[] {
return this._localeData.dates;
}
getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] {
if (style == 'long') {
return this._localeData.longDaysOfWeek;
}
if (style == 'short') {
return this._localeData.shortDaysOfWeek;
}
return this._localeData.narrowDaysOfWeek;
}
getYearName(date: Moment): string {
return this.clone(date).format('YYYY');
}
getFirstDayOfWeek(): number {
return this._localeData.firstDayOfWeek;
}
getNumDaysInMonth(date: Moment): number {
return this.clone(date).daysInMonth();
}
clone(date: Moment): Moment {
return date.clone().locale(this.locale);
}
createDate(year: number, month: number, date: number): Moment {
// Moment.js will create an invalid date if any of the components are out of bounds, but we
// explicitly check each case so we can throw more descriptive errors.
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (month < 0 || month > 11) {
throw Error(`Invalid month index "${month}". Month index has to be between 0 and 11.`);
}
if (date < 1) {
throw Error(`Invalid date "${date}". Date has to be greater than 0.`);
}
}
const result = this._createMoment({year, month, date}).locale(this.locale);
// If the result isn't valid, the date must have been out of bounds for this month.
if (!result.isValid() && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error(`Invalid date "${date}" for month with index "${month}".`);
}
return result;
}
today(): Moment {
return this._createMoment().locale(this.locale);
}
parse(value: any, parseFormat: string | string[]): Moment | null {
if (value && typeof value == 'string') {
return this._createMoment(value, parseFormat, this.locale);
}
return value ? this._createMoment(value).locale(this.locale) : null;
}
format(date: Moment, displayFormat: string): string {
date = this.clone(date);
if (!this.isValid(date) && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error('MomentDateAdapter: Cannot format invalid date.');
}
return date.format(displayFormat);
}
addCalendarYears(date: Moment, years: number): Moment {
return this.clone(date).add({years});
}
addCalendarMonths(date: Moment, months: number): Moment {
return this.clone(date).add({months});
}
addCalendarDays(date: Moment, days: number): Moment {
return this.clone(date).add({days});
}
toIso8601(date: Moment): string {
return this.clone(date).format();
}
/**
* Returns the given value if given a valid Moment or null. Deserializes valid ISO 8601 strings
* (https://www.ietf.org/rfc/rfc3339.txt) and valid Date objects into valid Moments and empty
* string into null. Returns an invalid date for all other values.
*/
override deserialize(value: any): Moment | null {
let date;
if (value instanceof Date) {
date = this._createMoment(value).locale(this.locale);
} else if (this.isDateInstance(value)) {
// Note: assumes that cloning also sets the correct locale.
return this.clone(value);
}
if (typeof value === 'string') {
if (!value) {
return null;
}
date = this._createMoment(value, moment.ISO_8601).locale(this.locale);
}
if (date && this.isValid(date)) {
return this._createMoment(date).locale(this.locale);
}
return super.deserialize(value);
}
isDateInstance(obj: any): boolean {
return moment.isMoment(obj);
}
isValid(date: Moment): boolean {
return this.clone(date).isValid();
}
invalid(): Moment {
return moment.invalid();
}
override setTime(target: Moment, hours: number, minutes: number, seconds: number): Moment {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (hours < 0 || hours > 23) {
throw Error(`Invalid hours "${hours}". Hours value must be between 0 and 23.`);
}
if (minutes < 0 || minutes > 59) {
throw Error(`Invalid minutes "${minutes}". Minutes value must be between 0 and 59.`);
}
if (seconds < 0 || seconds > 59) {
throw Error(`Invalid seconds "${seconds}". Seconds value must be between 0 and 59.`);
}
}
return this.clone(target).set({hours, minutes, seconds, milliseconds: 0});
}
override getHours(date: Moment): number {
return date.hours();
}
override getMinutes(date: Moment): number {
return date.minutes();
}
override getSeconds(date: Moment): number {
return date.seconds();
}
override parseTime(value: any, parseFormat: string | string[]): Moment | null {
return this.parse(value, parseFormat);
}
override addSeconds(date: Moment, amount: number): Moment {
return this.clone(date).add({seconds: amount});
}
/** Creates a Moment instance while respecting the current UTC settings. */
private _createMoment(
date?: MomentInput,
format?: MomentFormatSpecification,
locale?: string,
): Moment {
const {strict, useUtc}: MatMomentDateAdapterOptions = this._options || {};
return useUtc ? moment.utc(date, format, locale, strict) : moment(date, format, locale, strict);
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 9474,
"start_byte": 2149,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/adapter/moment-date-adapter.ts"
}
|
components/src/material-moment-adapter/adapter/index.ts_0_1454
|
/**
* @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, Provider} from '@angular/core';
import {
DateAdapter,
MAT_DATE_FORMATS,
MAT_DATE_LOCALE,
MatDateFormats,
} from '@angular/material/core';
import {
MAT_MOMENT_DATE_ADAPTER_OPTIONS,
MatMomentDateAdapterOptions,
MomentDateAdapter,
} from './moment-date-adapter';
import {MAT_MOMENT_DATE_FORMATS} from './moment-date-formats';
export * from './moment-date-adapter';
export * from './moment-date-formats';
@NgModule({
providers: [
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
},
],
})
export class MomentDateModule {}
@NgModule({
providers: [provideMomentDateAdapter()],
})
export class MatMomentDateModule {}
export function provideMomentDateAdapter(
formats: MatDateFormats = MAT_MOMENT_DATE_FORMATS,
options?: MatMomentDateAdapterOptions,
): Provider[] {
const providers: Provider[] = [
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS],
},
{provide: MAT_DATE_FORMATS, useValue: formats},
];
if (options) {
providers.push({provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS, useValue: options});
}
return providers;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1454,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/adapter/index.ts"
}
|
components/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts_0_670
|
/**
* @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 {LOCALE_ID} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core';
import {DEC, FEB, JAN, MAR} from '../../material/testing';
import {MomentDateModule} from './index';
import {MAT_MOMENT_DATE_ADAPTER_OPTIONS, MomentDateAdapter} from './moment-date-adapter';
import moment from 'moment';
// Import all locales for specs relying on non-US locales.
import 'moment/min/locales';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 670,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts"
}
|
components/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts_672_7263
|
describe('MomentDateAdapter', () => {
let adapter: MomentDateAdapter;
let assertValidDate: (d: moment.Moment | null, valid: boolean) => void;
beforeEach(() => {
TestBed.configureTestingModule({imports: [MomentDateModule]});
moment.locale('en');
adapter = TestBed.inject(DateAdapter) as MomentDateAdapter;
adapter.setLocale('en');
assertValidDate = (d: moment.Moment | null, valid: boolean) => {
expect(adapter.isDateInstance(d))
.not.withContext(`Expected ${d} to be a date instance`)
.toBeNull();
expect(adapter.isValid(d!))
.withContext(
`Expected ${d} to be ${valid ? 'valid' : 'invalid'}, but ` +
`was ${valid ? 'invalid' : 'valid'}`,
)
.toBe(valid);
};
});
it('should get year', () => {
expect(adapter.getYear(moment([2017, JAN, 1]))).toBe(2017);
});
it('should get month', () => {
expect(adapter.getMonth(moment([2017, JAN, 1]))).toBe(0);
});
it('should get date', () => {
expect(adapter.getDate(moment([2017, JAN, 1]))).toBe(1);
});
it('should get day of week', () => {
expect(adapter.getDayOfWeek(moment([2017, JAN, 1]))).toBe(0);
});
it('should get same day of week in a locale with a different first day of the week', () => {
adapter.setLocale('fr');
expect(adapter.getDayOfWeek(moment([2017, JAN, 1]))).toBe(0);
});
it('should get long month names', () => {
expect(adapter.getMonthNames('long')).toEqual([
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
]);
});
it('should get short month names', () => {
expect(adapter.getMonthNames('short')).toEqual([
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
]);
});
it('should get narrow month names', () => {
expect(adapter.getMonthNames('narrow')).toEqual([
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
]);
});
it('should get month names in a different locale', () => {
adapter.setLocale('ja-JP');
expect(adapter.getMonthNames('long')).toEqual([
'1月',
'2月',
'3月',
'4月',
'5月',
'6月',
'7月',
'8月',
'9月',
'10月',
'11月',
'12月',
]);
});
it('should get date names', () => {
expect(adapter.getDateNames()).toEqual([
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'10',
'11',
'12',
'13',
'14',
'15',
'16',
'17',
'18',
'19',
'20',
'21',
'22',
'23',
'24',
'25',
'26',
'27',
'28',
'29',
'30',
'31',
]);
});
it('should get date names in a different locale', () => {
adapter.setLocale('ar-AE');
expect(adapter.getDateNames()).toEqual([
'١',
'٢',
'٣',
'٤',
'٥',
'٦',
'٧',
'٨',
'٩',
'١٠',
'١١',
'١٢',
'١٣',
'١٤',
'١٥',
'١٦',
'١٧',
'١٨',
'١٩',
'٢٠',
'٢١',
'٢٢',
'٢٣',
'٢٤',
'٢٥',
'٢٦',
'٢٧',
'٢٨',
'٢٩',
'٣٠',
'٣١',
]);
});
it('should get long day of week names', () => {
expect(adapter.getDayOfWeekNames('long')).toEqual([
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
]);
});
it('should get short day of week names', () => {
expect(adapter.getDayOfWeekNames('short')).toEqual([
'Sun',
'Mon',
'Tue',
'Wed',
'Thu',
'Fri',
'Sat',
]);
});
it('should get narrow day of week names', () => {
expect(adapter.getDayOfWeekNames('narrow')).toEqual(['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']);
});
it('should get day of week names in a different locale', () => {
adapter.setLocale('ja-JP');
expect(adapter.getDayOfWeekNames('long')).toEqual([
'日曜日',
'月曜日',
'火曜日',
'水曜日',
'木曜日',
'金曜日',
'土曜日',
]);
});
it('should get year name', () => {
expect(adapter.getYearName(moment([2017, JAN, 1]))).toBe('2017');
});
it('should get year name in a different locale', () => {
adapter.setLocale('ar-AE');
expect(adapter.getYearName(moment([2017, JAN, 1]))).toBe('٢٠١٧');
});
it('should get first day of week', () => {
expect(adapter.getFirstDayOfWeek()).toBe(0);
});
it('should get first day of week in a different locale', () => {
adapter.setLocale('fr');
expect(adapter.getFirstDayOfWeek()).toBe(1);
});
it('should create Moment date', () => {
expect(adapter.createDate(2017, JAN, 1).format()).toEqual(moment([2017, JAN, 1]).format());
});
it('should not create Moment date with month over/under-flow', () => {
expect(() => adapter.createDate(2017, DEC + 1, 1)).toThrow();
expect(() => adapter.createDate(2017, JAN - 1, 1)).toThrow();
});
it('should not create Moment date with date over/under-flow', () => {
expect(() => adapter.createDate(2017, JAN, 32)).toThrow();
expect(() => adapter.createDate(2017, JAN, 0)).toThrow();
});
it('should create Moment date with low year number', () => {
expect(adapter.createDate(-1, JAN, 1).year()).toBe(-1);
expect(adapter.createDate(0, JAN, 1).year()).toBe(0);
expect(adapter.createDate(50, JAN, 1).year()).toBe(50);
expect(adapter.createDate(99, JAN, 1).year()).toBe(99);
expect(adapter.createDate(100, JAN, 1).year()).toBe(100);
});
it('should not create Moment date in utc format', () => {
expect(adapter.createDate(2017, JAN, 5).isUTC()).toEqual(false);
});
it("should get today's date", () => {
expect(adapter.sameDate(adapter.today(), moment()))
.withContext("should be equal to today's date")
.toBe(true);
});
it('should parse string according to given format', () => {
expect(adapter.parse('1/2/2017', 'MM/DD/YYYY')!.format()).toEqual(
moment([2017, JAN, 2]).format(),
);
expect(adapter.parse('1/2/2017', 'DD/MM/YYYY')!.format()).toEqual(
moment([2017, FEB, 1]).format(),
);
});
it('should parse number', () => {
let timestamp = new Date().getTime();
expect(adapter.parse(timestamp, 'MM/DD/
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 7263,
"start_byte": 672,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts"
}
|
components/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts_7267_14403
|
')!.format()).toEqual(moment(timestamp).format());
});
it('should parse Date', () => {
let date = new Date(2017, JAN, 1);
expect(adapter.parse(date, 'MM/DD/YYYY')!.format()).toEqual(moment(date).format());
});
it('should parse Moment date', () => {
let date = moment([2017, JAN, 1]);
let parsedDate = adapter.parse(date, 'MM/DD/YYYY');
expect(parsedDate!.format()).toEqual(date.format());
expect(parsedDate).not.toBe(date);
});
it('should parse empty string as null', () => {
expect(adapter.parse('', 'MM/DD/YYYY')).toBeNull();
});
it('should parse invalid value as invalid', () => {
let d = adapter.parse('hello', 'MM/DD/YYYY');
expect(d).not.toBeNull();
expect(adapter.isDateInstance(d))
.withContext('Expected string to have been fed through Date.parse')
.toBe(true);
expect(adapter.isValid(d as moment.Moment))
.withContext('Expected to parse as "invalid date" object')
.toBe(false);
});
it('should format date according to given format', () => {
expect(adapter.format(moment([2017, JAN, 2]), 'MM/DD/YYYY')).toEqual('01/02/2017');
expect(adapter.format(moment([2017, JAN, 2]), 'DD/MM/YYYY')).toEqual('02/01/2017');
});
it('should format with a different locale', () => {
expect(adapter.format(moment([2017, JAN, 2]), 'll')).toEqual('Jan 2, 2017');
adapter.setLocale('ja-JP');
expect(adapter.format(moment([2017, JAN, 2]), 'll')).toEqual('2017年1月2日');
});
it('should throw when attempting to format invalid date', () => {
expect(() => adapter.format(moment(NaN), 'MM/DD/YYYY')).toThrowError(
/MomentDateAdapter: Cannot format invalid date\./,
);
});
it('should add years', () => {
expect(adapter.addCalendarYears(moment([2017, JAN, 1]), 1).format()).toEqual(
moment([2018, JAN, 1]).format(),
);
expect(adapter.addCalendarYears(moment([2017, JAN, 1]), -1).format()).toEqual(
moment([2016, JAN, 1]).format(),
);
});
it('should respect leap years when adding years', () => {
expect(adapter.addCalendarYears(moment([2016, FEB, 29]), 1).format()).toEqual(
moment([2017, FEB, 28]).format(),
);
expect(adapter.addCalendarYears(moment([2016, FEB, 29]), -1).format()).toEqual(
moment([2015, FEB, 28]).format(),
);
});
it('should add months', () => {
expect(adapter.addCalendarMonths(moment([2017, JAN, 1]), 1).format()).toEqual(
moment([2017, FEB, 1]).format(),
);
expect(adapter.addCalendarMonths(moment([2017, JAN, 1]), -1).format()).toEqual(
moment([2016, DEC, 1]).format(),
);
});
it('should respect month length differences when adding months', () => {
expect(adapter.addCalendarMonths(moment([2017, JAN, 31]), 1).format()).toEqual(
moment([2017, FEB, 28]).format(),
);
expect(adapter.addCalendarMonths(moment([2017, MAR, 31]), -1).format()).toEqual(
moment([2017, FEB, 28]).format(),
);
});
it('should add days', () => {
expect(adapter.addCalendarDays(moment([2017, JAN, 1]), 1).format()).toEqual(
moment([2017, JAN, 2]).format(),
);
expect(adapter.addCalendarDays(moment([2017, JAN, 1]), -1).format()).toEqual(
moment([2016, DEC, 31]).format(),
);
});
it('should clone', () => {
let date = moment([2017, JAN, 1]);
expect(adapter.clone(date).format()).toEqual(date.format());
expect(adapter.clone(date)).not.toBe(date);
});
it('should compare dates', () => {
expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2017, JAN, 2]))).toBeLessThan(0);
expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2017, FEB, 1]))).toBeLessThan(0);
expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2018, JAN, 1]))).toBeLessThan(0);
expect(adapter.compareDate(moment([2017, JAN, 1]), moment([2017, JAN, 1]))).toBe(0);
expect(adapter.compareDate(moment([2018, JAN, 1]), moment([2017, JAN, 1]))).toBeGreaterThan(0);
expect(adapter.compareDate(moment([2017, FEB, 1]), moment([2017, JAN, 1]))).toBeGreaterThan(0);
expect(adapter.compareDate(moment([2017, JAN, 2]), moment([2017, JAN, 1]))).toBeGreaterThan(0);
});
it('should clamp date at lower bound', () => {
expect(
adapter.clampDate(moment([2017, JAN, 1]), moment([2018, JAN, 1]), moment([2019, JAN, 1])),
).toEqual(moment([2018, JAN, 1]));
});
it('should clamp date at upper bound', () => {
expect(
adapter.clampDate(moment([2020, JAN, 1]), moment([2018, JAN, 1]), moment([2019, JAN, 1])),
).toEqual(moment([2019, JAN, 1]));
});
it('should clamp date already within bounds', () => {
expect(
adapter.clampDate(moment([2018, FEB, 1]), moment([2018, JAN, 1]), moment([2019, JAN, 1])),
).toEqual(moment([2018, FEB, 1]));
});
it('should count today as a valid date instance', () => {
let d = moment();
expect(adapter.isValid(d)).toBe(true);
expect(adapter.isDateInstance(d)).toBe(true);
});
it('should count an invalid date as an invalid date instance', () => {
let d = moment(NaN);
expect(adapter.isValid(d)).toBe(false);
expect(adapter.isDateInstance(d)).toBe(true);
});
it('should count a string as not a date instance', () => {
let d = '1/1/2017';
expect(adapter.isDateInstance(d)).toBe(false);
});
it('should count a Date as not a date instance', () => {
let d = new Date();
expect(adapter.isDateInstance(d)).toBe(false);
});
it('should provide a method to return a valid date or null', () => {
let d = moment();
expect(adapter.getValidDateOrNull(d)).toBe(d);
expect(adapter.getValidDateOrNull(moment(NaN))).toBeNull();
});
it('should create valid dates from valid ISO strings', () => {
assertValidDate(adapter.deserialize('1985-04-12T23:20:50.52Z'), true);
assertValidDate(adapter.deserialize('1996-12-19T16:39:57-08:00'), true);
assertValidDate(adapter.deserialize('1937-01-01T12:00:27.87+00:20'), true);
assertValidDate(adapter.deserialize('1990-13-31T23:59:00Z'), false);
assertValidDate(adapter.deserialize('1/1/2017'), false);
expect(adapter.deserialize('')).toBeNull();
expect(adapter.deserialize(null)).toBeNull();
assertValidDate(adapter.deserialize(new Date()), true);
assertValidDate(adapter.deserialize(new Date(NaN)), false);
assertValidDate(adapter.deserialize(moment()), true);
assertValidDate(adapter.deserialize(moment.invalid()), false);
});
it('should clone the date when deserializing a Moment date', () => {
let date = moment([2017, JAN, 1]);
expect(adapter.deserialize(date)!.format()).toEqual(date.format());
expect(adapter.deserialize(date)).not.toBe(date);
});
it('should deserialize dates with the correct locale', () => {
adapter.setLocale('ja');
expect(adapter.deserialize('1985-04-12T23:20:50.52Z')!.locale()).toBe('ja');
expect(adapter.deserialize(new Date())!.locale()).toBe('ja');
expect(adapter.deserialize(moment())!.locale()).toBe('ja');
});
it('setLocale should not modify global moment locale', () => {
expect(moment.locale()).toBe('en');
adapter.setLocale(
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 14403,
"start_byte": 7267,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts"
}
|
components/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts_14407_21504
|
JP');
expect(moment.locale()).toBe('en');
});
it('returned Moments should have correct locale', () => {
adapter.setLocale('ja-JP');
expect(adapter.createDate(2017, JAN, 1).locale()).toBe('ja');
expect(adapter.today().locale()).toBe('ja');
expect(adapter.clone(moment()).locale()).toBe('ja');
expect(adapter.parse('1/1/2017', 'MM/DD/YYYY')!.locale()).toBe('ja');
expect(adapter.addCalendarDays(moment(), 1).locale()).toBe('ja');
expect(adapter.addCalendarMonths(moment(), 1).locale()).toBe('ja');
expect(adapter.addCalendarYears(moment(), 1).locale()).toBe('ja');
});
it('should not change locale of Moments passed as params', () => {
let date = moment();
expect(date.locale()).toBe('en');
adapter.setLocale('ja-JP');
adapter.getYear(date);
adapter.getMonth(date);
adapter.getDate(date);
adapter.getDayOfWeek(date);
adapter.getYearName(date);
adapter.getNumDaysInMonth(date);
adapter.clone(date);
adapter.parse(date, 'MM/DD/YYYY');
adapter.format(date, 'MM/DD/YYYY');
adapter.addCalendarDays(date, 1);
adapter.addCalendarMonths(date, 1);
adapter.addCalendarYears(date, 1);
adapter.toIso8601(date);
adapter.isDateInstance(date);
adapter.isValid(date);
expect(date.locale()).toBe('en');
});
it('should create invalid date', () => {
assertValidDate(adapter.invalid(), false);
});
it('should get hours', () => {
expect(adapter.getHours(moment([2024, JAN, 1, 14]))).toBe(14);
});
it('should get minutes', () => {
expect(adapter.getMinutes(moment([2024, JAN, 1, 14, 53]))).toBe(53);
});
it('should get seconds', () => {
expect(adapter.getSeconds(moment([2024, JAN, 1, 14, 53, 42]))).toBe(42);
});
it('should set the time of a date', () => {
const target = moment([2024, JAN, 1, 0, 0, 0]);
const result = adapter.setTime(target, 14, 53, 42);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(53);
expect(adapter.getSeconds(result)).toBe(42);
});
it('should throw when passing in invalid hours to setTime', () => {
expect(() => adapter.setTime(adapter.today(), -1, 0, 0)).toThrowError(
'Invalid hours "-1". Hours value must be between 0 and 23.',
);
expect(() => adapter.setTime(adapter.today(), 51, 0, 0)).toThrowError(
'Invalid hours "51". Hours value must be between 0 and 23.',
);
});
it('should throw when passing in invalid minutes to setTime', () => {
expect(() => adapter.setTime(adapter.today(), 0, -1, 0)).toThrowError(
'Invalid minutes "-1". Minutes value must be between 0 and 59.',
);
expect(() => adapter.setTime(adapter.today(), 0, 65, 0)).toThrowError(
'Invalid minutes "65". Minutes value must be between 0 and 59.',
);
});
it('should throw when passing in invalid seconds to setTime', () => {
expect(() => adapter.setTime(adapter.today(), 0, 0, -1)).toThrowError(
'Invalid seconds "-1". Seconds value must be between 0 and 59.',
);
expect(() => adapter.setTime(adapter.today(), 0, 0, 65)).toThrowError(
'Invalid seconds "65". Seconds value must be between 0 and 59.',
);
});
it('should parse a 24-hour time string', () => {
const result = adapter.parseTime('14:52', 'LT')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(0);
});
it('should parse a 12-hour time string', () => {
const result = adapter.parseTime('2:52 PM', 'LT')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(0);
});
it('should parse a padded time string', () => {
const result = adapter.parseTime('03:04:05', 'LTS')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(3);
expect(adapter.getMinutes(result)).toBe(4);
expect(adapter.getSeconds(result)).toBe(5);
});
it('should parse a time string that uses dot as a separator', () => {
adapter.setLocale('fi-FI');
const result = adapter.parseTime('14.52', 'LT')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(0);
});
it('should parse a time string with characters around the time', () => {
adapter.setLocale('bg-BG');
const result = adapter.parseTime('14:52 ч.', 'LT')!;
expect(result).toBeTruthy();
expect(adapter.isValid(result)).toBe(true);
expect(adapter.getHours(result)).toBe(14);
expect(adapter.getMinutes(result)).toBe(52);
expect(adapter.getSeconds(result)).toBe(0);
});
it('should return an invalid date when parsing invalid time string', () => {
expect(adapter.isValid(adapter.parseTime('abc', 'LT')!)).toBeFalse();
expect(adapter.isValid(adapter.parseTime(' ', 'LT')!)).toBeFalse();
expect(adapter.isValid(adapter.parseTime(true, 'LT')!)).toBeFalse();
expect(adapter.isValid(adapter.parseTime('24:05', 'LT')!)).toBeFalse();
expect(adapter.isValid(adapter.parseTime('00:61:05', 'LTS')!)).toBeFalse();
expect(adapter.isValid(adapter.parseTime('14:52:78', 'LTS')!)).toBeFalse();
});
it('should return null when parsing unsupported time values', () => {
expect(adapter.parseTime(undefined, 'LT')).toBeNull();
expect(adapter.parseTime('', 'LT')).toBeNull();
});
it('should compare times', () => {
// Use different dates to guarantee that we only compare the times.
const aDate = [2024, JAN, 1] as const;
const bDate = [2024, FEB, 7] as const;
expect(
adapter.compareTime(moment([...aDate, 12, 0, 0]), moment([...bDate, 13, 0, 0])),
).toBeLessThan(0);
expect(
adapter.compareTime(moment([...aDate, 12, 50, 0]), moment([...bDate, 12, 51, 0])),
).toBeLessThan(0);
expect(adapter.compareTime(moment([...aDate, 1, 2, 3]), moment([...bDate, 1, 2, 3]))).toBe(0);
expect(
adapter.compareTime(moment([...aDate, 13, 0, 0]), moment([...bDate, 12, 0, 0])),
).toBeGreaterThan(0);
expect(
adapter.compareTime(moment([...aDate, 12, 50, 11]), moment([...bDate, 12, 50, 10])),
).toBeGreaterThan(0);
expect(
adapter.compareTime(moment([...aDate, 13, 0, 0]), moment([...bDate, 10, 59, 59])),
).toBeGreaterThan(0);
});
it('should add milliseconds to a date', () => {
const amount = 20;
const initial = moment([2024, JAN, 1, 12, 34, 56]);
const result = adapter.addSeconds(initial, amount);
expect(result).not.toBe(initial);
expect(result.valueOf() - initial.valueOf()).toBe(amount * 1000);
});
});
describe('MomentDateAdapter with MAT_DATE_LOCALE override', () => {
let adapter: MomentDateAdapter;
beforeEach(() => {
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 21504,
"start_byte": 14407,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts"
}
|
components/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts_21506_24627
|
stBed.configureTestingModule({
imports: [MomentDateModule],
providers: [{provide: MAT_DATE_LOCALE, useValue: 'ja-JP'}],
});
adapter = TestBed.inject(DateAdapter) as MomentDateAdapter;
});
it('should take the default locale id from the MAT_DATE_LOCALE injection token', () => {
expect(adapter.format(moment([2017, JAN, 2]), 'll')).toEqual('2017年1月2日');
});
});
describe('MomentDateAdapter with LOCALE_ID override', () => {
let adapter: MomentDateAdapter;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MomentDateModule],
providers: [{provide: LOCALE_ID, useValue: 'fr'}],
});
adapter = TestBed.inject(DateAdapter) as MomentDateAdapter;
});
it('should take the default locale id from the LOCALE_ID injection token', () => {
expect(adapter.format(moment([2017, JAN, 2]), 'll')).toEqual('2 janv. 2017');
});
});
describe('MomentDateAdapter with MAT_MOMENT_DATE_ADAPTER_OPTIONS override', () => {
let adapter: MomentDateAdapter;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MomentDateModule],
providers: [
{
provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS,
useValue: {useUtc: true},
},
],
});
adapter = TestBed.inject(DateAdapter) as MomentDateAdapter;
});
describe('use UTC', () => {
it('should create Moment date in UTC', () => {
expect(adapter.createDate(2017, JAN, 5).isUtc()).toBe(true);
});
it('should create today in UTC', () => {
expect(adapter.today().isUtc()).toBe(true);
});
it('should parse dates to UTC', () => {
expect(adapter.parse('1/2/2017', 'MM/DD/YYYY')!.isUtc()).toBe(true);
});
it('should return UTC date when deserializing', () => {
expect(adapter.deserialize('1985-04-12T23:20:50.52Z')!.isUtc()).toBe(true);
});
});
describe('strict mode', () => {
beforeEach(() => {
TestBed.resetTestingModule();
TestBed.configureTestingModule({
imports: [MomentDateModule],
providers: [
{
provide: MAT_MOMENT_DATE_ADAPTER_OPTIONS,
useValue: {
strict: true,
},
},
],
});
adapter = TestBed.inject(DateAdapter) as MomentDateAdapter;
});
it('should detect valid strings according to given format', () => {
expect(adapter.parse('1/2/2017', 'D/M/YYYY')!.format('l')).toEqual(
moment([2017, FEB, 1]).format('l'),
);
expect(adapter.parse('February 1, 2017', 'MMMM D, YYYY')!.format('l')).toEqual(
moment([2017, FEB, 1]).format('l'),
);
});
it('should detect invalid strings according to given format', () => {
expect(adapter.parse('2017-01-01', 'MM/DD/YYYY')!.isValid()).toBe(false);
expect(adapter.parse('1/2/2017', 'MM/DD/YYYY')!.isValid()).toBe(false);
expect(adapter.parse('Jan 5, 2017', 'MMMM D, YYYY')!.isValid()).toBe(false);
});
});
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 24627,
"start_byte": 21506,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/adapter/moment-date-adapter.spec.ts"
}
|
components/src/material-moment-adapter/schematics/BUILD.bazel_0_909
|
load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin")
load("//tools:defaults.bzl", "pkg_npm", "ts_library")
package(default_visibility = ["//visibility:public"])
copy_to_bin(
name = "schematics_assets",
srcs = glob(["**/*.json"]),
)
ts_library(
name = "schematics",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
# Schematics can not yet run in ESM module. For now we continue to use CommonJS.
# TODO(ESM): remove this once the Angular CLI supports ESM schematics.
devmode_module = "commonjs",
prodmode_module = "commonjs",
deps = [
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
],
)
# This package is intended to be combined into the main @angular/material-moment-adapter package as a dep.
pkg_npm(
name = "npm_package",
deps = [
":schematics",
":schematics_assets",
],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 909,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/schematics/BUILD.bazel"
}
|
components/src/material-moment-adapter/schematics/ng-add/index.ts_0_455
|
/**
* @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 {Rule} from '@angular-devkit/schematics';
export default function (): Rule {
// Noop schematic so the CLI doesn't throw if users try to `ng add` this package.
// Also allows us to add more functionality in the future.
return () => {};
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 455,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-moment-adapter/schematics/ng-add/index.ts"
}
|
components/src/components-examples/example-data.ts_0_1322
|
// The example-module file will be auto-generated. As soon as the
// examples are being compiled, the module file will be generated.
import {EXAMPLE_COMPONENTS} from './example-module';
/**
* Example data with information about component name, selector, files used in
* example, and path to examples.
*/
export class ExampleData {
/** Description of the example. */
description: string;
/** List of files that are part of this example. */
exampleFiles: string[];
/** Selector name of the example component. */
selectorName: string;
/** Name of the file that contains the example component. */
indexFilename: string;
/** Names of the components being used in this example. */
componentNames: string[];
constructor(example: string) {
if (!example || !EXAMPLE_COMPONENTS.hasOwnProperty(example)) {
return;
}
const {componentName, files, selector, primaryFile, additionalComponents, title} =
EXAMPLE_COMPONENTS[example];
const exampleName = example.replace(/(?:^\w|\b\w)/g, letter => letter.toUpperCase());
this.exampleFiles = files;
this.selectorName = selector;
this.indexFilename = primaryFile;
this.description = title || exampleName.replace(/[\-]+/g, ' ') + ' Example';
this.componentNames = [componentName, ...additionalComponents];
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1322,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/example-data.ts"
}
|
components/src/components-examples/public-api.ts_0_200
|
export * from './example-data';
// The example-module file will be auto-generated. As soon as the
// examples are being compiled, the module file will be generated.
export * from './example-module';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 200,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/public-api.ts"
}
|
components/src/components-examples/config.bzl_0_3134
|
ALL_EXAMPLES = [
# TODO(devversion): try to have for each entry-point a bazel package so that
# we can automate this using the "package.bzl" variables. Currently generated
# with "bazel query 'kind("ng_module", //src/components-examples/...:*)' --output="label"
"//src/components-examples/material/tree",
"//src/components-examples/material/tooltip",
"//src/components-examples/material/toolbar",
"//src/components-examples/material/tabs",
"//src/components-examples/material/table",
"//src/components-examples/material/stepper",
"//src/components-examples/material/sort",
"//src/components-examples/material/snack-bar",
"//src/components-examples/material/slider",
"//src/components-examples/material/slide-toggle",
"//src/components-examples/material/sidenav",
"//src/components-examples/material/select",
"//src/components-examples/material/radio",
"//src/components-examples/material/progress-spinner",
"//src/components-examples/material/progress-bar",
"//src/components-examples/material/paginator",
"//src/components-examples/material/menu",
"//src/components-examples/material/list",
"//src/components-examples/material/input",
"//src/components-examples/material/icon",
"//src/components-examples/material/grid-list",
"//src/components-examples/material/form-field",
"//src/components-examples/material/expansion",
"//src/components-examples/material/divider",
"//src/components-examples/material/dialog",
"//src/components-examples/material/datepicker",
"//src/components-examples/material/core",
"//src/components-examples/material/chips",
"//src/components-examples/material/checkbox",
"//src/components-examples/material/card",
"//src/components-examples/material/button-toggle",
"//src/components-examples/material/button",
"//src/components-examples/material/bottom-sheet",
"//src/components-examples/material/badge",
"//src/components-examples/material/autocomplete",
"//src/components-examples/material/timepicker",
"//src/components-examples/material-experimental/column-resize",
"//src/components-examples/material-experimental/popover-edit",
"//src/components-examples/material-experimental/selection",
"//src/components-examples/cdk/tree",
"//src/components-examples/cdk/text-field",
"//src/components-examples/cdk/table",
"//src/components-examples/cdk/stepper",
"//src/components-examples/cdk/scrolling",
"//src/components-examples/cdk/portal",
"//src/components-examples/cdk/accordion",
"//src/components-examples/cdk/platform",
"//src/components-examples/cdk/drag-drop",
"//src/components-examples/cdk/clipboard",
"//src/components-examples/cdk/a11y",
"//src/components-examples/cdk/layout",
"//src/components-examples/cdk/listbox",
"//src/components-examples/cdk/menu",
"//src/components-examples/cdk/overlay",
"//src/components-examples/cdk/dialog",
"//src/components-examples/cdk-experimental/popover-edit",
"//src/components-examples/cdk-experimental/selection",
]
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3134,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/config.bzl"
}
|
components/src/components-examples/example-module.d.ts_0_678
|
interface LiveExample {
/** Title of the example. */
title: string;
/** Name of the example component. */
componentName: string;
/** Selector to match the component of this example. */
selector: string;
/** Name of the primary file of this example. */
primaryFile: string;
/** List of files which are part of the example. */
files: string[];
/** Path to the directory containing the example. */
packagePath: string;
/** List of additional components which are part of the example. */
additionalComponents: string[];
/** Path from which to import the xample. */
importPath: string;
}
export const EXAMPLE_COMPONENTS: {[id: string]: LiveExample};
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 678,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/example-module.d.ts"
}
|
components/src/components-examples/BUILD.bazel_0_2883
|
load("//tools:defaults.bzl", "ng_module", "ng_package")
load("//tools/highlight-files:index.bzl", "highlight_files")
load("//tools/package-docs-content:index.bzl", "package_docs_content")
load(":config.bzl", "ALL_EXAMPLES")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "components-examples",
srcs = glob(["*.ts"]) + [":example-module.ts"],
deps = ALL_EXAMPLES,
)
filegroup(
name = "example-source-files",
srcs = ["%s:source-files" % pkg for pkg in ALL_EXAMPLES],
)
highlight_files(
name = "examples-highlighted",
srcs = [":example-source-files"],
)
package_docs_content(
name = "docs-content",
srcs = {
# We want to package the guides in to the docs content. These will be displayed
# in the documentation.
"//guides": "guides",
# Package the overviews for "@angular/material" and "@angular/cdk" into the docs content
"//src/cdk:overviews": "overviews/cdk",
"//src/material:overviews": "overviews/material",
# Package the extracted token information into the docs content.
"//src/material:tokens": "tokens/material",
# Package the API docs for the Material and CDK package into the docs-content
"//src:api-docs": "api-docs",
# In order to be able to run examples in StackBlitz, we also want to package the
# plain source files into the docs-content.
":example-source-files": "examples-source",
# For the live-examples in our docs, we want to package the highlighted files
# into the docs content. These will be used to show the source code for examples.
# Note: `examples-highlighted` is a tree artifact that we want to store as is
# in the docs-content. Hence there is no target section name.
":examples-highlighted": "",
},
)
ng_package(
name = "npm_package",
srcs = ["package.json"],
# this is a workaround to store a tree artifact in the ng_package.
# ng_package does not properly handle tree artifacts currently so we escalate to nested_packages
nested_packages = [":docs-content"],
tags = ["docs-package"],
deps = [":components-examples"] + ALL_EXAMPLES,
)
genrule(
name = "example-module",
srcs = [":example-source-files"],
outs = [
"example-module.ts",
"_example_module.MF",
],
cmd = """
# Create source file manifest
echo "$(execpaths //src/components-examples:example-source-files)" \
> $(execpath _example_module.MF)
# Run the bazel entry-point for generating the example module.
./$(execpath //tools/example-module:bazel-bin) \
"$(execpath _example_module.MF)" \
"$(execpath example-module.ts)" \
"$$PWD/src/components-examples"
""",
output_to_bindir = True,
tools = ["//tools/example-module:bazel-bin"],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2883,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/BUILD.bazel"
}
|
components/src/components-examples/index.ts_0_30
|
export * from './public-api';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 30,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/index.ts"
}
|
components/src/components-examples/cdk/tree/tree-data.ts_0_1562
|
/** Flat node with expandable and level information */
export interface FlatFoodNode {
expandable: boolean;
name: string;
level: number;
isExpanded?: boolean;
}
export const FLAT_DATA: FlatFoodNode[] = [
{
name: 'Fruit',
expandable: true,
level: 0,
},
{
name: 'Apple',
expandable: false,
level: 1,
},
{
name: 'Banana',
expandable: false,
level: 1,
},
{
name: 'Fruit loops',
expandable: false,
level: 1,
},
{
name: 'Vegetables',
expandable: true,
level: 0,
},
{
name: 'Green',
expandable: true,
level: 1,
},
{
name: 'Broccoli',
expandable: false,
level: 2,
},
{
name: 'Brussels sprouts',
expandable: false,
level: 2,
},
{
name: 'Orange',
expandable: true,
level: 1,
},
{
name: 'Pumpkins',
expandable: false,
level: 2,
},
{
name: 'Carrots',
expandable: false,
level: 2,
},
];
/**
* Food data with nested structure.
* Each node has a name and an optional list of children.
*/
export interface NestedFoodNode {
name: string;
children?: NestedFoodNode[];
}
export const NESTED_DATA: NestedFoodNode[] = [
{
name: 'Fruit',
children: [{name: 'Apple'}, {name: 'Banana'}, {name: 'Fruit loops'}],
},
{
name: 'Vegetables',
children: [
{
name: 'Green',
children: [{name: 'Broccoli'}, {name: 'Brussels sprouts'}],
},
{
name: 'Orange',
children: [{name: 'Pumpkins'}, {name: 'Carrots'}],
},
],
},
];
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1562,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/tree-data.ts"
}
|
components/src/components-examples/cdk/tree/BUILD.bazel_0_509
|
load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "tree",
srcs = glob(["**/*.ts"]),
assets = glob([
"**/*.html",
"**/*.css",
]),
deps = [
"//src/cdk/tree",
"//src/material/button",
"//src/material/icon",
"//src/material/progress-spinner",
],
)
filegroup(
name = "source-files",
srcs = glob([
"**/*.html",
"**/*.css",
"**/*.ts",
]),
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 509,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/BUILD.bazel"
}
|
components/src/components-examples/cdk/tree/index.ts_0_849
|
export {CdkTreeFlatChildrenAccessorExample} from './cdk-tree-flat-children-accessor/cdk-tree-flat-children-accessor-example';
export {CdkTreeFlatLevelAccessorExample} from './cdk-tree-flat-level-accessor/cdk-tree-flat-level-accessor-example';
export {CdkTreeFlatExample} from './cdk-tree-flat/cdk-tree-flat-example';
export {CdkTreeNestedLevelAccessorExample} from './cdk-tree-nested-level-accessor/cdk-tree-nested-level-accessor-example';
export {CdkTreeNestedChildrenAccessorExample} from './cdk-tree-nested-children-accessor/cdk-tree-nested-children-accessor-example';
export {CdkTreeNestedExample} from './cdk-tree-nested/cdk-tree-nested-example';
export {CdkTreeComplexExample} from './cdk-tree-complex/cdk-tree-complex-example';
export {CdkTreeCustomKeyManagerExample} from './cdk-tree-custom-key-manager/cdk-tree-custom-key-manager-example';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 849,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/index.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-flat-level-accessor/cdk-tree-flat-level-accessor-example.ts_0_1607
|
import {ArrayDataSource} from '@angular/cdk/collections';
import {CdkTree, CdkTreeModule} from '@angular/cdk/tree';
import {ChangeDetectionStrategy, Component, ViewChild} from '@angular/core';
import {MatButtonModule} from '@angular/material/button';
import {MatIconModule} from '@angular/material/icon';
import {FlatFoodNode, FLAT_DATA} from '../tree-data';
/**
* @title Tree with flat nodes
*/
@Component({
selector: 'cdk-tree-flat-level-accessor-example',
templateUrl: 'cdk-tree-flat-level-accessor-example.html',
styleUrls: ['cdk-tree-flat-level-accessor-example.css'],
imports: [CdkTreeModule, MatButtonModule, MatIconModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkTreeFlatLevelAccessorExample {
@ViewChild(CdkTree)
tree: CdkTree<FlatFoodNode>;
levelAccessor = (dataNode: FlatFoodNode) => dataNode.level;
dataSource = new ArrayDataSource(FLAT_DATA);
hasChild = (_: number, node: FlatFoodNode) => node.expandable;
getParentNode(node: FlatFoodNode) {
const nodeIndex = FLAT_DATA.indexOf(node);
// Determine the node's parent by finding the first preceding node that's
// one level shallower.
for (let i = nodeIndex - 1; i >= 0; i--) {
if (FLAT_DATA[i].level === node.level - 1) {
return FLAT_DATA[i];
}
}
return null;
}
shouldRender(node: FlatFoodNode): boolean {
// This node should render if it is a root node or if all of its ancestors are expanded.
const parent = this.getParentNode(node);
return !parent || (!!this.tree?.isExpanded(parent) && this.shouldRender(parent));
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1607,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-flat-level-accessor/cdk-tree-flat-level-accessor-example.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-flat-level-accessor/cdk-tree-flat-level-accessor-example.html_0_1334
|
<cdk-tree #tree [dataSource]="dataSource" [levelAccessor]="levelAccessor">
<!-- This is the tree node template for leaf nodes -->
<cdk-tree-node *cdkTreeNodeDef="let node" cdkTreeNodePadding
[style.display]="shouldRender(node) ? 'flex' : 'none'"
[isDisabled]="!shouldRender(node)"
class="example-tree-node">
<!-- use a disabled button to provide padding for tree leaf -->
<button mat-icon-button disabled></button>
{{node.name}}
</cdk-tree-node>
<!-- This is the tree node template for expandable nodes -->
<cdk-tree-node *cdkTreeNodeDef="let node; when: hasChild" cdkTreeNodePadding
cdkTreeNodeToggle
[cdkTreeNodeTypeaheadLabel]="node.name"
[style.display]="shouldRender(node) ? 'flex' : 'none'"
[isDisabled]="!shouldRender(node)"
[isExpandable]="node.expandable"
class="example-tree-node">
<button mat-icon-button cdkTreeNodeToggle
[attr.aria-label]="'Toggle ' + node.name"
[style.visibility]="node.expandable ? 'visible' : 'hidden'">
<mat-icon class="mat-icon-rtl-mirror">
{{tree.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.name}}
</cdk-tree-node>
</cdk-tree>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1334,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-flat-level-accessor/cdk-tree-flat-level-accessor-example.html"
}
|
components/src/components-examples/cdk/tree/cdk-tree-flat-level-accessor/cdk-tree-flat-level-accessor-example.css_0_63
|
.example-tree-node {
display: flex;
align-items: center;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 63,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-flat-level-accessor/cdk-tree-flat-level-accessor-example.css"
}
|
components/src/components-examples/cdk/tree/cdk-tree-complex/cdk-tree-complex-example.css_0_58
|
cdk-tree-node {
display: flex;
align-items: center;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 58,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-complex/cdk-tree-complex-example.css"
}
|
components/src/components-examples/cdk/tree/cdk-tree-complex/cdk-tree-complex-example.ts_0_3114
|
import {CdkTreeModule} from '@angular/cdk/tree';
import {CommonModule} from '@angular/common';
import {ChangeDetectionStrategy, Component, OnInit} from '@angular/core';
import {MatButtonModule} from '@angular/material/button';
import {MatIconModule} from '@angular/material/icon';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {BehaviorSubject, Observable, combineLatest, of as observableOf} from 'rxjs';
import {delay, map, shareReplay} from 'rxjs/operators';
interface BackendData {
id: string;
name: string;
parent?: string;
children?: string[];
}
const TREE_DATA: Map<string, BackendData> = new Map(
[
{
id: '1',
name: 'Fruit',
children: ['1-1', '1-2', '1-3'],
},
{id: '1-1', name: 'Apple', parent: '1'},
{id: '1-2', name: 'Banana', parent: '1'},
{id: '1-3', name: 'Fruit Loops', parent: '1'},
{
id: '2',
name: 'Vegetables',
children: ['2-1', '2-2'],
},
{
id: '2-1',
name: 'Green',
parent: '2',
children: ['2-1-1', '2-1-2'],
},
{
id: '2-2',
name: 'Orange',
parent: '2',
children: ['2-2-1', '2-2-2'],
},
{id: '2-1-1', name: 'Broccoli', parent: '2-1'},
{id: '2-1-2', name: 'Brussel sprouts', parent: '2-1'},
{id: '2-2-1', name: 'Pumpkins', parent: '2-2'},
{id: '2-2-2', name: 'Carrots', parent: '2-2'},
].map(datum => [datum.id, datum]),
);
class FakeDataBackend {
private _getRandomDelayTime() {
// anywhere from 100 to 500ms.
return Math.floor(Math.random() * 400) + 100;
}
getChildren(id: string): Observable<BackendData[]> {
// first, find the specified ID in our tree
const item = TREE_DATA.get(id);
const children = item?.children ?? [];
return observableOf(children.map(childId => TREE_DATA.get(childId)!)).pipe(
delay(this._getRandomDelayTime()),
);
}
getRoots(): Observable<BackendData[]> {
return observableOf([...TREE_DATA.values()].filter(datum => !datum.parent)).pipe(
delay(this._getRandomDelayTime()),
);
}
}
type LoadingState = 'INIT' | 'LOADING' | 'LOADED';
interface RawData {
id: string;
name: string;
parentId?: string;
childrenIds?: string[];
childrenLoading: LoadingState;
}
class TransformedData {
constructor(public raw: RawData) {}
areChildrenLoading() {
return this.raw.childrenLoading === 'LOADING';
}
isExpandable() {
return (
(this.raw.childrenLoading === 'INIT' || this.raw.childrenLoading === 'LOADED') &&
!!this.raw.childrenIds?.length
);
}
isLeaf() {
return !this.isExpandable() && !this.areChildrenLoading();
}
}
interface State {
rootIds: string[];
rootsLoading: LoadingState;
allData: Map<string, RawData>;
dataLoading: Map<string, LoadingState>;
}
type ObservedValueOf<T> = T extends Observable<infer U> ? U : never;
type ObservedValuesOf<T extends readonly Observable<unknown>[]> = {
[K in keyof T]: ObservedValueOf<T[K]>;
};
type TransformFn<T extends readonly Observable<unknown>[], U> = (
...args: [...ObservedValuesOf<T>, State]
) => U;
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3114,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-complex/cdk-tree-complex-example.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-complex/cdk-tree-complex-example.ts_3116_8763
|
class ComplexDataStore {
private readonly _backend = new FakeDataBackend();
private _state = new BehaviorSubject<State>({
rootIds: [],
rootsLoading: 'INIT',
allData: new Map(),
dataLoading: new Map(),
});
private readonly _rootIds = this.select(state => state.rootIds);
private readonly _allData = this.select(state => state.allData);
private readonly _loadingData = this.select(state => state.dataLoading);
private readonly _rootsLoadingState = this.select(state => state.rootsLoading);
readonly areRootsLoading = this.select(
this._rootIds,
this._loadingData,
this._rootsLoadingState,
(rootIds, loading, rootsLoading) =>
rootsLoading !== 'LOADED' || rootIds.some(id => loading.get(id) !== 'LOADED'),
);
readonly roots = this.select(
this.areRootsLoading,
this._rootIds,
this._allData,
(rootsLoading, rootIds, data) => {
if (rootsLoading) {
return [];
}
return this._getDataByIds(rootIds, data);
},
);
getChildren(parentId: string) {
return this.select(this._allData, this._loadingData, (data, loading) => {
const parentData = data.get(parentId);
if (parentData?.childrenLoading !== 'LOADED') {
return [];
}
const childIds = parentData.childrenIds ?? [];
if (childIds.some(id => loading.get(id) !== 'LOADED')) {
return [];
}
return this._getDataByIds(childIds, data);
});
}
loadRoots() {
this._setRootsLoading();
this._backend.getRoots().subscribe(roots => {
this._setRoots(roots);
});
}
loadChildren(parentId: string) {
this._setChildrenLoading(parentId);
this._backend.getChildren(parentId).subscribe(children => {
this._addLoadedData(parentId, children);
});
}
private _setRootsLoading() {
this._state.next({
...this._state.value,
rootsLoading: 'LOADING',
});
}
private _setRoots(roots: BackendData[]) {
const currentState = this._state.value;
this._state.next({
...currentState,
rootIds: roots.map(root => root.id),
rootsLoading: 'LOADED',
...this._addData(currentState, roots),
});
}
private _setChildrenLoading(parentId: string) {
const currentState = this._state.value;
const parentData = currentState.allData.get(parentId);
this._state.next({
...currentState,
allData: new Map([
...currentState.allData,
...(parentData ? ([[parentId, {...parentData, childrenLoading: 'LOADING'}]] as const) : []),
]),
dataLoading: new Map([
...currentState.dataLoading,
...(parentData?.childrenIds?.map(childId => [childId, 'LOADING'] as const) ?? []),
]),
});
}
private _addLoadedData(parentId: string, childData: BackendData[]) {
const currentState = this._state.value;
this._state.next({
...currentState,
...this._addData(currentState, childData, parentId),
});
}
private _addData(
{allData, dataLoading}: State,
data: BackendData[],
parentId?: string,
): Pick<State, 'allData' | 'dataLoading'> {
const parentData = parentId && allData.get(parentId);
const allChildren = data.flatMap(datum => datum.children ?? []);
return {
allData: new Map([
...allData,
...data.map(datum => {
return [
datum.id,
{
id: datum.id,
name: datum.name,
parentId,
childrenIds: datum.children,
childrenLoading: 'INIT',
},
] as const;
}),
...(parentData ? ([[parentId, {...parentData, childrenLoading: 'LOADED'}]] as const) : []),
]),
dataLoading: new Map([
...dataLoading,
...data.map(datum => [datum.id, 'LOADED'] as const),
...allChildren.map(childId => [childId, 'INIT'] as const),
]),
};
}
private _getDataByIds(ids: string[], data: State['allData']) {
return ids
.map(id => data.get(id))
.filter(<T>(item: T | undefined): item is T => !!item)
.map(datum => new TransformedData(datum));
}
select<T extends readonly Observable<unknown>[], U>(
...sourcesAndTransform: [...T, TransformFn<T, U>]
) {
const sources = sourcesAndTransform.slice(0, -1) as unknown as T;
const transformFn = sourcesAndTransform[sourcesAndTransform.length - 1] as TransformFn<T, U>;
return combineLatest([...sources, this._state]).pipe(
map(args => transformFn(...(args as [...ObservedValuesOf<T>, State]))),
shareReplay({refCount: true, bufferSize: 1}),
);
}
}
/**
* @title Complex example making use of the redux pattern.
*/
@Component({
selector: 'cdk-tree-complex-example',
templateUrl: 'cdk-tree-complex-example.html',
styleUrls: ['cdk-tree-complex-example.css'],
imports: [CdkTreeModule, MatButtonModule, MatIconModule, CommonModule, MatProgressSpinnerModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkTreeComplexExample implements OnInit {
private readonly _dataStore = new ComplexDataStore();
areRootsLoading = this._dataStore.areRootsLoading;
roots = this._dataStore.roots;
getChildren = (node: TransformedData) => this._dataStore.getChildren(node.raw.id);
trackBy = (index: number, node: TransformedData) => this.expansionKey(node);
expansionKey = (node: TransformedData) => node.raw.id;
ngOnInit() {
this._dataStore.loadRoots();
}
onExpand(node: TransformedData, expanded: boolean) {
if (expanded) {
// Only perform a load on expansion.
this._dataStore.loadChildren(node.raw.id);
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 8763,
"start_byte": 3116,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-complex/cdk-tree-complex-example.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-complex/cdk-tree-complex-example.html_0_1218
|
@if (areRootsLoading | async) {
<mat-spinner></mat-spinner>
} @else {
<cdk-tree
#tree
[dataSource]="roots"
[childrenAccessor]="getChildren"
[trackBy]="trackBy"
[expansionKey]="expansionKey">
<cdk-tree-node
*cdkTreeNodeDef="let node"
cdkTreeNodePadding
[cdkTreeNodeTypeaheadLabel]="node.raw.name"
[isExpandable]="node.isExpandable()"
(expandedChange)="onExpand(node, $event)">
<!-- Spinner when node is loading children; this replaces the expand button. -->
@if (node.areChildrenLoading()) {
<mat-spinner diameter="48" mode="indeterminate"></mat-spinner>
}
@if (!node.areChildrenLoading() && node.isExpandable()) {
<button
mat-icon-button
cdkTreeNodeToggle
[attr.aria-label]="'Toggle ' + node.raw.name">
<mat-icon class="mat-icon-rtl-mirror">
{{tree.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
}
<!-- Spacer for leaf nodes -->
@if (node.isLeaf()) {
<div class="toggle-spacer"></div>
}
<span>{{node.raw.name}}</span>
</cdk-tree-node>
</cdk-tree>
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1218,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-complex/cdk-tree-complex-example.html"
}
|
components/src/components-examples/cdk/tree/cdk-tree-nested/cdk-tree-nested-example.html_0_1133
|
<cdk-tree [dataSource]="dataSource" [treeControl]="treeControl">
<!-- This is the tree node template for leaf nodes -->
<cdk-nested-tree-node #treeNode="cdkNestedTreeNode" *cdkTreeNodeDef="let node"
class="example-tree-node">
<!-- use a disabled button to provide padding for tree leaf -->
<button mat-icon-button disabled></button>
{{node.name}}
</cdk-nested-tree-node>
<!-- This is the tree node template for expandable nodes -->
<cdk-nested-tree-node #treeNode="cdkNestedTreeNode"
[cdkTreeNodeTypeaheadLabel]="node.name"
*cdkTreeNodeDef="let node; when: hasChild"
isExpandable
class="example-tree-node">
<button
mat-icon-button
class="example-toggle"
[attr.aria-label]="'Toggle ' + node.name"
cdkTreeNodeToggle>
<mat-icon class="mat-icon-rtl-mirror">
{{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.name}}
<div [class.example-tree-invisible]="!treeControl.isExpanded(node)">
<ng-container cdkTreeNodeOutlet></ng-container>
</div>
</cdk-nested-tree-node>
</cdk-tree>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1133,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-nested/cdk-tree-nested-example.html"
}
|
components/src/components-examples/cdk/tree/cdk-tree-nested/cdk-tree-nested-example.css_0_300
|
.example-tree-invisible {
display: none;
}
.example-tree ul,
.example-tree li {
margin-top: 0;
margin-bottom: 0;
list-style-type: none;
}
.example-tree-node {
display: block;
}
.example-tree-node .example-tree-node {
padding-left: 40px;
}
.example-toggle {
vertical-align: middle;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 300,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-nested/cdk-tree-nested-example.css"
}
|
components/src/components-examples/cdk/tree/cdk-tree-nested/cdk-tree-nested-example.ts_0_1418
|
import {ChangeDetectionStrategy, Component} from '@angular/core';
import {ArrayDataSource} from '@angular/cdk/collections';
import {NestedTreeControl, CdkTreeModule} from '@angular/cdk/tree';
import {MatIconModule} from '@angular/material/icon';
import {MatButtonModule} from '@angular/material/button';
/**
* Food data with nested structure.
* Each node has a name and an optional list of children.
*/
interface FoodNode {
name: string;
children?: FoodNode[];
}
const TREE_DATA: FoodNode[] = [
{
name: 'Fruit',
children: [{name: 'Apple'}, {name: 'Banana'}, {name: 'Fruit loops'}],
},
{
name: 'Vegetables',
children: [
{
name: 'Green',
children: [{name: 'Broccoli'}, {name: 'Brussels sprouts'}],
},
{
name: 'Orange',
children: [{name: 'Pumpkins'}, {name: 'Carrots'}],
},
],
},
];
/**
* @title Tree with nested nodes
*/
@Component({
selector: 'cdk-tree-nested-example',
templateUrl: 'cdk-tree-nested-example.html',
styleUrl: 'cdk-tree-nested-example.css',
imports: [CdkTreeModule, MatButtonModule, MatIconModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkTreeNestedExample {
treeControl = new NestedTreeControl<FoodNode>(node => node.children);
dataSource = new ArrayDataSource(TREE_DATA);
hasChild = (_: number, node: FoodNode) => !!node.children && node.children.length > 0;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1418,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-nested/cdk-tree-nested-example.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-nested-children-accessor/cdk-tree-nested-children-accessor-example.html_0_1135
|
<cdk-tree #tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
<!-- This is the tree node template for leaf nodes -->
<cdk-nested-tree-node #treeNode="cdkNestedTreeNode" *cdkTreeNodeDef="let node"
class="example-tree-node">
<!-- use a disabled button to provide padding for tree leaf -->
<button mat-icon-button disabled></button>
{{node.name}}
</cdk-nested-tree-node>
<!-- This is the tree node template for expandable nodes -->
<cdk-nested-tree-node #treeNode="cdkNestedTreeNode"
*cdkTreeNodeDef="let node; when: hasChild"
[cdkTreeNodeTypeaheadLabel]="node.name"
isExpandable
class="example-tree-node">
<button
mat-icon-button
class="example-toggle"
[attr.aria-label]="'Toggle ' + node.name"
cdkTreeNodeToggle>
<mat-icon class="mat-icon-rtl-mirror">
{{tree.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.name}}
<div [class.example-tree-invisible]="!tree.isExpanded(node)">
<ng-container cdkTreeNodeOutlet></ng-container>
</div>
</cdk-nested-tree-node>
</cdk-tree>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1135,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-nested-children-accessor/cdk-tree-nested-children-accessor-example.html"
}
|
components/src/components-examples/cdk/tree/cdk-tree-nested-children-accessor/cdk-tree-nested-children-accessor-example.ts_0_1823
|
import {ArrayDataSource} from '@angular/cdk/collections';
import {CdkTree, CdkTreeModule} from '@angular/cdk/tree';
import {ChangeDetectionStrategy, Component, ViewChild} from '@angular/core';
import {MatButtonModule} from '@angular/material/button';
import {MatIconModule} from '@angular/material/icon';
import {NestedFoodNode, NESTED_DATA} from '../tree-data';
function flattenNodes(nodes: NestedFoodNode[]): NestedFoodNode[] {
const flattenedNodes = [];
for (const node of nodes) {
flattenedNodes.push(node);
if (node.children) {
flattenedNodes.push(...flattenNodes(node.children));
}
}
return flattenedNodes;
}
/**
* @title Tree with nested nodes using childAccessor
*/
@Component({
selector: 'cdk-tree-nested-children-accessor-example',
templateUrl: 'cdk-tree-nested-children-accessor-example.html',
styleUrls: ['cdk-tree-nested-children-accessor-example.css'],
imports: [CdkTreeModule, MatButtonModule, MatIconModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkTreeNestedChildrenAccessorExample {
@ViewChild(CdkTree) tree: CdkTree<NestedFoodNode>;
childrenAccessor = (dataNode: NestedFoodNode) => dataNode.children ?? [];
dataSource = new ArrayDataSource(NESTED_DATA);
hasChild = (_: number, node: NestedFoodNode) => !!node.children && node.children.length > 0;
getParentNode(node: NestedFoodNode) {
for (const parent of flattenNodes(NESTED_DATA)) {
if (parent.children?.includes(node)) {
return parent;
}
}
return null;
}
shouldRender(node: NestedFoodNode): boolean {
// This node should render if it is a root node or if all of its ancestors are expanded.
const parent = this.getParentNode(node);
return !parent || (!!this.tree?.isExpanded(parent) && this.shouldRender(parent));
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1823,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-nested-children-accessor/cdk-tree-nested-children-accessor-example.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-nested-children-accessor/cdk-tree-nested-children-accessor-example.css_0_321
|
.example-tree-invisible {
display: none;
}
.example-tree ul,
.example-tree li {
margin-top: 0;
margin-bottom: 0;
list-style-type: none;
}
.example-tree-node {
display: block;
line-height: 40px;
}
.example-tree-node .example-tree-node {
padding-left: 40px;
}
.example-toggle {
vertical-align: middle;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 321,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-nested-children-accessor/cdk-tree-nested-children-accessor-example.css"
}
|
components/src/components-examples/cdk/tree/cdk-tree-flat-children-accessor/cdk-tree-flat-children-accessor-example.html_0_1245
|
<cdk-tree #tree [dataSource]="dataSource" [childrenAccessor]="childrenAccessor">
<!-- This is the tree node template for leaf nodes -->
<cdk-tree-node *cdkTreeNodeDef="let node" cdkTreeNodePadding
[style.display]="shouldRender(node) ? 'flex' : 'none'"
[isDisabled]="!shouldRender(node)"
class="example-tree-node">
<!-- use a disabled button to provide padding for tree leaf -->
<button mat-icon-button disabled></button>
{{node.name}}
</cdk-tree-node>
<!-- This is the tree node template for expandable nodes -->
<cdk-tree-node *cdkTreeNodeDef="let node; when: hasChild" cdkTreeNodePadding
cdkTreeNodeToggle
[cdkTreeNodeTypeaheadLabel]="node.name"
[style.display]="shouldRender(node) ? 'flex' : 'none'"
[isDisabled]="!shouldRender(node)"
[isExpandable]="true"
class="example-tree-node">
<button mat-icon-button cdkTreeNodeToggle [attr.aria-label]="'Toggle ' + node.name">
<mat-icon class="mat-icon-rtl-mirror">
{{tree.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.name}}
</cdk-tree-node>
</cdk-tree>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1245,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-flat-children-accessor/cdk-tree-flat-children-accessor-example.html"
}
|
components/src/components-examples/cdk/tree/cdk-tree-flat-children-accessor/cdk-tree-flat-children-accessor-example.ts_0_1836
|
import {ArrayDataSource} from '@angular/cdk/collections';
import {CdkTree, CdkTreeModule} from '@angular/cdk/tree';
import {ChangeDetectionStrategy, Component, ViewChild} from '@angular/core';
import {MatButtonModule} from '@angular/material/button';
import {MatIconModule} from '@angular/material/icon';
import {timer} from 'rxjs';
import {mapTo} from 'rxjs/operators';
import {NestedFoodNode, NESTED_DATA} from '../tree-data';
function flattenNodes(nodes: NestedFoodNode[]): NestedFoodNode[] {
const flattenedNodes = [];
for (const node of nodes) {
flattenedNodes.push(node);
if (node.children) {
flattenedNodes.push(...flattenNodes(node.children));
}
}
return flattenedNodes;
}
/**
* @title Tree with flat nodes
*/
@Component({
selector: 'cdk-tree-flat-children-accessor-example',
templateUrl: 'cdk-tree-flat-children-accessor-example.html',
styleUrls: ['cdk-tree-flat-children-accessor-example.css'],
imports: [CdkTreeModule, MatButtonModule, MatIconModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkTreeFlatChildrenAccessorExample {
@ViewChild(CdkTree)
tree!: CdkTree<NestedFoodNode>;
childrenAccessor = (dataNode: NestedFoodNode) => timer(100).pipe(mapTo(dataNode.children ?? []));
dataSource = new ArrayDataSource(NESTED_DATA);
hasChild = (_: number, node: NestedFoodNode) => !!node.children?.length;
getParentNode(node: NestedFoodNode) {
for (const parent of flattenNodes(NESTED_DATA)) {
if (parent.children?.includes(node)) {
return parent;
}
}
return null;
}
shouldRender(node: NestedFoodNode) {
let parent = this.getParentNode(node);
while (parent) {
if (!this.tree.isExpanded(parent)) {
return false;
}
parent = this.getParentNode(parent);
}
return true;
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1836,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-flat-children-accessor/cdk-tree-flat-children-accessor-example.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-flat-children-accessor/cdk-tree-flat-children-accessor-example.css_0_63
|
.example-tree-node {
display: flex;
align-items: center;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 63,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-flat-children-accessor/cdk-tree-flat-children-accessor-example.css"
}
|
components/src/components-examples/cdk/tree/cdk-tree-nested-level-accessor/cdk-tree-nested-level-accessor-example.css_0_321
|
.example-tree-invisible {
display: none;
}
.example-tree ul,
.example-tree li {
margin-top: 0;
margin-bottom: 0;
list-style-type: none;
}
.example-tree-node {
display: block;
line-height: 40px;
}
.example-tree-node .example-tree-node {
padding-left: 40px;
}
.example-toggle {
vertical-align: middle;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 321,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-nested-level-accessor/cdk-tree-nested-level-accessor-example.css"
}
|
components/src/components-examples/cdk/tree/cdk-tree-nested-level-accessor/cdk-tree-nested-level-accessor-example.ts_0_1634
|
import {ArrayDataSource} from '@angular/cdk/collections';
import {CdkTree, CdkTreeModule} from '@angular/cdk/tree';
import {ChangeDetectionStrategy, Component, ViewChild} from '@angular/core';
import {MatButtonModule} from '@angular/material/button';
import {MatIconModule} from '@angular/material/icon';
import {FLAT_DATA, FlatFoodNode} from '../tree-data';
/**
* @title Tree with nested nodes and level accessor
*/
@Component({
selector: 'cdk-tree-nested-level-accessor-example',
templateUrl: 'cdk-tree-nested-level-accessor-example.html',
styleUrls: ['cdk-tree-nested-level-accessor-example.css'],
imports: [CdkTreeModule, MatButtonModule, MatIconModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkTreeNestedLevelAccessorExample {
@ViewChild(CdkTree) tree: CdkTree<FlatFoodNode>;
levelAccessor = (dataNode: FlatFoodNode) => dataNode.level;
dataSource = new ArrayDataSource(FLAT_DATA);
hasChild = (_: number, node: FlatFoodNode) => node.expandable;
getParentNode(node: FlatFoodNode) {
const nodeIndex = FLAT_DATA.indexOf(node);
// Determine the node's parent by finding the first preceding node that's
// one level shallower.
for (let i = nodeIndex - 1; i >= 0; i--) {
if (FLAT_DATA[i].level === node.level - 1) {
return FLAT_DATA[i];
}
}
return null;
}
shouldRender(node: FlatFoodNode): boolean {
// This node should render if it is a root node or if all of its ancestors are expanded.
const parent = this.getParentNode(node);
return !parent || (!!this.tree?.isExpanded(parent) && this.shouldRender(parent));
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1634,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-nested-level-accessor/cdk-tree-nested-level-accessor-example.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-nested-level-accessor/cdk-tree-nested-level-accessor-example.html_0_1133
|
<cdk-tree #tree [dataSource]="dataSource" [levelAccessor]="levelAccessor">
<!-- This is the tree node template for leaf nodes -->
<cdk-nested-tree-node #treeNode="cdkNestedTreeNode" *cdkTreeNodeDef="let node"
class="example-tree-node">
<!-- use a disabled button to provide padding for tree leaf -->
<button mat-icon-button disabled></button>
{{node.name}}
</cdk-nested-tree-node>
<!-- This is the tree node template for expandable nodes -->
<cdk-nested-tree-node
#treeNode="cdkNestedTreeNode"
[cdkTreeNodeTypeaheadLabel]="node.name"
*cdkTreeNodeDef="let node; when: hasChild"
isExpandable
class="example-tree-node">
<button
mat-icon-button
class="example-toggle"
[attr.aria-label]="'Toggle ' + node.name"
cdkTreeNodeToggle>
<mat-icon class="mat-icon-rtl-mirror">
{{tree.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.name}}
<div [class.example-tree-invisible]="!tree.isExpanded(node)">
<ng-container cdkTreeNodeOutlet></ng-container>
</div>
</cdk-nested-tree-node>
</cdk-tree>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1133,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-nested-level-accessor/cdk-tree-nested-level-accessor-example.html"
}
|
components/src/components-examples/cdk/tree/cdk-tree-custom-key-manager/cdk-tree-custom-key-manager-example.css_0_63
|
.example-tree-node {
display: flex;
align-items: center;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 63,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-custom-key-manager/cdk-tree-custom-key-manager-example.css"
}
|
components/src/components-examples/cdk/tree/cdk-tree-custom-key-manager/cdk-tree-custom-key-manager-example.ts_0_1932
|
import {ChangeDetectionStrategy, Component, QueryList} from '@angular/core';
import {ArrayDataSource} from '@angular/cdk/collections';
import {coerceObservable} from '@angular/cdk/coercion/private';
import {FlatTreeControl, CdkTreeModule} from '@angular/cdk/tree';
import {MatIconModule} from '@angular/material/icon';
import {MatButtonModule} from '@angular/material/button';
import {
TREE_KEY_MANAGER,
TreeKeyManagerFactory,
TreeKeyManagerItem,
TreeKeyManagerStrategy,
} from '@angular/cdk/a11y';
import {
DOWN_ARROW,
END,
ENTER,
H,
HOME,
J,
K,
L,
LEFT_ARROW,
RIGHT_ARROW,
SPACE,
TAB,
UP_ARROW,
} from '@angular/cdk/keycodes';
import {Subject, isObservable, Observable} from 'rxjs';
import {take} from 'rxjs/operators';
const TREE_DATA: ExampleFlatNode[] = [
{
name: 'Fruit',
expandable: true,
level: 0,
},
{
name: 'Apple',
expandable: false,
level: 1,
},
{
name: 'Banana',
expandable: false,
level: 1,
},
{
name: 'Fruit loops',
expandable: false,
level: 1,
},
{
name: 'Vegetables',
expandable: true,
level: 0,
},
{
name: 'Green',
expandable: true,
level: 1,
},
{
name: 'Broccoli',
expandable: false,
level: 2,
},
{
name: 'Brussels sprouts',
expandable: false,
level: 2,
},
{
name: 'Orange',
expandable: true,
level: 1,
},
{
name: 'Pumpkins',
expandable: false,
level: 2,
},
{
name: 'Carrots',
expandable: false,
level: 2,
},
];
/** Flat node with expandable and level information */
interface ExampleFlatNode {
expandable: boolean;
name: string;
level: number;
isExpanded?: boolean;
}
/**
* This class manages keyboard events for trees. If you pass it a QueryList or other list of tree
* items, it will set the active item, focus, handle expansion and typeahead correctly when
* keyboard events occur.
*/
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1932,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-custom-key-manager/cdk-tree-custom-key-manager-example.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-custom-key-manager/cdk-tree-custom-key-manager-example.ts_1933_10059
|
export class VimTreeKeyManager<T extends TreeKeyManagerItem> implements TreeKeyManagerStrategy<T> {
private _activeItemIndex = -1;
private _activeItem: T | null = null;
private _items: T[] = [];
private _hasInitialFocused = false;
private _initialFocus() {
if (this._hasInitialFocused) {
return;
}
if (!this._items.length) {
return;
}
this._focusFirstItem();
this._hasInitialFocused = true;
}
// TreeKeyManagerOptions not implemented.
constructor(items: Observable<T[]> | QueryList<T> | T[]) {
// We allow for the items to be an array or Observable because, in some cases, the consumer may
// not have access to a QueryList of the items they want to manage (e.g. when the
// items aren't being collected via `ViewChildren` or `ContentChildren`).
if (items instanceof QueryList) {
this._items = items.toArray();
items.changes.subscribe((newItems: QueryList<T>) => {
this._items = newItems.toArray();
this._updateActiveItemIndex(this._items);
this._initialFocus();
});
} else if (isObservable(items)) {
items.subscribe(newItems => {
this._items = newItems;
this._updateActiveItemIndex(newItems);
this._initialFocus();
});
} else {
this._items = items;
this._initialFocus();
}
}
destroy() {
this.change.complete();
}
/** Stream that emits any time the focused item changes. */
readonly change = new Subject<T | null>();
/**
* Handles a keyboard event on the tree.
* @param event Keyboard event that represents the user interaction with the tree.
*/
onKeydown(event: KeyboardEvent) {
const keyCode = event.keyCode;
switch (keyCode) {
case TAB:
// Return early here, in order to allow Tab to actually tab out of the tree
return;
case DOWN_ARROW:
case J:
this._focusNextItem();
break;
case UP_ARROW:
case K:
this._focusPreviousItem();
break;
case RIGHT_ARROW:
case L:
this._expandCurrentItem();
break;
case LEFT_ARROW:
case H:
this._collapseCurrentItem();
break;
case HOME:
this._focusFirstItem();
break;
case END:
this._focusLastItem();
break;
case ENTER:
case SPACE:
this._activateCurrentItem();
break;
}
}
/** Index of the currently active item. */
getActiveItemIndex(): number | null {
return this._activeItemIndex;
}
/** The currently active item. */
getActiveItem(): T | null {
return this._activeItem;
}
/**
* Focus the provided item by index.
* @param index The index of the item to focus.
* @param options Additional focusing options.
*/
focusItem(index: number, options?: {emitChangeEvent?: boolean}): void;
/**
* Focus the provided item.
* @param item The item to focus. Equality is determined via the trackBy function.
* @param options Additional focusing options.
*/
focusItem(item: T, options?: {emitChangeEvent?: boolean}): void;
focusItem(itemOrIndex: number | T, options?: {emitChangeEvent?: boolean}): void;
focusItem(itemOrIndex: number | T, options: {emitChangeEvent?: boolean} = {}) {
// Set default options
options.emitChangeEvent ??= true;
let index =
typeof itemOrIndex === 'number'
? itemOrIndex
: this._items.findIndex(item => item === itemOrIndex);
if (index < 0 || index >= this._items.length) {
return;
}
const activeItem = this._items[index];
// If we're just setting the same item, don't re-call activate or focus
if (this._activeItem !== null && activeItem === this._activeItem) {
return;
}
this._activeItem = activeItem ?? null;
this._activeItemIndex = index;
if (options.emitChangeEvent) {
// Emit to `change` stream as required by TreeKeyManagerStrategy interface.
this.change.next(this._activeItem);
}
this._activeItem?.focus();
this._activateCurrentItem();
}
private _updateActiveItemIndex(newItems: T[]) {
const activeItem = this._activeItem;
if (activeItem) {
const newIndex = newItems.findIndex(item => item === activeItem);
if (newIndex > -1 && newIndex !== this._activeItemIndex) {
this._activeItemIndex = newIndex;
}
}
}
/** Focus the first available item. */
private _focusFirstItem(): void {
this.focusItem(this._findNextAvailableItemIndex(-1));
}
/** Focus the last available item. */
private _focusLastItem(): void {
this.focusItem(this._findPreviousAvailableItemIndex(this._items.length));
}
/** Focus the next available item. */
private _focusNextItem(): void {
this.focusItem(this._findNextAvailableItemIndex(this._activeItemIndex));
}
/** Focus the previous available item. */
private _focusPreviousItem(): void {
this.focusItem(this._findPreviousAvailableItemIndex(this._activeItemIndex));
}
//// Navigational methods
private _findNextAvailableItemIndex(startingIndex: number) {
if (startingIndex + 1 < this._items.length) {
return startingIndex + 1;
}
return startingIndex;
}
private _findPreviousAvailableItemIndex(startingIndex: number) {
if (startingIndex - 1 >= 0) {
return startingIndex - 1;
}
return startingIndex;
}
/**
* If the item is already expanded, we collapse the item. Otherwise, we will focus the parent.
*/
private _collapseCurrentItem() {
if (!this._activeItem) {
return;
}
if (this._isCurrentItemExpanded()) {
this._activeItem.collapse();
} else {
const parent = this._activeItem.getParent();
if (!parent) {
return;
}
this.focusItem(parent as T);
}
}
/**
* If the item is already collapsed, we expand the item. Otherwise, we will focus the first child.
*/
private _expandCurrentItem() {
if (!this._activeItem) {
return;
}
if (!this._isCurrentItemExpanded()) {
this._activeItem.expand();
} else {
coerceObservable(this._activeItem.getChildren())
.pipe(take(1))
.subscribe(children => {
const firstChild = children[0];
if (!firstChild) {
return;
}
this.focusItem(firstChild as T);
});
}
}
private _isCurrentItemExpanded() {
if (!this._activeItem) {
return false;
}
return typeof this._activeItem.isExpanded === 'boolean'
? this._activeItem.isExpanded
: this._activeItem.isExpanded();
}
private _activateCurrentItem() {
this._activeItem?.activate();
}
}
function VimTreeKeyManagerFactory<T extends TreeKeyManagerItem>(): TreeKeyManagerFactory<T> {
return items => new VimTreeKeyManager(items);
}
const VIM_TREE_KEY_MANAGER_PROVIDER = {
provide: TREE_KEY_MANAGER,
useFactory: VimTreeKeyManagerFactory,
};
/**
* @title Tree with vim keyboard commands.
*/
@Component({
selector: 'cdk-tree-custom-key-manager-example',
templateUrl: 'cdk-tree-custom-key-manager-example.html',
styleUrls: ['cdk-tree-custom-key-manager-example.css'],
imports: [CdkTreeModule, MatButtonModule, MatIconModule],
providers: [VIM_TREE_KEY_MANAGER_PROVIDER],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkTreeCustomKeyManagerExample {
treeControl = new FlatTreeControl<ExampleFlatNode>(
node => node.level,
node => node.expandable,
);
dataSource = new ArrayDataSource(TREE_DATA);
hasChild = (_: number, node: ExampleFlatNode) => node.expandable;
getParentNode(node: ExampleFlatNode) {
const nodeIndex = TREE_DATA.indexOf(node);
for (let i = nodeIndex - 1; i >= 0; i--) {
if (TREE_DATA[i].level === node.level - 1) {
return TREE_DATA[i];
}
}
return null;
}
shouldRender(node: ExampleFlatNode) {
let parent = this.getParentNode(node);
while (parent) {
if (!parent.isExpanded) {
return false;
}
parent = this.getParentNode(parent);
}
return true;
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 10059,
"start_byte": 1933,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-custom-key-manager/cdk-tree-custom-key-manager-example.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-custom-key-manager/cdk-tree-custom-key-manager-example.html_0_1372
|
<cdk-tree [dataSource]="dataSource" [treeControl]="treeControl">
<!-- This is the tree node template for leaf nodes -->
<cdk-tree-node *cdkTreeNodeDef="let node" cdkTreeNodePadding
[style.display]="shouldRender(node) ? 'flex' : 'none'"
[isDisabled]="!shouldRender(node)"
class="example-tree-node">
<!-- use a disabled button to provide padding for tree leaf -->
<button mat-icon-button disabled></button>
{{node.name}}
</cdk-tree-node>
<!-- This is the tree node template for expandable nodes -->
<cdk-tree-node *cdkTreeNodeDef="let node; when: hasChild" cdkTreeNodePadding
cdkTreeNodeToggle
[cdkTreeNodeTypeaheadLabel]="node.name"
[style.display]="shouldRender(node) ? 'flex' : 'none'"
[isDisabled]="!shouldRender(node)"
(expandedChange)="node.isExpanded = $event"
class="example-tree-node"
tabindex="0">
<button mat-icon-button cdkTreeNodeToggle
[attr.aria-label]="'Toggle ' + node.name"
[style.visibility]="node.expandable ? 'visible' : 'hidden'">
<mat-icon class="mat-icon-rtl-mirror">
{{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.name}}
</cdk-tree-node>
</cdk-tree>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1372,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-custom-key-manager/cdk-tree-custom-key-manager-example.html"
}
|
components/src/components-examples/cdk/tree/cdk-tree-flat/cdk-tree-flat-example.html_0_1325
|
<cdk-tree [dataSource]="dataSource" [treeControl]="treeControl">
<!-- This is the tree node template for leaf nodes -->
<cdk-tree-node *cdkTreeNodeDef="let node" cdkTreeNodePadding
[style.display]="shouldRender(node) ? 'flex' : 'none'"
[isDisabled]="!shouldRender(node)"
class="example-tree-node">
<!-- use a disabled button to provide padding for tree leaf -->
<button mat-icon-button disabled></button>
{{node.name}}
</cdk-tree-node>
<!-- This is the tree node template for expandable nodes -->
<cdk-tree-node *cdkTreeNodeDef="let node; when: hasChild" cdkTreeNodePadding
cdkTreeNodeToggle [cdkTreeNodeTypeaheadLabel]="node.name"
[style.display]="shouldRender(node) ? 'flex' : 'none'"
[isDisabled]="!shouldRender(node)"
(expandedChange)="node.isExpanded = $event"
class="example-tree-node">
<button mat-icon-button cdkTreeNodeToggle
[attr.aria-label]="'Toggle ' + node.name"
[style.visibility]="node.expandable ? 'visible' : 'hidden'">
<mat-icon class="mat-icon-rtl-mirror">
{{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.name}}
</cdk-tree-node>
</cdk-tree>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1325,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-flat/cdk-tree-flat-example.html"
}
|
components/src/components-examples/cdk/tree/cdk-tree-flat/cdk-tree-flat-example.ts_0_2299
|
import {ChangeDetectionStrategy, Component} from '@angular/core';
import {ArrayDataSource} from '@angular/cdk/collections';
import {FlatTreeControl, CdkTreeModule} from '@angular/cdk/tree';
import {MatIconModule} from '@angular/material/icon';
import {MatButtonModule} from '@angular/material/button';
const TREE_DATA: ExampleFlatNode[] = [
{
name: 'Fruit',
expandable: true,
level: 0,
},
{
name: 'Apple',
expandable: false,
level: 1,
},
{
name: 'Banana',
expandable: false,
level: 1,
},
{
name: 'Fruit loops',
expandable: false,
level: 1,
},
{
name: 'Vegetables',
expandable: true,
level: 0,
},
{
name: 'Green',
expandable: true,
level: 1,
},
{
name: 'Broccoli',
expandable: false,
level: 2,
},
{
name: 'Brussels sprouts',
expandable: false,
level: 2,
},
{
name: 'Orange',
expandable: true,
level: 1,
},
{
name: 'Pumpkins',
expandable: false,
level: 2,
},
{
name: 'Carrots',
expandable: false,
level: 2,
},
];
/** Flat node with expandable and level information */
interface ExampleFlatNode {
expandable: boolean;
name: string;
level: number;
isExpanded?: boolean;
}
/**
* @title Tree with flat nodes
*/
@Component({
selector: 'cdk-tree-flat-example',
templateUrl: 'cdk-tree-flat-example.html',
styleUrl: 'cdk-tree-flat-example.css',
imports: [CdkTreeModule, MatButtonModule, MatIconModule],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CdkTreeFlatExample {
treeControl = new FlatTreeControl<ExampleFlatNode>(
node => node.level,
node => node.expandable,
);
dataSource = new ArrayDataSource(TREE_DATA);
hasChild = (_: number, node: ExampleFlatNode) => node.expandable;
getParentNode(node: ExampleFlatNode) {
const nodeIndex = TREE_DATA.indexOf(node);
for (let i = nodeIndex - 1; i >= 0; i--) {
if (TREE_DATA[i].level === node.level - 1) {
return TREE_DATA[i];
}
}
return null;
}
shouldRender(node: ExampleFlatNode) {
let parent = this.getParentNode(node);
while (parent) {
if (!parent.isExpanded) {
return false;
}
parent = this.getParentNode(parent);
}
return true;
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2299,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-flat/cdk-tree-flat-example.ts"
}
|
components/src/components-examples/cdk/tree/cdk-tree-flat/cdk-tree-flat-example.css_0_63
|
.example-tree-node {
display: flex;
align-items: center;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 63,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/tree/cdk-tree-flat/cdk-tree-flat-example.css"
}
|
components/src/components-examples/cdk/portal/BUILD.bazel_0_406
|
load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "portal",
srcs = glob(["**/*.ts"]),
assets = glob([
"**/*.html",
"**/*.css",
]),
deps = [
"//src/cdk/portal",
],
)
filegroup(
name = "source-files",
srcs = glob([
"**/*.html",
"**/*.css",
"**/*.ts",
]),
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 406,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/portal/BUILD.bazel"
}
|
components/src/components-examples/cdk/portal/index.ts_0_123
|
export {
CdkPortalOverviewExample,
ComponentPortalExample,
} from './cdk-portal-overview/cdk-portal-overview-example';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 123,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/portal/index.ts"
}
|
components/src/components-examples/cdk/portal/cdk-portal-overview/cdk-portal-overview-example.css_0_128
|
.example-portal-outlet {
margin-bottom: 10px;
padding: 10px;
border: 1px dashed black;
width: 250px;
height: 250px;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 128,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/portal/cdk-portal-overview/cdk-portal-overview-example.css"
}
|
components/src/components-examples/cdk/portal/cdk-portal-overview/cdk-portal-overview-example.html_0_525
|
<h2>The portal outlet is below:</h2>
<div class="example-portal-outlet">
<ng-template [cdkPortalOutlet]="selectedPortal"></ng-template>
</div>
<ng-template #templatePortalContent>Hello, this is a template portal</ng-template>
<button (click)="selectedPortal = componentPortal">Render component portal</button>
<button (click)="selectedPortal = templatePortal">Render template portal</button>
<button (click)="selectedPortal = domPortal">Render DOM portal</button>
<div #domPortalContent>Hello, this is a DOM portal</div>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 525,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/portal/cdk-portal-overview/cdk-portal-overview-example.html"
}
|
components/src/components-examples/cdk/portal/cdk-portal-overview/cdk-portal-overview-example.ts_0_1313
|
import {
AfterViewInit,
Component,
TemplateRef,
ViewChild,
ViewContainerRef,
ElementRef,
inject,
} from '@angular/core';
import {
ComponentPortal,
DomPortal,
Portal,
TemplatePortal,
PortalModule,
} from '@angular/cdk/portal';
/**
* @title Portal overview
*/
@Component({
selector: 'cdk-portal-overview-example',
templateUrl: 'cdk-portal-overview-example.html',
styleUrl: 'cdk-portal-overview-example.css',
imports: [PortalModule],
})
export class CdkPortalOverviewExample implements AfterViewInit {
private _viewContainerRef = inject(ViewContainerRef);
@ViewChild('templatePortalContent') templatePortalContent: TemplateRef<unknown>;
@ViewChild('domPortalContent') domPortalContent: ElementRef<HTMLElement>;
selectedPortal: Portal<any>;
componentPortal: ComponentPortal<ComponentPortalExample>;
templatePortal: TemplatePortal<any>;
domPortal: DomPortal<any>;
ngAfterViewInit() {
this.componentPortal = new ComponentPortal(ComponentPortalExample);
this.templatePortal = new TemplatePortal(this.templatePortalContent, this._viewContainerRef);
this.domPortal = new DomPortal(this.domPortalContent);
}
}
@Component({
selector: 'component-portal-example',
template: 'Hello, this is a component portal',
})
export class ComponentPortalExample {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1313,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/portal/cdk-portal-overview/cdk-portal-overview-example.ts"
}
|
components/src/components-examples/cdk/accordion/BUILD.bazel_0_412
|
load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "accordion",
srcs = glob(["**/*.ts"]),
assets = glob([
"**/*.html",
"**/*.css",
]),
deps = [
"//src/cdk/accordion",
],
)
filegroup(
name = "source-files",
srcs = glob([
"**/*.html",
"**/*.css",
"**/*.ts",
]),
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 412,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/accordion/BUILD.bazel"
}
|
components/src/components-examples/cdk/accordion/index.ts_0_101
|
export {CdkAccordionOverviewExample} from './cdk-accordion-overview/cdk-accordion-overview-example';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 101,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/accordion/index.ts"
}
|
components/src/components-examples/cdk/accordion/cdk-accordion-overview/cdk-accordion-overview-example.ts_0_465
|
import {Component} from '@angular/core';
import {CdkAccordionModule} from '@angular/cdk/accordion';
/**
* @title Accordion overview
*/
@Component({
selector: 'cdk-accordion-overview-example',
templateUrl: 'cdk-accordion-overview-example.html',
styleUrl: 'cdk-accordion-overview-example.css',
imports: [CdkAccordionModule],
})
export class CdkAccordionOverviewExample {
items = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
expandedIndex = 0;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 465,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/accordion/cdk-accordion-overview/cdk-accordion-overview-example.ts"
}
|
components/src/components-examples/cdk/accordion/cdk-accordion-overview/cdk-accordion-overview-example.html_0_1206
|
<cdk-accordion class="example-accordion">
@for (item of items; track item; let index = $index) {
<cdk-accordion-item
#accordionItem="cdkAccordionItem"
class="example-accordion-item"
role="button"
tabindex="0"
[attr.id]="'accordion-header-' + index"
[attr.aria-expanded]="accordionItem.expanded"
[attr.aria-controls]="'accordion-body-' + index">
<div class="example-accordion-item-header" (click)="accordionItem.toggle()">
{{ item }}
<span class="example-accordion-item-description">
Click to {{ accordionItem.expanded ? 'close' : 'open' }}
</span>
</div>
<div
class="example-accordion-item-body"
role="region"
[style.display]="accordionItem.expanded ? '' : 'none'"
[attr.id]="'accordion-body-' + index"
[attr.aria-labelledby]="'accordion-header-' + index">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Perferendis
excepturi incidunt ipsum deleniti labore, tempore non nam doloribus blanditiis
veritatis illo autem iure aliquid ullam rem tenetur deserunt velit culpa?
</div>
</cdk-accordion-item>
}
</cdk-accordion>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1206,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/accordion/cdk-accordion-overview/cdk-accordion-overview-example.html"
}
|
components/src/components-examples/cdk/accordion/cdk-accordion-overview/cdk-accordion-overview-example.css_0_781
|
.example-accordion {
display: block;
max-width: 500px;
}
.example-accordion-item {
display: block;
border: solid 1px #ccc;
}
.example-accordion-item + .example-accordion-item {
border-top: none;
}
.example-accordion-item-header {
display: flex;
align-content: center;
justify-content: space-between;
}
.example-accordion-item-description {
font-size: 0.85em;
color: #999;
}
.example-accordion-item-header,
.example-accordion-item-body {
padding: 16px;
}
.example-accordion-item-header:hover {
cursor: pointer;
background-color: #eee;
}
.example-accordion-item:first-child {
border-top-left-radius: 4px;
border-top-right-radius: 4px;
}
.example-accordion-item:last-child {
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 781,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/accordion/cdk-accordion-overview/cdk-accordion-overview-example.css"
}
|
components/src/components-examples/cdk/layout/BUILD.bazel_0_406
|
load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "layout",
srcs = glob(["**/*.ts"]),
assets = glob([
"**/*.html",
"**/*.css",
]),
deps = [
"//src/cdk/layout",
],
)
filegroup(
name = "source-files",
srcs = glob([
"**/*.html",
"**/*.css",
"**/*.ts",
]),
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 406,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/layout/BUILD.bazel"
}
|
components/src/components-examples/cdk/layout/index.ts_0_119
|
export {BreakpointObserverOverviewExample} from './breakpoint-observer-overview/breakpoint-observer-overview-example';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 119,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/layout/index.ts"
}
|
components/src/components-examples/cdk/layout/breakpoint-observer-overview/breakpoint-observer-overview-example.css_0_31
|
/** No CSS for this example */
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 31,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/layout/breakpoint-observer-overview/breakpoint-observer-overview-example.css"
}
|
components/src/components-examples/cdk/layout/breakpoint-observer-overview/breakpoint-observer-overview-example.html_0_154
|
<p>
Resize your browser window to see the current screen size change.
</p>
<p>
The current screen size is <strong>{{currentScreenSize}}</strong>
</p>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 154,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/layout/breakpoint-observer-overview/breakpoint-observer-overview-example.html"
}
|
components/src/components-examples/cdk/layout/breakpoint-observer-overview/breakpoint-observer-overview-example.ts_0_1461
|
import {Component, OnDestroy, inject} from '@angular/core';
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
/** @title Respond to viewport changes with BreakpointObserver */
@Component({
selector: 'breakpoint-observer-overview-example',
templateUrl: 'breakpoint-observer-overview-example.html',
styleUrl: 'breakpoint-observer-overview-example.css',
})
export class BreakpointObserverOverviewExample implements OnDestroy {
destroyed = new Subject<void>();
currentScreenSize: string;
// Create a map to display breakpoint names for demonstration purposes.
displayNameMap = new Map([
[Breakpoints.XSmall, 'XSmall'],
[Breakpoints.Small, 'Small'],
[Breakpoints.Medium, 'Medium'],
[Breakpoints.Large, 'Large'],
[Breakpoints.XLarge, 'XLarge'],
]);
constructor() {
inject(BreakpointObserver)
.observe([
Breakpoints.XSmall,
Breakpoints.Small,
Breakpoints.Medium,
Breakpoints.Large,
Breakpoints.XLarge,
])
.pipe(takeUntil(this.destroyed))
.subscribe(result => {
for (const query of Object.keys(result.breakpoints)) {
if (result.breakpoints[query]) {
this.currentScreenSize = this.displayNameMap.get(query) ?? 'Unknown';
}
}
});
}
ngOnDestroy() {
this.destroyed.next();
this.destroyed.complete();
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1461,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/layout/breakpoint-observer-overview/breakpoint-observer-overview-example.ts"
}
|
components/src/components-examples/cdk/platform/BUILD.bazel_0_410
|
load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "platform",
srcs = glob(["**/*.ts"]),
assets = glob([
"**/*.html",
"**/*.css",
]),
deps = [
"//src/cdk/platform",
],
)
filegroup(
name = "source-files",
srcs = glob([
"**/*.html",
"**/*.css",
"**/*.ts",
]),
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 410,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/platform/BUILD.bazel"
}
|
components/src/components-examples/cdk/platform/index.ts_0_98
|
export {CdkPlatformOverviewExample} from './cdk-platform-overview/cdk-platform-overview-example';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 98,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/platform/index.ts"
}
|
components/src/components-examples/cdk/platform/cdk-platform-overview/cdk-platform-overview-example.ts_0_607
|
import {Component, inject} from '@angular/core';
import {
getSupportedInputTypes,
Platform,
supportsPassiveEventListeners,
supportsScrollBehavior,
} from '@angular/cdk/platform';
/**
* @title Platform overview
*/
@Component({
selector: 'cdk-platform-overview-example',
templateUrl: 'cdk-platform-overview-example.html',
})
export class CdkPlatformOverviewExample {
platform = inject(Platform);
supportedInputTypes = Array.from(getSupportedInputTypes()).join(', ');
supportsPassiveEventListeners = supportsPassiveEventListeners();
supportsScrollBehavior = supportsScrollBehavior();
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 607,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/platform/cdk-platform-overview/cdk-platform-overview-example.ts"
}
|
components/src/components-examples/cdk/platform/cdk-platform-overview/cdk-platform-overview-example.html_0_518
|
<h2>Platform information:</h2>
<p>Is Android: {{platform.ANDROID}}</p>
<p>Is iOS: {{platform.IOS}}</p>
<p>Is Firefox: {{platform.FIREFOX}}</p>
<p>Is Blink: {{platform.BLINK}}</p>
<p>Is Webkit: {{platform.WEBKIT}}</p>
<p>Is Trident: {{platform.TRIDENT}}</p>
<p>Is Edge: {{platform.EDGE}}</p>
<p>Is Safari: {{platform.SAFARI}}</p>
<p>Supported input types: {{supportedInputTypes}}</p>
<p>Supports passive event listeners: {{supportsPassiveEventListeners}}</p>
<p>Supports scroll behavior: {{supportsScrollBehavior}}</p>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 518,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/platform/cdk-platform-overview/cdk-platform-overview-example.html"
}
|
components/src/components-examples/cdk/listbox/BUILD.bazel_0_473
|
load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "listbox",
srcs = glob(["**/*.ts"]),
assets = glob([
"**/*.html",
"**/*.css",
]),
deps = [
"//src/cdk/listbox",
"@npm//@angular/common",
"@npm//@angular/forms",
],
)
filegroup(
name = "source-files",
srcs = glob([
"**/*.html",
"**/*.css",
"**/*.ts",
]),
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 473,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/BUILD.bazel"
}
|
components/src/components-examples/cdk/listbox/index.ts_0_1301
|
export {CdkListboxActivedescendantExample} from './cdk-listbox-activedescendant/cdk-listbox-activedescendant-example';
export {CdkListboxCompareWithExample} from './cdk-listbox-compare-with/cdk-listbox-compare-with-example';
export {CdkListboxCustomNavigationExample} from './cdk-listbox-custom-navigation/cdk-listbox-custom-navigation-example';
export {CdkListboxCustomTypeaheadExample} from './cdk-listbox-custom-typeahead/cdk-listbox-custom-typeahead-example';
export {CdkListboxDisabledExample} from './cdk-listbox-disabled/cdk-listbox-disabled-example';
export {CdkListboxFormsValidationExample} from './cdk-listbox-forms-validation/cdk-listbox-forms-validation-example';
export {CdkListboxHorizontalExample} from './cdk-listbox-horizontal/cdk-listbox-horizontal-example';
export {CdkListboxMultipleExample} from './cdk-listbox-multiple/cdk-listbox-multiple-example';
export {CdkListboxOverviewExample} from './cdk-listbox-overview/cdk-listbox-overview-example';
export {CdkListboxReactiveFormsExample} from './cdk-listbox-reactive-forms/cdk-listbox-reactive-forms-example';
export {CdkListboxTemplateFormsExample} from './cdk-listbox-template-forms/cdk-listbox-template-forms-example';
export {CdkListboxValueBindingExample} from './cdk-listbox-value-binding/cdk-listbox-value-binding-example';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1301,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/index.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-overview/cdk-listbox-overview-example.html_0_552
|
<div class="example-listbox-container">
<!-- #docregion listbox -->
<label class="example-listbox-label" id="example-fav-color-label">
Favorite color
</label>
<ul cdkListbox
aria-labelledby="example-fav-color-label"
class="example-listbox">
<!-- #docregion option -->
<li cdkOption="red" class="example-option">Red</li>
<!-- #enddocregion option -->
<li cdkOption="green" class="example-option">Green</li>
<li cdkOption="blue" class="example-option">Blue</li>
</ul>
<!-- #enddocregion listbox -->
</div>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 552,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-overview/cdk-listbox-overview-example.html"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-overview/cdk-listbox-overview-example.css_0_757
|
.example-listbox-container {
display: block;
width: 250px;
border: 1px solid black;
}
.example-listbox-label {
display: block;
padding: 5px;
}
.example-listbox {
list-style: none;
padding: 0;
margin: 0;
}
.example-option {
position: relative;
padding: 5px 5px 5px 25px;
}
.example-option[aria-selected='true']::before {
content: '';
display: block;
width: 20px;
height: 20px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.55 18-5.7-5.7 1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4Z"/></svg>'); /* stylelint-disable-line */
background-size: cover;
position: absolute;
left: 2px;
}
.example-option:focus {
background: rgba(0, 0, 0, 0.2);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 757,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-overview/cdk-listbox-overview-example.css"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-overview/cdk-listbox-overview-example.ts_0_410
|
import {Component} from '@angular/core';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Basic listbox. */
@Component({
selector: 'cdk-listbox-overview-example',
exportAs: 'cdkListboxOverviewExample',
templateUrl: 'cdk-listbox-overview-example.html',
styleUrl: 'cdk-listbox-overview-example.css',
imports: [CdkListbox, CdkOption],
})
export class CdkListboxOverviewExample {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 410,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-overview/cdk-listbox-overview-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-activedescendant/cdk-listbox-activedescendant-example.css_0_777
|
.example-listbox-container {
display: block;
width: 250px;
border: 1px solid black;
}
.example-listbox-label {
display: block;
padding: 5px;
}
.example-listbox {
list-style: none;
padding: 0;
margin: 0;
}
.example-option {
position: relative;
padding: 5px 5px 5px 25px;
}
.example-option[aria-selected='true']::before {
content: '';
display: block;
width: 20px;
height: 20px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.55 18-5.7-5.7 1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4Z"/></svg>'); /* stylelint-disable-line */
background-size: cover;
position: absolute;
left: 2px;
}
.example-listbox:focus .cdk-option-active {
background: rgba(0, 0, 0, 0.2);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 777,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-activedescendant/cdk-listbox-activedescendant-example.css"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-activedescendant/cdk-listbox-activedescendant-example.html_0_498
|
<div class="example-listbox-container">
<!-- #docregion listbox -->
<label class="example-listbox-label" id="example-spatula-label">
Spatula Features
</label>
<ul cdkListbox
cdkListboxMultiple
cdkListboxUseActiveDescendant
aria-labelledby="example-spatula-label"
class="example-listbox">
@for (feature of features; track feature) {
<li [cdkOption]="feature" class="example-option">{{feature}}</li>
}
</ul>
<!-- #enddocregion listbox -->
</div>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 498,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-activedescendant/cdk-listbox-activedescendant-example.html"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-activedescendant/cdk-listbox-activedescendant-example.ts_0_550
|
import {Component} from '@angular/core';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Listbox with aria-activedescendant. */
@Component({
selector: 'cdk-listbox-activedescendant-example',
exportAs: 'cdkListboxActivedescendantExample',
templateUrl: 'cdk-listbox-activedescendant-example.html',
styleUrl: 'cdk-listbox-activedescendant-example.css',
imports: [CdkListbox, CdkOption],
})
export class CdkListboxActivedescendantExample {
features = ['Hydrodynamic', 'Port & Starboard Attachments', 'Turbo Drive'];
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 550,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-activedescendant/cdk-listbox-activedescendant-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-disabled/cdk-listbox-disabled-example.html_0_1133
|
<form>
<p>
<input type="checkbox" id="can-drink" [formControl]="canDrinkCtrl">
<label for="can-drink">I am 21 or older</label>
</p>
<section>
<div class="example-listbox-container" [class.example-disabled]="!canDrinkCtrl.value">
<!-- #docregion listbox -->
<label class="example-listbox-label" id="example-wine-type-label">
Wine Selection
</label>
<ul cdkListbox
[cdkListboxDisabled]="!canDrinkCtrl.value"
aria-labelledby="example-wine-type-label"
class="example-listbox">
<li cdkOption="cabernet"
class="example-option">
Cabernet Sauvignon
</li>
<li cdkOption="syrah"
class="example-option">
Syrah
</li>
<li cdkOption="zinfandel"
cdkOptionDisabled
class="example-option">
Zinfandel <span class="example-sold-out">(sold out)</span>
</li>
<li cdkOption="riesling"
class="example-option">
Riesling
</li>
</ul>
<!-- #enddocregion listbox -->
</div>
</section>
</form>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1133,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-disabled/cdk-listbox-disabled-example.html"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-disabled/cdk-listbox-disabled-example.ts_0_580
|
import {Component} from '@angular/core';
import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Listbox with disabled options. */
@Component({
selector: 'cdk-listbox-disabled-example',
exportAs: 'cdkListboxDisabledExample',
templateUrl: 'cdk-listbox-disabled-example.html',
styleUrl: 'cdk-listbox-disabled-example.css',
imports: [FormsModule, ReactiveFormsModule, CdkListbox, CdkOption],
})
export class CdkListboxDisabledExample {
canDrinkCtrl = new FormControl(false);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 580,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-disabled/cdk-listbox-disabled-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-disabled/cdk-listbox-disabled-example.css_0_1043
|
.example-listbox-container {
display: block;
width: 250px;
border: 1px solid black;
}
.example-disabled {
border-color: rgba(0, 0, 0, 0.5);
}
.example-listbox-label {
display: block;
padding: 5px;
}
.example-disabled .example-listbox-label {
opacity: 0.5;
}
.example-listbox {
list-style: none;
padding: 0;
margin: 0;
}
.example-option {
position: relative;
padding: 5px 5px 5px 25px;
}
.example-option[aria-selected='true']::before {
content: '';
display: block;
width: 20px;
height: 20px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.55 18-5.7-5.7 1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4Z"/></svg>'); /* stylelint-disable-line */
background-size: cover;
position: absolute;
left: 2px;
}
.example-option[aria-disabled='true'] {
opacity: 0.5;
}
.example-option[aria-disabled='false']:focus {
background: rgba(0, 0, 0, 0.2);
}
.example-sold-out {
color: red;
font-size: 0.75em;
vertical-align: super;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1043,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-disabled/cdk-listbox-disabled-example.css"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-reactive-forms/cdk-listbox-reactive-forms-example.css_0_757
|
.example-listbox-container {
display: block;
width: 250px;
border: 1px solid black;
}
.example-listbox-label {
display: block;
padding: 5px;
}
.example-listbox {
list-style: none;
padding: 0;
margin: 0;
}
.example-option {
position: relative;
padding: 5px 5px 5px 25px;
}
.example-option[aria-selected='true']::before {
content: '';
display: block;
width: 20px;
height: 20px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.55 18-5.7-5.7 1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4Z"/></svg>'); /* stylelint-disable-line */
background-size: cover;
position: absolute;
left: 2px;
}
.example-option:focus {
background: rgba(0, 0, 0, 0.2);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 757,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-reactive-forms/cdk-listbox-reactive-forms-example.css"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-reactive-forms/cdk-listbox-reactive-forms-example.html_0_626
|
<div class="example-listbox-container">
<!-- #docregion listbox -->
<label class="example-listbox-label" id="example-language-label">
Preferred Language
</label>
<ul cdkListbox
[formControl]="languageCtrl"
aria-labelledby="example-language-label"
class="example-listbox">
@for (language of languages; track language) {
<li [cdkOption]="language" class="example-option">{{language}}</li>
}
</ul>
<!-- #enddocregion listbox -->
</div>
<p>
Your preferred language: <strong>{{languageCtrl.value | json}}</strong>
<button (click)="languageCtrl.reset()">Reset</button>
</p>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 626,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-reactive-forms/cdk-listbox-reactive-forms-example.html"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-reactive-forms/cdk-listbox-reactive-forms-example.ts_0_736
|
import {Component} from '@angular/core';
import {FormControl, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {JsonPipe} from '@angular/common';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Listbox with reactive forms. */
@Component({
selector: 'cdk-listbox-reactive-forms-example',
exportAs: 'cdkListboxReactiveFormsExample',
templateUrl: 'cdk-listbox-reactive-forms-example.html',
styleUrl: 'cdk-listbox-reactive-forms-example.css',
imports: [CdkListbox, FormsModule, ReactiveFormsModule, CdkOption, JsonPipe],
})
export class CdkListboxReactiveFormsExample {
languages = ['C++', 'Java', 'JavaScript', 'Python', 'TypeScript'];
languageCtrl = new FormControl(['TypeScript']);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 736,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-reactive-forms/cdk-listbox-reactive-forms-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-value-binding/cdk-listbox-value-binding-example.ts_0_642
|
import {Component} from '@angular/core';
import {JsonPipe} from '@angular/common';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Listbox with value binding. */
@Component({
selector: 'cdk-listbox-value-binding-example',
exportAs: 'cdkListboxValueBindingExample',
templateUrl: 'cdk-listbox-value-binding-example.html',
styleUrl: 'cdk-listbox-value-binding-example.css',
imports: [CdkListbox, CdkOption, JsonPipe],
})
export class CdkListboxValueBindingExample {
starters = ['Sprigatito', 'Fuecoco', 'Quaxly'];
starter: readonly string[] = ['Fuecoco'];
reset() {
this.starter = ['Fuecoco'];
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 642,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-value-binding/cdk-listbox-value-binding-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-value-binding/cdk-listbox-value-binding-example.css_0_757
|
.example-listbox-container {
display: block;
width: 250px;
border: 1px solid black;
}
.example-listbox-label {
display: block;
padding: 5px;
}
.example-listbox {
list-style: none;
padding: 0;
margin: 0;
}
.example-option {
position: relative;
padding: 5px 5px 5px 25px;
}
.example-option[aria-selected='true']::before {
content: '';
display: block;
width: 20px;
height: 20px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.55 18-5.7-5.7 1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4Z"/></svg>'); /* stylelint-disable-line */
background-size: cover;
position: absolute;
left: 2px;
}
.example-option:focus {
background: rgba(0, 0, 0, 0.2);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 757,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-value-binding/cdk-listbox-value-binding-example.css"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-value-binding/cdk-listbox-value-binding-example.html_0_661
|
<div class="example-listbox-container">
<!-- #docregion listbox -->
<label class="example-listbox-label" id="example-starter-pokemon-label">
Starter Pokemon
</label>
<ul cdkListbox
[cdkListboxValue]="starter"
(cdkListboxValueChange)="starter = $event.value"
aria-labelledby="example-starter-pokemon-label"
class="example-listbox">
@for (pokemon of starters; track pokemon) {
<li [cdkOption]="pokemon" class="example-option">{{pokemon}}</li>
}
</ul>
<!-- #enddocregion listbox -->
</div>
<p>
Your starter pokemon is <strong>{{starter | json}}</strong>
<button (click)="reset()">Reset</button>
</p>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 661,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-value-binding/cdk-listbox-value-binding-example.html"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-template-forms/cdk-listbox-template-forms-example.ts_0_670
|
import {Component} from '@angular/core';
import {JsonPipe} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Listbox with template-driven forms. */
@Component({
selector: 'cdk-listbox-template-forms-example',
exportAs: 'cdkListboxTemplateFormsExample',
templateUrl: 'cdk-listbox-template-forms-example.html',
styleUrl: 'cdk-listbox-template-forms-example.css',
imports: [CdkListbox, FormsModule, CdkOption, JsonPipe],
})
export class CdkListboxTemplateFormsExample {
toppings = ['Extra Cheese', 'Mushrooms', 'Pepperoni', 'Sausage'];
order: readonly string[] = [];
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 670,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-template-forms/cdk-listbox-template-forms-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-template-forms/cdk-listbox-template-forms-example.html_0_598
|
<div class="example-listbox-container">
<!-- #docregion listbox -->
<label class="example-listbox-label" id="example-toppings-label">
Choose Toppings
</label>
<ul cdkListbox
cdkListboxMultiple
[(ngModel)]="order"
aria-labelledby="example-toppings-label"
class="example-listbox">
@for (topping of toppings; track topping) {
<li [cdkOption]="topping" class="example-option">{{topping}}</li>
}
</ul>
<!-- #enddocregion listbox -->
</div>
<p>
Your order: <strong>{{order | json}}</strong>
<button (click)="order = []">Reset</button>
</p>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 598,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-template-forms/cdk-listbox-template-forms-example.html"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-template-forms/cdk-listbox-template-forms-example.css_0_757
|
.example-listbox-container {
display: block;
width: 250px;
border: 1px solid black;
}
.example-listbox-label {
display: block;
padding: 5px;
}
.example-listbox {
list-style: none;
padding: 0;
margin: 0;
}
.example-option {
position: relative;
padding: 5px 5px 5px 25px;
}
.example-option[aria-selected='true']::before {
content: '';
display: block;
width: 20px;
height: 20px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.55 18-5.7-5.7 1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4Z"/></svg>'); /* stylelint-disable-line */
background-size: cover;
position: absolute;
left: 2px;
}
.example-option:focus {
background: rgba(0, 0, 0, 0.2);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 757,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-template-forms/cdk-listbox-template-forms-example.css"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-custom-navigation/cdk-listbox-custom-navigation-example.css_0_839
|
.example-listbox-container {
display: block;
width: 250px;
border: 1px solid black;
}
.example-listbox-label {
display: block;
padding: 5px;
}
.example-listbox {
list-style: none;
padding: 0;
margin: 0;
}
.example-option {
position: relative;
padding: 5px 5px 5px 25px;
}
.example-option[aria-selected='true']::before {
content: '';
display: block;
width: 20px;
height: 20px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.55 18-5.7-5.7 1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4Z"/></svg>'); /* stylelint-disable-line */
background-size: cover;
position: absolute;
left: 2px;
}
.example-option[aria-disabled='true'] {
opacity: 0.5;
}
.example-option[aria-disabled='false']:focus {
background: rgba(0, 0, 0, 0.2);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 839,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-custom-navigation/cdk-listbox-custom-navigation-example.css"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-custom-navigation/cdk-listbox-custom-navigation-example.html_0_774
|
<div class="example-listbox-container">
<!-- #docregion listbox -->
<label class="example-listbox-label" id="example-flavor-label">
Flavor
</label>
<ul cdkListbox
cdkListboxNavigatesDisabledOptions
cdkListboxNavigationWrapDisabled
aria-labelledby="example-flavor-label"
class="example-listbox">
<li cdkOption="chocolate"
class="example-option">
Chocolate
</li>
<li cdkOption="pumpkin-spice"
cdkOptionDisabled
class="example-option">
Pumpkin Spice (seasonal)
</li>
<li cdkOption="strawberry"
class="example-option">
Strawberry
</li>
<li cdkOption="vanilla"
class="example-option">
Vanilla
</li>
</ul>
<!-- #enddocregion listbox -->
</div>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 774,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-custom-navigation/cdk-listbox-custom-navigation-example.html"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-custom-navigation/cdk-listbox-custom-navigation-example.ts_0_487
|
import {Component} from '@angular/core';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Listbox with custom keyboard navigation options. */
@Component({
selector: 'cdk-listbox-custom-navigation-example',
exportAs: 'cdkListboxCustomNavigationExample',
templateUrl: 'cdk-listbox-custom-navigation-example.html',
styleUrl: 'cdk-listbox-custom-navigation-example.css',
imports: [CdkListbox, CdkOption],
})
export class CdkListboxCustomNavigationExample {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 487,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-custom-navigation/cdk-listbox-custom-navigation-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-forms-validation/cdk-listbox-forms-validation-example.css_0_953
|
.example-listbox-container {
display: block;
width: 250px;
border: 1px solid black;
}
.example-listbox-invalid {
border-color: red;
}
.example-listbox-label {
display: block;
padding: 5px;
}
.example-listbox-invalid .example-listbox-label {
color: red;
}
.example-listbox {
list-style: none;
padding: 0;
margin: 0;
height: 200px;
overflow: auto;
}
.example-option {
position: relative;
padding: 5px 5px 5px 25px;
}
.example-option[aria-selected='true']::before {
content: '';
display: block;
width: 20px;
height: 20px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.55 18-5.7-5.7 1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4Z"/></svg>'); /* stylelint-disable-line */
background-size: cover;
position: absolute;
left: 2px;
}
.example-option:focus {
background: rgba(0, 0, 0, 0.2);
}
.example-listbox-errors {
color: red;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 953,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-forms-validation/cdk-listbox-forms-validation-example.css"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-forms-validation/cdk-listbox-forms-validation-example.ts_0_1386
|
import {Component} from '@angular/core';
import {FormControl, Validators, FormsModule, ReactiveFormsModule} from '@angular/forms';
import {map} from 'rxjs/operators';
import {Observable} from 'rxjs';
import {AsyncPipe, JsonPipe} from '@angular/common';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Listbox with forms validation. */
@Component({
selector: 'cdk-listbox-forms-validation-example',
exportAs: 'cdkListboxFormsValidationExample',
templateUrl: 'cdk-listbox-forms-validation-example.html',
styleUrl: 'cdk-listbox-forms-validation-example.css',
imports: [CdkListbox, FormsModule, ReactiveFormsModule, CdkOption, AsyncPipe, JsonPipe],
})
export class CdkListboxFormsValidationExample {
signs = [
'Rat',
'Ox',
'Tiger',
'Rabbit',
'Dragon',
'Snake',
'Horse',
'Goat',
'Monkey',
'Rooster',
'Dog',
'Pig',
];
invalid: Observable<boolean>;
constructor() {
this.invalid = this.signCtrl.valueChanges.pipe(
map(() => this.signCtrl.touched && !this.signCtrl.valid),
);
}
// #docregion errors
signCtrl = new FormControl<string[]>([], Validators.required);
getErrors() {
const errors = [];
if (this.signCtrl.hasError('required')) {
errors.push('You must enter your zodiac sign');
}
return errors.length ? errors : null;
}
// #enddocregion errors
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1386,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-forms-validation/cdk-listbox-forms-validation-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-forms-validation/cdk-listbox-forms-validation-example.html_0_731
|
<div class="example-listbox-container" [class.example-listbox-invalid]="invalid | async">
<label class="example-listbox-label" id="example-zodiac-sign-label">
Zodiac Sign
</label>
<ul cdkListbox
[formControl]="signCtrl"
aria-labelledby="example-zodiac-sign-label"
class="example-listbox">
@for (sign of signs; track sign) {
<li [cdkOption]="sign" class="example-option">{{sign}}</li>
}
</ul>
</div>
@if (invalid | async) {
<div class="example-listbox-errors">
@for (error of getErrors(); track error) {
<p>{{error}}</p>
}
</div>
}
<p>
Your zodiac sign is: <strong>{{signCtrl.value | json}}</strong>
<button (click)="signCtrl.setValue([])">Clear</button>
</p>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 731,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-forms-validation/cdk-listbox-forms-validation-example.html"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-compare-with/cdk-listbox-compare-with-example.html_0_713
|
<div class="example-listbox-container">
<!-- #docregion listbox -->
<label class="example-listbox-label" id="example-appointment-label">
Appointment Time
</label>
<ul cdkListbox
[cdkListboxValue]="appointment"
[cdkListboxCompareWith]="compareDate"
(cdkListboxValueChange)="appointment = $event.value"
aria-labelledby="example-appointment-label"
class="example-listbox">
@for (time of slots; track time) {
<li [cdkOption]="time" class="example-option">{{formatTime(time)}}</li>
}
</ul>
<!-- #enddocregion listbox -->
</div>
@if (appointment[0]) {
<p>
Your appointment is scheduled for <strong>{{formatAppointment() | json}}</strong>
</p>
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 713,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-compare-with/cdk-listbox-compare-with-example.html"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-compare-with/cdk-listbox-compare-with-example.css_0_757
|
.example-listbox-container {
display: block;
width: 250px;
border: 1px solid black;
}
.example-listbox-label {
display: block;
padding: 5px;
}
.example-listbox {
list-style: none;
padding: 0;
margin: 0;
}
.example-option {
position: relative;
padding: 5px 5px 5px 25px;
}
.example-option[aria-selected='true']::before {
content: '';
display: block;
width: 20px;
height: 20px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.55 18-5.7-5.7 1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4Z"/></svg>'); /* stylelint-disable-line */
background-size: cover;
position: absolute;
left: 2px;
}
.example-option:focus {
background: rgba(0, 0, 0, 0.2);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 757,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-compare-with/cdk-listbox-compare-with-example.css"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-compare-with/cdk-listbox-compare-with-example.ts_0_1181
|
import {Component} from '@angular/core';
import {JsonPipe} from '@angular/common';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
const today = new Date();
const formatter = new Intl.DateTimeFormat(undefined, {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
});
/** @title Listbox with complex object as values. */
@Component({
selector: 'cdk-listbox-compare-with-example',
exportAs: 'cdkListboxCompareWithExample',
templateUrl: 'cdk-listbox-compare-with-example.html',
styleUrl: 'cdk-listbox-compare-with-example.css',
imports: [CdkListbox, CdkOption, JsonPipe],
})
export class CdkListboxCompareWithExample {
slots = [12, 13, 14, 15].map(
hour => new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1, hour),
);
appointment: readonly Date[] = [
new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1, 14),
];
compareDate(date1: Date, date2: Date) {
return date1.getTime() === date2.getTime();
}
formatTime(date: Date) {
return formatter.format(date);
}
formatAppointment() {
return this.appointment.map(a => this.formatTime(a));
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1181,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-compare-with/cdk-listbox-compare-with-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-custom-typeahead/cdk-listbox-custom-typeahead-example.html_0_698
|
<div class="example-listbox-container">
<!-- #docregion listbox -->
<label class="example-listbox-label" id="example-satisfaction-label">
How was your service?
</label>
<ul cdkListbox
aria-labelledby="example-satisfaction-label"
class="example-listbox">
<li
[cdkOption]="1"
cdkOptionTypeaheadLabel="great"
class="example-option">
😀 Great
</li>
<li [cdkOption]="0"
cdkOptionTypeaheadLabel="okay"
class="example-option">
😐 Okay
</li>
<li [cdkOption]="-1"
cdkOptionTypeaheadLabel="bad"
class="example-option">
🙁 Bad
</li>
</ul>
<!-- #enddocregion listbox -->
</div>
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 698,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-custom-typeahead/cdk-listbox-custom-typeahead-example.html"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-custom-typeahead/cdk-listbox-custom-typeahead-example.css_0_757
|
.example-listbox-container {
display: block;
width: 250px;
border: 1px solid black;
}
.example-listbox-label {
display: block;
padding: 5px;
}
.example-listbox {
list-style: none;
padding: 0;
margin: 0;
}
.example-option {
position: relative;
padding: 5px 5px 5px 25px;
}
.example-option[aria-selected='true']::before {
content: '';
display: block;
width: 20px;
height: 20px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" height="24" width="24"><path d="m9.55 18-5.7-5.7 1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4Z"/></svg>'); /* stylelint-disable-line */
background-size: cover;
position: absolute;
left: 2px;
}
.example-option:focus {
background: rgba(0, 0, 0, 0.2);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 757,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-custom-typeahead/cdk-listbox-custom-typeahead-example.css"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-custom-typeahead/cdk-listbox-custom-typeahead-example.ts_0_464
|
import {Component} from '@angular/core';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Listbox with custom typeahead. */
@Component({
selector: 'cdk-listbox-custom-typeahead-example',
exportAs: 'cdkListboxCustomTypeaheadExample',
templateUrl: 'cdk-listbox-custom-typeahead-example.html',
styleUrl: 'cdk-listbox-custom-typeahead-example.css',
imports: [CdkListbox, CdkOption],
})
export class CdkListboxCustomTypeaheadExample {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 464,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-custom-typeahead/cdk-listbox-custom-typeahead-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-horizontal/cdk-listbox-horizontal-example.ts_0_464
|
import {Component} from '@angular/core';
import {CdkListbox, CdkOption} from '@angular/cdk/listbox';
/** @title Horizontal listbox */
@Component({
selector: 'cdk-listbox-horizontal-example',
exportAs: 'cdkListboxhorizontalExample',
templateUrl: 'cdk-listbox-horizontal-example.html',
styleUrl: 'cdk-listbox-horizontal-example.css',
imports: [CdkListbox, CdkOption],
})
export class CdkListboxHorizontalExample {
sizes = ['XS', 'S', 'M', 'L', 'XL'];
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 464,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-horizontal/cdk-listbox-horizontal-example.ts"
}
|
components/src/components-examples/cdk/listbox/cdk-listbox-horizontal/cdk-listbox-horizontal-example.css_0_569
|
.example-listbox {
display: flex;
width: 250px;
padding: 0;
}
.example-option {
display: flex;
flex: 1;
align-items: center;
justify-content: center;
position: relative;
list-style: none;
padding: 12px;
border: solid black;
border-width: 1px 1px 1px 0;
}
.example-option:first-child {
border-left-width: 1px;
}
.example-option[aria-selected='true']::before {
content: '';
position: absolute;
border: 2px solid black;
top: 3px;
bottom: 3px;
left: 3px;
right: 3px;
}
.example-option:focus {
background: rgba(0, 0, 0, 0.2);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 569,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/components-examples/cdk/listbox/cdk-listbox-horizontal/cdk-listbox-horizontal-example.css"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.