Angular ng-select - All in One UI Select, Multiselect and Autocomplete library providing comprehensive select component functionality
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Angular ng-select provides a comprehensive configuration system and utility services for customizing default behavior, accessing internal functionality, and integrating with application-wide settings.
Service for setting application-wide defaults for all ng-select components.
/**
* Injectable service for configuring global ng-select defaults
* Can be provided at root level or component level for different scopes
*/
@Injectable({
providedIn: 'root'
})
export class NgSelectConfig {
/** Default placeholder text for all selects */
placeholder: string;
/** Whether placeholder should remain visible when item is selected */
fixedPlaceholder: boolean = true;
/** Default text shown when no items match search */
notFoundText: string = 'No items found';
/** Default text shown when search term is required */
typeToSearchText: string = 'Type to search';
/** Default text for add tag functionality */
addTagText: string = 'Add item';
/** Default loading text */
loadingText: string = 'Loading...';
/** Default text for clear all action */
clearAllText: string = 'Clear all';
/** Disable virtual scroll globally */
disableVirtualScroll: boolean = true;
/** Open dropdown when Enter key is pressed */
openOnEnter: boolean = true;
/** Default element to append dropdown to */
appendTo: string;
/** Default property name for item values */
bindValue: string;
/** Default property name for item labels */
bindLabel: string;
/** Default appearance style */
appearance: string = 'underline';
/** Clear search term when adding items */
clearSearchOnAdd: boolean;
/** Deselect item when clicking on selected item */
deselectOnClick: boolean;
/** Move focus to tab when clearing selection */
tabFocusOnClear: boolean = true;
}Usage Examples:
// Configure globally in app module or main.ts
import { NgSelectConfig } from '@ng-select/ng-select';
// Method 1: Using injection token
@NgModule({
providers: [
{
provide: NgSelectConfig,
useValue: {
placeholder: 'Choose an option...',
notFoundText: 'No results found',
clearAllText: 'Remove all',
appearance: 'material'
}
}
]
})
export class AppModule {}
// Method 2: Using service configuration
@Component({
providers: [NgSelectConfig]
})
export class CustomConfigComponent {
constructor(private config: NgSelectConfig) {
this.config.placeholder = 'Select from list...';
this.config.clearable = true;
this.config.appearance = 'outline';
}
}
// Method 3: Per-component configuration
@Component({
template: `
<ng-select
[config]="customConfig"
[(ngModel)]="selected">
<!-- options -->
</ng-select>
`
})
export class PerComponentConfigComponent {
customConfig = {
placeholder: 'Pick your choice',
clearAllText: 'Clear selection',
notFoundText: 'Nothing matches your search'
};
selected: any;
}Utility service for handling warnings and debug information.
/**
* Injectable service for console logging and warnings
* Used internally but can be overridden for custom logging
*/
@Injectable({
providedIn: 'root'
})
export class ConsoleService {
/**
* Log warning message to console
* @param message - Warning message to log
*/
warn(message: string): void;
}Usage Example:
// Override console service for custom logging
@Injectable()
export class CustomConsoleService extends ConsoleService {
warn(message: string): void {
// Send warnings to external logging service
this.loggingService.logWarning('ng-select', message);
super.warn(message);
}
constructor(private loggingService: LoggingService) {
super();
}
}
@NgModule({
providers: [
{ provide: ConsoleService, useClass: CustomConsoleService }
]
})
export class AppModule {}Service providing calculations and utilities for dropdown panel positioning and virtual scrolling.
/**
* Injectable service for dropdown panel calculations and virtual scrolling
* Handles viewport calculations, item positioning, and scroll optimization
*/
@Injectable({
providedIn: 'root'
})
export class NgDropdownPanelService {
/** Current panel dimensions and measurements */
dimensions: PanelDimensions;
/**
* Calculate visible items range for virtual scrolling
* @param scrollPos - Current scroll position in pixels
* @param itemsLength - Total number of items
* @param buffer - Number of buffer items to render outside viewport
* @returns Object containing scroll calculations and item range
*/
calculateItems(
scrollPos: number,
itemsLength: number,
buffer: number
): ItemsRangeResult;
/**
* Get dimensions for panel sizing calculations
* @param itemHeight - Height of individual items
* @param panelHeight - Total height of panel
* @returns Panel dimensions object
*/
calculateDimensions(itemHeight: number, panelHeight: number): PanelDimensions;
/**
* Update scroll position and recalculate visible range
* @param scrollTop - New scroll position
* @param itemsLength - Total items count
* @returns Updated items range
*/
scrollTo(scrollTop: number, itemsLength: number): ItemsRangeResult;
}
/**
* Interface for panel dimension calculations
*/
interface PanelDimensions {
/** Height of individual items in pixels */
itemHeight: number;
/** Total height of the panel in pixels */
panelHeight: number;
/** Number of items visible in current viewport */
itemsPerViewport: number;
}
/**
* Interface for virtual scroll calculation results
*/
interface ItemsRangeResult {
/** Total scroll height for scrollbar sizing */
scrollHeight: number;
/** Top padding to maintain scroll position */
topPadding: number;
/** Start index of visible range */
start: number;
/** End index of visible range */
end: number;
}Usage Example:
@Component({
template: `
<ng-select
[items]="largeItemList"
[virtualScroll]="true"
[bufferAmount]="customBuffer"
(scroll)="onScroll($event)">
</ng-select>
`
})
export class VirtualScrollComponent {
largeItemList = Array.from({length: 50000}, (_, i) => ({
id: i,
name: `Item ${i + 1}`,
category: `Category ${Math.floor(i / 100)}`
}));
customBuffer = 10;
constructor(private panelService: NgDropdownPanelService) {}
onScroll(event: {start: number, end: number}) {
console.log(`Visible items: ${event.start} to ${event.end}`);
// Access panel dimensions
const dimensions = this.panelService.dimensions;
console.log(`Item height: ${dimensions.itemHeight}px`);
console.log(`Items per viewport: ${dimensions.itemsPerViewport}`);
}
}Angular module providing all components, directives, and services with configuration options.
/**
* Angular module providing all ng-select functionality
* Exports all components and directives for use in templates
*/
@NgModule({
declarations: [
NgSelectComponent,
NgOptionComponent,
NgDropdownPanelComponent,
// All template directives...
],
imports: [CommonModule, FormsModule],
exports: [
NgSelectComponent,
NgOptionComponent,
NgDropdownPanelComponent,
// All template directives...
],
providers: [
NgSelectConfig,
ConsoleService,
NgDropdownPanelService,
{ provide: SELECTION_MODEL_FACTORY, useValue: DefaultSelectionModelFactory }
]
})
export class NgSelectModule {
/**
* Configure the module with custom settings
* @param config - Configuration options for the module
* @returns ModuleWithProviders for use in app module imports
*/
static forRoot(config?: Partial<NgSelectConfig>): ModuleWithProviders<NgSelectModule>;
}Usage Examples:
// Basic module import
@NgModule({
imports: [NgSelectModule],
// ...
})
export class FeatureModule {}
// Module with global configuration
@NgModule({
imports: [
NgSelectModule.forRoot({
placeholder: 'Select an option...',
notFoundText: 'No matches found',
appearance: 'material',
clearAllText: 'Clear all selections'
})
],
// ...
})
export class AppModule {}
// Standalone component imports
@Component({
selector: 'app-standalone',
standalone: true,
imports: [
NgSelectComponent,
NgOptionComponent,
NgLabelTemplateDirective,
NgOptionTemplateDirective
],
template: `
<ng-select [(ngModel)]="selected">
<ng-option *ngFor="let item of items" [value]="item">
{{ item.name }}
</ng-option>
</ng-select>
`
})
export class StandaloneSelectComponent {}Factory system for creating custom selection models with different behaviors.
/**
* Injection token for providing custom selection model factory
*/
export const SELECTION_MODEL_FACTORY: InjectionToken<SelectionModelFactory>;
/**
* Function type for creating selection model instances
*/
type SelectionModelFactory = () => SelectionModel;
/**
* Interface defining selection model behavior
*/
interface SelectionModel {
/** Currently selected items */
value: NgOption[];
/**
* Select an item
* @param item - Item to select
* @param multiple - Whether multiple selection is enabled
* @param selectableGroupAsModel - Whether groups should be part of model
*/
select(item: NgOption, multiple: boolean, selectableGroupAsModel: boolean): void;
/**
* Unselect an item
* @param item - Item to unselect
* @param multiple - Whether multiple selection is enabled
*/
unselect(item: NgOption, multiple: boolean): void;
/**
* Clear all selections
* @param keepDisabled - Whether to keep disabled items selected
*/
clear(keepDisabled: boolean): void;
}
/**
* Default selection model implementation
*/
export class DefaultSelectionModel implements SelectionModel {
value: NgOption[] = [];
select(item: NgOption, multiple: boolean, selectableGroupAsModel: boolean): void;
unselect(item: NgOption, multiple: boolean): void;
clear(keepDisabled: boolean): void;
}
/**
* Default factory function for creating selection models
*/
export function DefaultSelectionModelFactory(): SelectionModel;Usage Example:
// Custom selection model with additional behavior
class AuditedSelectionModel extends DefaultSelectionModel {
private auditLog: Array<{action: string, item: any, timestamp: Date}> = [];
select(item: NgOption, multiple: boolean, selectableGroupAsModel: boolean): void {
super.select(item, multiple, selectableGroupAsModel);
this.auditLog.push({
action: 'select',
item: item.value,
timestamp: new Date()
});
}
unselect(item: NgOption, multiple: boolean): void {
super.unselect(item, multiple);
this.auditLog.push({
action: 'unselect',
item: item.value,
timestamp: new Date()
});
}
getAuditLog() {
return this.auditLog;
}
}
// Provide custom selection model factory
@NgModule({
providers: [
{
provide: SELECTION_MODEL_FACTORY,
useValue: () => new AuditedSelectionModel()
}
]
})
export class AppModule {}