Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 78 additions & 2 deletions projects/igniteui-angular/grids/core/src/row.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
Directive,
DoCheck,
ElementRef,
EmbeddedViewRef,
EventEmitter,
forwardRef,
HostBinding,
Expand All @@ -14,14 +15,16 @@ import {
OnDestroy,
Output,
QueryList,
TemplateRef,
ViewChild,
ViewChildren
ViewChildren,
ViewContainerRef
} from '@angular/core';
import { IgxGridForOfDirective } from 'igniteui-angular/directives';
import { ColumnType, mergeObjects, TransactionType } from 'igniteui-angular/core';
import { IgxGridSelectionService } from './selection/selection.service';
import { IgxEditRow } from './common/crud.service';
import { CellType, GridType, IGX_GRID_BASE } from './common/grid.interface';
import { CellType, GridType, IGX_GRID_BASE, IgxRowSelectorTemplateContext } from './common/grid.interface';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { trackByIdentity } from 'igniteui-angular/core';
Expand Down Expand Up @@ -192,6 +195,20 @@ export class IgxRowDirective implements DoCheck, AfterViewInit, OnDestroy {
@ViewChild(forwardRef(() => IgxCheckboxComponent), { read: IgxCheckboxComponent })
public checkboxElement: IgxCheckboxComponent;

/**
* @hidden
* @internal
* Anchor for the custom row selector template, rendered via `updateRowSelectorView`.
*/
@ViewChild('rowSelectorOutlet', { read: ViewContainerRef })
protected rowSelectorOutlet: ViewContainerRef;

private _rowSelectorViewRef: EmbeddedViewRef<IgxRowSelectorTemplateContext>;
private _rowSelectorViewKey: any;
private _rowSelectorViewTemplate: TemplateRef<IgxRowSelectorTemplateContext>;
private _rowSelectorViewSelected: boolean;
private _rowSelectorViewIndex: number;

@ViewChildren('cell')
protected _cells: QueryList<CellType>;

Expand Down Expand Up @@ -237,6 +254,22 @@ export class IgxRowDirective implements DoCheck, AfterViewInit, OnDestroy {
this.grid.cdr.markForCheck();
}

/**
* @hidden
* @internal
* Context for the custom row selector template.
*/
public get rowSelectorContext(): IgxRowSelectorTemplateContext {
return {
$implicit: {
index: this.viewIndex,
rowID: this.key,
key: this.key,
selected: this.selected
}
};
}

/**
* @hidden
*/
Expand Down Expand Up @@ -484,6 +517,48 @@ export class IgxRowDirective implements DoCheck, AfterViewInit, OnDestroy {
public ngAfterViewInit() {
// If the template of the row changes, the forOf in it is recreated and is not detected by the grid and rows can't be scrolled.
this._virtDirRow.changes.pipe(takeUntil(this.destroy$)).subscribe(() => this.grid.resetHorizontalVirtualization());
this.updateRowSelectorView();
}

/**
* @hidden
* @internal
* Renders the custom row selector template, re-creating its view whenever this row component is
* recycled for a different record (or the template changes). Interactive native elements in the
* template (e.g. `<input type="checkbox" [checked]>`) mutate their own DOM state; when such DOM
* is reused for another record, Angular skips re-writing a binding whose value appears unchanged
* and the stale visual state would stick (#17292). A fresh view per record guarantees the first
* binding write always happens against pristine DOM.
*/
protected updateRowSelectorView(): void {
const outlet = this.rowSelectorOutlet;
const template = this.grid.rowSelectorTemplate;
if (!outlet || !template) {
this._rowSelectorViewRef = undefined;
return;
}
const selected = this.selected;
const index = this.viewIndex;
if (!this._rowSelectorViewRef || this._rowSelectorViewRef.destroyed
|| template !== this._rowSelectorViewTemplate || this.key !== this._rowSelectorViewKey) {
// Different row/template - render a fresh view so a native checkbox is not shown with a
// recycled DOM state that Angular would skip re-writing (#17292).
outlet.clear();
this._rowSelectorViewTemplate = template;
this._rowSelectorViewKey = this.key;
this._rowSelectorViewSelected = selected;
this._rowSelectorViewIndex = index;
this._rowSelectorViewRef = outlet.createEmbeddedView(template, this.rowSelectorContext);
this._rowSelectorViewRef.detectChanges();
} else if (selected !== this._rowSelectorViewSelected || index !== this._rowSelectorViewIndex) {
// Same record, but its selection/index changed - refresh just this view. Needed because
// the selector is a transplanted view that the row's normal change detection does not
// update on programmatic selection changes (e.g. select all, cascade).
this._rowSelectorViewSelected = selected;
this._rowSelectorViewIndex = index;
this._rowSelectorViewRef.context.$implicit = this.rowSelectorContext.$implicit;
this._rowSelectorViewRef.detectChanges();
}
}

/**
Expand Down Expand Up @@ -598,6 +673,7 @@ export class IgxRowDirective implements DoCheck, AfterViewInit, OnDestroy {
*/
public ngDoCheck() {
this.cdr.markForCheck();
this.updateRowSelectorView();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
SingleRowSelectionComponent,
RowSelectionWithoutPrimaryKeyComponent,
SelectionWithTransactionsComponent,
GridCustomSelectorsComponent
GridCustomSelectorsComponent,
GridCustomNativeSelectorComponent
} from '../../../test-utils/grid-samples.spec';
import { GridFunctions, GridSelectionFunctions } from '../../../test-utils/grid-functions.spec';
import { SampleTestData } from '../../../test-utils/sample-test-data.spec';
Expand All @@ -30,7 +31,8 @@ describe('IgxGrid - Row Selection #grid', () => {
RowSelectionWithoutPrimaryKeyComponent,
SingleRowSelectionComponent,
SelectionWithTransactionsComponent,
GridCustomSelectorsComponent
GridCustomSelectorsComponent,
GridCustomNativeSelectorComponent
]
}).compileComponents();
}));
Expand Down Expand Up @@ -2386,6 +2388,39 @@ describe('IgxGrid - Row Selection #grid', () => {
grid.rowSelection = GridSelectionMode.multiple;
}));

