I have these two grid. The bottom one is based on the top one:

Each of the items in the lower grid is related to the Program Name and the Tool# selected from the top grid. In this picture the "Delete Tool Change" button is enable since I have selected an item from the lower grid.

Now, if I choose a different Program name and Tool# (Eg: from #6 to 1 on the top grid), and choose a different item from the bottom grid(Eg:1#), it suddenly disables the "Delete Tool Change" button.

The two grid after choosing a different item from upper grid

This is my code for the upper grid component.

  columns: ColumnDef[] = [
    { field: 'programName', name: 'Program Name', editable: false, filterField: true, width: '12em', tooltip: 'Read Only' },
    { field: 'toolNoPrefix', name: 'Tool #(Prefix)', editable: false, filterField: true, width: '12em', tooltip: 'First 8 characters of the Tool Tip - Read Only' },
    { field: 'toolNoSuffix', name: '(Suffix)', filterField: true, width: '8em' },
    { field: 'toolName', name: 'Tool Name', editable: false, filterField: true, width: '24em' },
    { field: 'tlLeadFileName', name: 'Tool File Name' },
    { field: 'typeName', name: 'Fixture Type', editable: false, width: '12em' },
    {field: 'engineerId', name: 'MSE', type: 'dropdown', 
     optionsList: this.engineers, optionsListField: 'id', optionsListName: 'lastFirstName', width: '10em'},
    { field: 'userSource', name: 'User Source', editable: false, width: '12em' },
    { field: 'tprCreateDate', name: 'Date Created', type: 'date', editable: false, width: '8em' },
];
hasLoaded = false;
resourced = false;
selectedEcmTool$: BehaviorSubject<any> = new BehaviorSubject(null);

@ViewChild('tools') dataTable: DataTableComponent;

constructor(
    private router: Router,
    private cgpAlertDialogService: CgpAlertDialogService,
    private ecmService: EcmService,
    private dialog: MatDialog,
    private readonly toastr: ToastrService
) {}

ngOnInit() {
    if (!this.selectionCriteria) {
        this._init = this.cgpAlertDialogService.showAlertDialog({
            title: 'Invalid Selection Criteria',
            message: 'A selection criteria has not been selected. Redirecting back to the main page.',
            alert: cgpAlertTypes.warning,
            closeLabel: 'OK'
        }).afterClosed().subscribe(
            () => this.router.navigate([''])
        );
    }

    if (this.router.url === '/tprecm/ecm/re-source') {
        this.resourced = true;
        this.columns.forEach(val => val.editable = false);
    }
    this.updateNameSources();
    this.hasLoaded = true;
}

ngOnDestroy() {
    if (this._init) {
        this._init.unsubscribe();
    }
}

loadECMs() {
    this.loading = true;

    const body = {
        ...this.selectionCriteria,
        filterColumn: this._currentFilters,
        reSourced: +this.resourced,
    };

    this.ecmService.getAllTools(body, this.pageOptions)
        .pipe(
            filter(Boolean),
            finalize(() => this.loading = false)
        ).subscribe((res: { totalCount: number, data: any[] }) => {
            this.total = res.totalCount;
            this.data = res.data;
            if (this.data.length >= 1) {
                this.dataTable.selections = [this.data[0]];
                this.selectedEcmTool$.next(this.data[0]);
            }

        });
}
 onSelect(selectedEcmTool) {
      this.selectedEcmTool$.next(selectedEcmTool);
   }

This is my html for the uppergrid:

<cgp-app-card titleText="View/Update ECM" showFullScreenToggle="true" [showBackButton]="true"
   [onBackButtonClicked]="onBackButtonClicked">
   <div *ngIf="hasLoaded">
      <data-table #tools [data]="data" [columns]="columns" (lazyLoad)="onLazyLoad($event)" [lazy]="true" [paging]="true"
         [pageSize]="pageOptions.size" [totalRecords]="total" [loading]="loading" [filterable]="true" (edit)="updateTool($event)"
         (select)="onSelect($event)">
         <ng-container actionStart>
            <button mat-button (keypress)="onEcmNecReportsClick()" (click)="onEcmNecReportsClick()">Nec Reports</button>
            <button mat-button (keypress)="onEcmReportsClick()" (click)="onEcmReportsClick()">ECM Reports</button>
            <button mat-button (keypress)="onToolPartRelationshipClick()" (click)="onToolPartRelationshipClick()">Edit
               Tool/Part Relationship</button>
            <button mat-button (keypress)="onEcmPartsClick()" (click)="onEcmPartsClick()">Parts</button>
            <button mat-button [disabled]="this.resourced" (keypress)="onEcmPartsUploadClick()"
               (click)="onEcmPartsUploadClick()">Upload Parts from a File</button>
         </ng-container>
         <ng-container actionEnd>
            <button mat-button>Change Log</button>
         </ng-container>
      </data-table>
      <ecm-tool-change [resourced]="this.resourced" [selectedEcmTool$]="selectedEcmTool$"></ecm-tool-change>
   </div>
</cgp-app-card>

This is my code for the lower grid component:

