or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration-services.mdindex.mdng-option-highlight.mdng-select-component.mdtemplate-directives.mdtypes-interfaces.md

configuration-services.mddocs/

0

# Configuration and Services

1

2

Angular ng-select provides a comprehensive configuration system and utility services for customizing default behavior, accessing internal functionality, and integrating with application-wide settings.

3

4

## Capabilities

5

6

### Global Configuration Service

7

8

Service for setting application-wide defaults for all ng-select components.

9

10

```typescript { .api }

11

/**

12

* Injectable service for configuring global ng-select defaults

13

* Can be provided at root level or component level for different scopes

14

*/

15

@Injectable({

16

providedIn: 'root'

17

})

18

export class NgSelectConfig {

19

/** Default placeholder text for all selects */

20

placeholder: string;

21

/** Whether placeholder should remain visible when item is selected */

22

fixedPlaceholder: boolean = true;

23

/** Default text shown when no items match search */

24

notFoundText: string = 'No items found';

25

/** Default text shown when search term is required */

26

typeToSearchText: string = 'Type to search';

27

/** Default text for add tag functionality */

28

addTagText: string = 'Add item';

29

/** Default loading text */

30

loadingText: string = 'Loading...';

31

/** Default text for clear all action */

32

clearAllText: string = 'Clear all';

33

/** Disable virtual scroll globally */

34

disableVirtualScroll: boolean = true;

35

/** Open dropdown when Enter key is pressed */

36

openOnEnter: boolean = true;

37

/** Default element to append dropdown to */

38

appendTo: string;

39

/** Default property name for item values */

40

bindValue: string;

41

/** Default property name for item labels */

42

bindLabel: string;

43

/** Default appearance style */

44

appearance: string = 'underline';

45

/** Clear search term when adding items */

46

clearSearchOnAdd: boolean;

47

/** Deselect item when clicking on selected item */

48

deselectOnClick: boolean;

49

/** Move focus to tab when clearing selection */

50

tabFocusOnClear: boolean = true;

51

}

52

```

53

54

**Usage Examples:**

55

56

```typescript

57

// Configure globally in app module or main.ts

58

import { NgSelectConfig } from '@ng-select/ng-select';

59

60

// Method 1: Using injection token

61

@NgModule({

62

providers: [

63

{

64

provide: NgSelectConfig,

65

useValue: {

66

placeholder: 'Choose an option...',

67

notFoundText: 'No results found',

68

clearAllText: 'Remove all',

69

appearance: 'material'

70

}

71

}

72

]

73

})

74

export class AppModule {}

75

76

// Method 2: Using service configuration

77

@Component({

78

providers: [NgSelectConfig]

79

})

80

export class CustomConfigComponent {

81

constructor(private config: NgSelectConfig) {

82

this.config.placeholder = 'Select from list...';

83

this.config.clearable = true;

84

this.config.appearance = 'outline';

85

}

86

}

87

88

// Method 3: Per-component configuration

89

@Component({

90

template: `

91

<ng-select

92

[config]="customConfig"

93

[(ngModel)]="selected">

94

<!-- options -->

95

</ng-select>

96

`

97

})

98

export class PerComponentConfigComponent {

99

customConfig = {

100

placeholder: 'Pick your choice',

101

clearAllText: 'Clear selection',

102

notFoundText: 'Nothing matches your search'

103

};

104

selected: any;

105

}

106

```

107

108

### Console Service

109

110

Utility service for handling warnings and debug information.

111

112

```typescript { .api }

113

/**

114

* Injectable service for console logging and warnings

115

* Used internally but can be overridden for custom logging

116

*/

117

@Injectable({

118

providedIn: 'root'

119

})

120

export class ConsoleService {

121

/**

122

* Log warning message to console

123

* @param message - Warning message to log

124

*/

125

warn(message: string): void;

126

}

127

```

128

129

**Usage Example:**

130

131

```typescript

132

// Override console service for custom logging

133

@Injectable()

134

export class CustomConsoleService extends ConsoleService {

135

warn(message: string): void {

136

// Send warnings to external logging service

137

this.loggingService.logWarning('ng-select', message);

138

super.warn(message);

139

}

140

141

constructor(private loggingService: LoggingService) {

142

super();

143

}

144

}

145

146

@NgModule({

147

providers: [

148

{ provide: ConsoleService, useClass: CustomConsoleService }

149

]

150

})

151

export class AppModule {}

152

```

