简体   繁体   English

ngOnDestroy() 可以在条件下触发吗? 选择复选框时,即使在网格重新加载后,它也会记住我以前的选择

[英]Can ngOnDestroy() be triggered on condition? When selecting the checkboxes, it keeps remembering my previous selects even after the grid reload

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.现在,如果我选择不同的程序名称和工具#(例如:从顶部网格中的 #6 到 1),并从底部网格中选择不同的项目(例如:1#),它会突然禁用“删除工具更改” “ 按钮。

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:这是我用于上网格的 html:

<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:这是我的下网格 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.如何编写 function 或触发 ngOnDestroy 使其不再记住先前选择的行。

why not just call clearSelections() from within this.selectedEcmTool$.subscribe()?为什么不直接从 this.selectedEcmTool$.subscribe() 中调用 clearSelections()?

every time the selectedEcmTool$ observable gets a new value, the lower grid clears it's selections.每次 selectedEcmTool$ observable 获得一个新值时,下部网格都会清除它的选择。

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 = [];
        }
     }
  );

} }

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.并在 html 中添加此检查以禁用按钮(如果为真)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM