
Background:
By default, when you add a new row to a data grid like FlexGrid, the new row is empty. Often developers want newly added rows to come pre-populated with default values. FlexGrid makes this easy by using the newItemCreator property of its CollectionView, which allows you to specify a function that returns the defaults for each newly created item.
Steps to Complete:
- Initiate the grid and set its itemsSource to an Angular CollectionView.
- Use newItemCreator on the CollectionView to define the default values for newly added rows.
Getting Started:
Initiate the grid and set its itemsSource to an Angular CollectionView
You create a CollectionView for your grid’s data so that you can hook into row creation via newItemCreator. Setting allowAddNew to true enables the built-in “new row template” in the grid UI.
<!-- app.component.html -->
<wj-flex-grid
#flex
[autoGenerateColumns]="false"
[itemsSource]="items"
[allowAddNew]="true">
</wj-flex-grid>
- CollectionView wraps your source data and adds hooks like newItemCreator.
- allowAddNew enables the user to add new rows via the UI.
Use newItemCreator on the CollectionView to define the default values for newly added rows
The newItemCreator function is called whenever a new item is added (e.g., when the user starts editing the new-row template or programmatically adds a row). It returns a plain object whose properties become the default values for that new row.
// app.component.ts
import { Component, ViewChild } from '@angular/core';
import * as wjcCore from '@mescius/wijmo';
import * as wjcGrid from '@mescius/wijmo.grid';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('flex', { static: true }) flex: wjcGrid.FlexGrid;
items: any;
constructor() {
// Use a CollectionView so newItemCreator can be applied
this.items = new wjcCore.CollectionView(getData(10), {
newItemCreator: () => {
return {
id: this.getUniqueId(),
country: 'Default Country',
discount: 0,
downloads: 0,
sales: 0,
expenses: 0
};
}
});
}
// Optional helper: generate a unique ID
private getUniqueId(): number {
const arr = this.items.sourceCollection;
return Math.max(0, ...arr.map((i: any) => i.id)) + 1;
}
}
With this Angular setup, any newly added row (either via UI or programmatically) will start with your defined default values, eliminating the need for the user to manually fill every field.
Happy coding!
Andrew Peterson