153

154

### Dropdown Panel Service

155

156

Service providing calculations and utilities for dropdown panel positioning and virtual scrolling.

157

158

```typescript { .api }

159

/**

160

* Injectable service for dropdown panel calculations and virtual scrolling

161

* Handles viewport calculations, item positioning, and scroll optimization

162

*/

163

@Injectable({

164

providedIn: 'root'

165

})

166

export class NgDropdownPanelService {

167

/** Current panel dimensions and measurements */

168

dimensions: PanelDimensions;

169

170

/**

171

* Calculate visible items range for virtual scrolling

172

* @param scrollPos - Current scroll position in pixels

173

* @param itemsLength - Total number of items

174

* @param buffer - Number of buffer items to render outside viewport

175

* @returns Object containing scroll calculations and item range

176

*/

177

calculateItems(

178

scrollPos: number,

179

itemsLength: number,

180

buffer: number

181

): ItemsRangeResult;

182

183

/**

184

* Get dimensions for panel sizing calculations

185

* @param itemHeight - Height of individual items

186

* @param panelHeight - Total height of panel

187

* @returns Panel dimensions object

188

*/

189

calculateDimensions(itemHeight: number, panelHeight: number): PanelDimensions;

190

191

/**

192

* Update scroll position and recalculate visible range

193

* @param scrollTop - New scroll position

194

* @param itemsLength - Total items count

195

* @returns Updated items range

196

*/

197

scrollTo(scrollTop: number, itemsLength: number): ItemsRangeResult;

198

}

199

200

/**

201

* Interface for panel dimension calculations

202

*/

203

interface PanelDimensions {

204

/** Height of individual items in pixels */

205

itemHeight: number;

206

/** Total height of the panel in pixels */

207

panelHeight: number;

208

/** Number of items visible in current viewport */

209

itemsPerViewport: number;

210

}

211

212

/**

213

* Interface for virtual scroll calculation results

214

*/

215

interface ItemsRangeResult {

216

/** Total scroll height for scrollbar sizing */

217

scrollHeight: number;

218

/** Top padding to maintain scroll position */

219

topPadding: number;

220

/** Start index of visible range */

221

start: number;

222

/** End index of visible range */

223

end: number;

224

}

225

```

226

227

**Usage Example:**

228

229

```typescript

230

@Component({

231

template: `

232

<ng-select

233

[items]="largeItemList"

234

[virtualScroll]="true"

235

[bufferAmount]="customBuffer"

236

(scroll)="onScroll($event)">

237

</ng-select>

238

`

239

})

240

export class VirtualScrollComponent {

241

largeItemList = Array.from({length: 50000}, (_, i) => ({

242

id: i,

243

name: `Item ${i + 1}`,

244

category: `Category ${Math.floor(i / 100)}`

245

}));

246

247

customBuffer = 10;

248

249

constructor(private panelService: NgDropdownPanelService) {}

250

251

onScroll(event: {start: number, end: number}) {

252

console.log(`Visible items: ${event.start} to ${event.end}`);

253

254

// Access panel dimensions

255

const dimensions = this.panelService.dimensions;

256

console.log(`Item height: ${dimensions.itemHeight}px`);

257

console.log(`Items per viewport: ${dimensions.itemsPerViewport}`);

258

}

259

}

260

```

261

262

### Module Configuration

263

264

Angular module providing all components, directives, and services with configuration options.

265

266

```typescript { .api }

267

/**

268

* Angular module providing all ng-select functionality

269

* Exports all components and directives for use in templates

270

*/

271

@NgModule({

272

declarations: [

273

NgSelectComponent,

274

NgOptionComponent,

275

NgDropdownPanelComponent,

276

// All template directives...

277

],

278

imports: [CommonModule, FormsModule],

279

exports: [

280

NgSelectComponent,

281

NgOptionComponent,

282

NgDropdownPanelComponent,

283

// All template directives...

284

],

285

providers: [

286

NgSelectConfig,

287

ConsoleService,

288

NgDropdownPanelService,

289

{ provide: SELECTION_MODEL_FACTORY, useValue: DefaultSelectionModelFactory }

290

]

291

})

292

export class NgSelectModule {

293

/**

294

* Configure the module with custom settings

295

* @param config - Configuration options for the module

296

* @returns ModuleWithProviders for use in app module imports

297

*/

298

static forRoot(config?: Partial<NgSelectConfig>): ModuleWithProviders<NgSelectModule>;

299

}

300

```