@Input() selectedEcmTool$: BehaviorSubject<any>;

   @ViewChild('toolChangeTable') toolChangeTable: DataTableComponent;

    constructor(
        private readonly ecmToolChangeService: EcmToolChangeService,
        private readonly ecmService: EcmService,
        private readonly dialog: MatDialog,
        private readonly toastr: ToastrService,
        private readonly confirmation: CgpConfirmationDialogService,
        private readonly cgpAlertDialogService: CgpAlertDialogService,
    ) {
    }

   onSelect(selectedEcmTool, toolChangeTable: DataTableComponent) {
      if (selectedEcmTool.dtShippedToDatabank) {
         const selected = toolChangeTable.selections;
         const index = selected.findIndex(s => s.toolId === selectedEcmTool.toolId);
         if (index !== -1) {
            toolChangeTable.selections.splice(index, 1);
         }
         this.toastr.error('You cannot check this Tool Change after you have entered the Shipped to Databank Date ');
      }
   }

   onUnSelect(dataItem) {
      return dataItem;
   }


   ngOnInit() {
      if (this.resourced) {
         this.columns.forEach((val) => val.editable = false);
      }

      this.selectedEcmTool$.subscribe(
         (selectedEcmTool) => {
            if (selectedEcmTool) {
               const toolId = selectedEcmTool.toolId;
               this.updateSelectedEcmTool(toolId);
               this.updateDesignSources();
            } else {
               this.data = [];
            }
         }
      );
   }

   ngOnDestroy() {
      if (this.selectedEcmTool$) { this.selectedEcmTool$.unsubscribe(); }
   }

   onLazyLoad(event: LazyLoadEvent) {
      this.pageOptions.order = event.sortOrder === 1 ? 'asc' : 'desc';
      this.pageOptions.size = event.rows;
      this.pageOptions.sort = event.sortField;
      this.pageOptions.page = event.first / this.pageOptions.size;
      this.updateSelectedEcmTool(this.toolId);
   }
    clearSelections() {
      this.toolChangeTable.selections = [];
   }

   updateSelectedEcmTool(toolId) {
      if (!toolId) {
         return;
      }

      this.toolId = toolId;
      this.loading = true;
      this.ecmToolChangeService.getToolChange(toolId, this.pageOptions)
         .pipe(filter(Boolean))
         .subscribe({
            next: (res: { totalCount: number, data: any[] }) => {
               this.total = res ? res.totalCount : 0;
               this.data = res ? res.data : [];
            },
            complete: () => this.loading = false
         });
   }
 
updateToolChange(event: any) {
      const body = event.data;
      body.sourceName = undefined;
      this.ecmToolChangeService.updateToolChange(body)
         .subscribe();
   }

This is my code for the lower grid html:

<data-table #toolChangeTable [columns]="columns" [data]="data" [loading]="loading"  (lazyLoad)="onLazyLoad($event)"  [lazy]="true" 
[lazyLoadOnInit]="false" [pageSize]="pageOptions.size" [multiselect]="true"  [paging] = "true" [totalRecords]="total" 
   defaultSortField="necLec" (edit)="updateToolChange($event, toolChangeTable)" (select)="onSelect($event, toolChangeTable)" (unSelect)="onUnSelect($event)">
   <ng-container actionStart>
      <button mat-button (click)="onMultiRowUpdateClick()" (keypress.enter)="onMultiRowUpdateClick()"
         [disabled]="this.resourced || hasSelectedNone">Multi-Edit</button>
      <button mat-button (click)="clearSelections()" (keypress.enter)="clearSelections()">Clear All</button>
      <button mat-button (click)="onAddToolChangeClick()" [disabled]="this.resourced">Add Tool Change</button>
      <button mat-button (click)="onDeleteToolChangeClick()" (keypress.enter)="onDeleteToolChangeClick()"
              [disabled]="!hasSelectedSingle">Delete Tool Change</button>
      <button mat-button [disabled]="!hasSelectedSingle" (click)="onEditAuthoritiesClick()"
         (keypress.enter)="onEditAuthoritiesClick()">Edit Tool Change
         Authorities</button>
   </ng-container>
</data-table>

How can I write a function or trigger ngOnDestroy so that it does not remembers the previously selected rows anymore.

2

There are 2 best solutions below

2
On

why not just call clearSelections() from within this.selectedEcmTool$.subscribe()?

every time the selectedEcmTool$ observable gets a new value, the lower grid clears it's selections.

or am I missing something?

ngOnInit() {
  if (this.resourced) {
     this.columns.forEach((val) => val.editable = false);
  }

  this.selectedEcmTool$.subscribe(
     //clear selections whenever the tool changes
     this.clearSelections();
     
     (selectedEcmTool) => {
        if (selectedEcmTool) {
           const toolId = selectedEcmTool.toolId;
           this.updateSelectedEcmTool(toolId);
           this.updateDesignSources();
        } else {
           this.data = [];
        }
     }
  );

}

0
On

I fixed it by adding:

  get hasSelectedSingleCheck(): boolean {
      return (this.toolChangeTable.selections || [])
         .filter((row) => row.toolId === this.selectedToolId).length === 1;
   }

and adding this check in the html to disable the button if its true.