it('Should keep a native custom row selector checkbox in sync when rows are recycled (#17292)', async () => {
// Uses a harness whose data is re-sorted selected-first with fresh record objects, so the
// grid recycles row DOM by slot (the #17292 scenario). A native <input> is toggled by the
// click, which is what desyncs its DOM from Angular's cached [checked] binding value.
const nativeFix = TestBed.createComponent(GridCustomNativeSelectorComponent);
nativeFix.detectChanges();
const nativeGrid = nativeFix.componentInstance.grid;
nativeFix.detectChanges(); // second pass enables the scrollbar / virtualization

const getNativeCheckbox = (row) =>
GridSelectionFunctions.getRowCheckboxDiv(row.nativeElement).querySelector('input[type="checkbox"]') as HTMLInputElement;
const clickRow = async (index) => {
getNativeCheckbox(nativeGrid.gridAPI.get_row_by_index(index)).click();
await wait(DEBOUNCETIME);
nativeFix.detectChanges();
};

// Select two records - they sort to the top.
await clickRow(0);
await clickRow(1);

// Deselect the top record - its element's DOM is toggled off and the other selected
// record is recycled into that same element.
await clickRow(0);
await wait(SCROLL_DEBOUNCETIME);
nativeFix.detectChanges();

// Every rendered row's native checkbox must match its actual selection state.
for (const row of nativeGrid.rowList.toArray()) {
expect(getNativeCheckbox(row).checked).toBe(row.selected);
}
});