301

302

**Usage Examples:**

303

304

```typescript

305

// Basic module import

306

@NgModule({

307

imports: [NgSelectModule],

308

// ...

309

})

310

export class FeatureModule {}

311

312

// Module with global configuration

313

@NgModule({

314

imports: [

315

NgSelectModule.forRoot({

316

placeholder: 'Select an option...',

317

notFoundText: 'No matches found',

318

appearance: 'material',

319

clearAllText: 'Clear all selections'

320

})

321

],

322

// ...

323

})

324

export class AppModule {}

325

326

// Standalone component imports

327

@Component({

328

selector: 'app-standalone',

329

standalone: true,

330

imports: [

331

NgSelectComponent,

332

NgOptionComponent,

333

NgLabelTemplateDirective,

334

NgOptionTemplateDirective

335

],

336

template: `

337

<ng-select [(ngModel)]="selected">

338

<ng-option *ngFor="let item of items" [value]="item">

339

{{ item.name }}

340

</ng-option>

341

</ng-select>

342

`

343

})

344

export class StandaloneSelectComponent {}

345

```

346

347

### Selection Model Factory

348

349

Factory system for creating custom selection models with different behaviors.

350

351

```typescript { .api }

352

/**

353

* Injection token for providing custom selection model factory

354

*/

355

export const SELECTION_MODEL_FACTORY: InjectionToken<SelectionModelFactory>;

356

357

/**

358

* Function type for creating selection model instances

359

*/

360

type SelectionModelFactory = () => SelectionModel;

361

362

/**

363

* Interface defining selection model behavior

364

*/

365

interface SelectionModel {

366

/** Currently selected items */

367

value: NgOption[];

368

369

/**

370

* Select an item

371

* @param item - Item to select

372

* @param multiple - Whether multiple selection is enabled

373

* @param selectableGroupAsModel - Whether groups should be part of model

374

*/

375

select(item: NgOption, multiple: boolean, selectableGroupAsModel: boolean): void;

376

377

/**

378

* Unselect an item

379

* @param item - Item to unselect

380

* @param multiple - Whether multiple selection is enabled

381

*/

382

unselect(item: NgOption, multiple: boolean): void;

383

384

/**

385

* Clear all selections

386

* @param keepDisabled - Whether to keep disabled items selected

387

*/

388

clear(keepDisabled: boolean): void;

389

}

390

391

/**

392

* Default selection model implementation

393

*/

394

export class DefaultSelectionModel implements SelectionModel {

395

value: NgOption[] = [];

396

397

select(item: NgOption, multiple: boolean, selectableGroupAsModel: boolean): void;

398

unselect(item: NgOption, multiple: boolean): void;

399

clear(keepDisabled: boolean): void;

400

}

401

402

/**

403

* Default factory function for creating selection models

404

*/

405

export function DefaultSelectionModelFactory(): SelectionModel;

406

```

407

408

**Usage Example:**

409

410

```typescript

411

// Custom selection model with additional behavior

412

class AuditedSelectionModel extends DefaultSelectionModel {

413

private auditLog: Array<{action: string, item: any, timestamp: Date}> = [];

414

415

select(item: NgOption, multiple: boolean, selectableGroupAsModel: boolean): void {

416

super.select(item, multiple, selectableGroupAsModel);

417

this.auditLog.push({

418

action: 'select',

419

item: item.value,

420

timestamp: new Date()

421

});

422

}

423

424

unselect(item: NgOption, multiple: boolean): void {

425

super.unselect(item, multiple);

426

this.auditLog.push({

427

action: 'unselect',

428

item: item.value,

429

timestamp: new Date()

430

});

431

}

432

433

getAuditLog() {

434

return this.auditLog;

435

}

436

}

437

438

// Provide custom selection model factory

439

@NgModule({

440

providers: [

441

{

442

provide: SELECTION_MODEL_FACTORY,

443

useValue: () => new AuditedSelectionModel()

444

}

445

]

446

})

447

export class AppModule {}

448

```