it('Should have the correct properties in the custom row selector template', () => {
const firstRow = grid.gridAPI.get_row_by_index(0);
const firstCheckbox = firstRow.nativeElement.querySelector('.igx-checkbox__composite');
Expand Down
21 changes: 5 additions & 16 deletions projects/igniteui-angular/grids/grid/src/grid-row.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,11 @@
(pointerdown)="$event.preventDefault()"
(click)="onRowSelectorClick($event)"
>
<ng-template
*ngTemplateOutlet="
this.grid.rowSelectorTemplate
? this.grid.rowSelectorTemplate
: rowSelectorBaseTemplate;
context: {
$implicit: {
index: viewIndex,
rowID: key,
key,
selected: selected,
},
}
"
>
</ng-template>
@if (this.grid.rowSelectorTemplate) {
<ng-container #rowSelectorOutlet></ng-container>
} @else {
<ng-template *ngTemplateOutlet="rowSelectorBaseTemplate"></ng-template>
}
</div>
}
@if (grid.groupingExpressions.length > 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,24 +52,11 @@
(click)="onRowSelectorClick($event)"
(pointerdown)="$event.preventDefault()"
>
<ng-template
*ngTemplateOutlet="
this.grid.rowSelectorTemplate
? this.grid.rowSelectorTemplate
: rowSelectorBaseTemplate;
context: {
$implicit: {
index: viewIndex,
rowID: key,
key,
selected: selected,
select: select,
deselect: deselect,
},
}
"
>
</ng-template>
@if (this.grid.rowSelectorTemplate) {
<ng-container #rowSelectorOutlet></ng-container>
} @else {
<ng-template *ngTemplateOutlet="rowSelectorBaseTemplate"></ng-template>
}
</div>
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
} from '@angular/core';
import { IgxRowDirective } from 'igniteui-angular/grids/core';
import { IgxHierarchicalGridCellComponent } from './hierarchical-cell.component';
import { GridType } from 'igniteui-angular/grids/core';
import { GridType, IgxRowSelectorTemplateContext } from 'igniteui-angular/grids/core';
import { IgxGridNotGroupedPipe, IgxGridCellStylesPipe, IgxGridCellStyleClassesPipe, IgxGridDataMapperPipe, IgxGridTransactionStatePipe } from 'igniteui-angular/grids/core';
import { IgxRowDragDirective } from 'igniteui-angular/grids/core';
import { NgTemplateOutlet, NgClass, NgStyle } from '@angular/common';
Expand Down Expand Up @@ -138,6 +138,17 @@ export class IgxHierarchicalRowComponent extends IgxRowDirective {
this.grid.deselectRows([this.key]);
};

/**
* @hidden
* @internal
*/
public override get rowSelectorContext(): IgxRowSelectorTemplateContext {
const context = super.rowSelectorContext;
context.$implicit.select = this.select;
context.$implicit.deselect = this.deselect;
return context;
}

/**
* @hidden
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,11 @@
(click)="onRowSelectorClick($event)"
(pointerdown)="$event.preventDefault()"
>
<ng-template
*ngTemplateOutlet="
this.grid.rowSelectorTemplate
? this.grid.rowSelectorTemplate
: rowSelectorBaseTemplate;
context: {
$implicit: {
index: viewIndex,
rowID: key,
key,
selected: selected,
},
}
"
>
</ng-template>
@if (this.grid.rowSelectorTemplate) {
<ng-container #rowSelectorOutlet></ng-container>
} @else {
<ng-template *ngTemplateOutlet="rowSelectorBaseTemplate"></ng-template>
}
</div>
}
@if (pinnedStartColumns.length > 0) {
Expand Down
38 changes: 38 additions & 0 deletions projects/igniteui-angular/test-utils/grid-samples.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1453,6 +1453,44 @@ export class GridCustomSelectorsComponent extends BasicGridComponent implements
}
}

@Component({
template: `
<igx-grid #grid [data]="data" [primaryKey]="'ID'" [rowSelection]="'multiple'" [autoGenerate]="false"
[height]="'300px'" [width]="'500px'" [selectedRows]="selectedIds"
(rowSelectionChanging)="onSelectionChanging($event)">
<igx-column field="ID" header="ID" [width]="'120px'"></igx-column>
<igx-column field="ContactName" header="ContactName"></igx-column>
<ng-template igxRowSelector let-rowContext>
<input type="checkbox" [checked]="rowContext.selected" />
</ng-template>
</igx-grid>`,
changeDetection: ChangeDetectionStrategy.Eager,
imports: [IgxGridComponent, IgxColumnComponent, IgxRowSelectorDirective]
})
export class GridCustomNativeSelectorComponent {
@ViewChild('grid', { static: true })
public grid: IgxGridComponent;

// Keeps selected records sorted to the top, producing NEW record objects on every recompute so
// the grid recycles row DOM by slot (mirrors the #17292 repro).
public base: any[] = SampleTestData.contactInfoDataFull();
public selectedIds: any[] = [];
public data: any[] = this.resort();

public onSelectionChanging(event: any): void {
// newSelection holds selected data records; r.ID is the primary key.
this.selectedIds = event.newSelection.map((r: any) => r.ID);
this.data = this.resort();
}

private resort(): any[] {
const selected = new Set(this.selectedIds);
return this.base
.map(r => ({ ...r }))
.sort((a, b) => (Number(selected.has(b.ID)) - Number(selected.has(a.ID))) || (a.ID > b.ID ? 1 : -1));
}
}

@Component({
template: `
<igx-grid #grid [data]="data" [primaryKey]="'ProductID'" width="900px" height="600px" [rowEditable]="true">
Expand Down
5 changes: 5 additions & 0 deletions src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
changeDetection: ChangeDetectionStrategy.Eager,

Check warning on line 41 in src/app/app.component.ts

View workflow job for this annotation

GitHub Actions / run-tests

Components should not opt out of the default `ChangeDetectionStrategy.OnPush` change detection strategy
imports: [
IgxNavigationDrawerComponent,
IGX_NAVIGATION_DRAWER_DIRECTIVES,
Expand Down Expand Up @@ -434,6 +434,11 @@
icon: 'view_column',
name: 'Grid Selection'
},
{
link: '/gridRowSelectorCd',
icon: 'view_column',
name: 'Grid Row Selector CD (#17292)'
},
Comment on lines +437 to +441
{
link: '/gridRowDrag',
icon: 'view_column',
Expand Down Expand Up @@ -830,7 +835,7 @@
return this.styleLinks.filter(item => item.name.toLowerCase().includes(filterValue));
});

constructor(private router: Router, private iconService: IgxIconService) {

Check warning on line 838 in src/app/app.component.ts

View workflow job for this annotation

GitHub Actions / run-tests

Prefer using the inject() function over constructor parameter injection. Use Angular's migration schematic to automatically refactor: ng generate @angular/core:inject

Check warning on line 838 in src/app/app.component.ts

View workflow job for this annotation

GitHub Actions / run-tests

Prefer using the inject() function over constructor parameter injection. Use Angular's migration schematic to automatically refactor: ng generate @angular/core:inject
iconService.setFamily('fa-solid', { className: 'fa', type: 'font', prefix: 'fa-'});
iconService.setFamily('fa-brands', { className: 'fab', type: 'font' });

Expand Down
5 changes: 5 additions & 0 deletions src/app/app.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ import { GridSummaryComponent } from './grid-summaries/grid-summaries.sample';
import { GridPerformanceSampleComponent } from './grid-performance/grid-performance.sample';
import { GridRemotePagingSampleComponent } from './grid-remote-paging/grid-remote-paging.sample';
import { GridSelectionComponent } from './grid-selection/grid-selection.sample';
import { GridRowSelectorCdSampleComponent } from './grid-row-selector-cd/grid-row-selector-cd.sample';
import { GridRowDraggableComponent } from './grid-row-draggable/grid-row-draggable.sample';
import { GridToolbarSampleComponent } from './grid-toolbar/grid-toolbar.sample';
import { GridToolbarCustomSampleComponent } from './grid-toolbar/grid-toolbar-custom.sample';
Expand Down Expand Up @@ -530,6 +531,10 @@ export const appRoutes: Routes = [
path: 'gridSelection',
component: GridSelectionComponent
},
{
path: 'gridRowSelectorCd',
component: GridRowSelectorCdSampleComponent
},
Comment on lines +534 to +537
{
path: 'gridRowDrag',
component: GridRowDraggableComponent
Expand Down
Loading
Loading