我在Angular2中使用DevExpress的DevExtreme。我有一个数据网格(在下面),列出了状态并要求用户选择一些状态。某些状态可能已经存储在数据库中。如何设置先前选择的状态?我可以在文档中看到应该使用dataGrid.instance.selectRows(arrayOfPreviouslySelectedStates),但是在尝试设置ngOnInit()中的dataGrid后会实例化它。

我的HTML网格:

<dx-data-grid #statesGrid id="statesContainer" [dataSource]="states" [selectedRowKeys]="[]" [hoverStateEnabled]="true" [showBorders]="true" [showColumnLines]="true" [showRowLines]="true" [rowAlternationEnabled]="true">
    <dxo-sorting mode="multiple"></dxo-sorting>
    <dxo-selection mode="multiple" [deferred]="true"></dxo-selection>
    <dxo-paging [pageSize]="10"></dxo-paging>
    <dxo-pager [showPageSizeSelector]="true" [allowedPageSizes]="[5, 10, 20]" [showInfo]="true"></dxo-pager>
    <dxo-filter-row [visible]="true"></dxo-filter-row>
    <dxi-column dataField="abbreviation" [width]="100"></dxi-column>
    <dxi-column dataField="name"></dxi-column>
</dx-data-grid>


我的componenet:

import 'rxjs/add/operator/switchMap';
import { Component, OnInit, ViewContainerRef, ViewChild } from '@angular/core';
import { CompanyService } from './../../../shared/services/company.service';
import { StateService } from './../../../shared/services/state.service';
import notify from 'devextreme/ui/notify';
import { DxDataGridModule, DxDataGridComponent } from 'devextreme-angular';

@Component({
  selector: 'app-company-detail',
  templateUrl: './company-detail.component.html'
})
export class CompanyDetailComponent implements OnInit {
  @ViewChild(DxDataGridComponent) dataGrid: DxDataGridComponent;

  companyStates: Array<ICompanyState>;
  states: Array<IState>;

  constructor(private CompanyService: CompanyService, private StateService: StateService) { }

  ngOnInit() {
    this.StateService.getStates().subscribe((states) => {
        this.getSelectedStates();
        this.states = states
    });
  }

  public getSelectedStates = (): void => {
      this.CompanyService.getStates(id).subscribe((states) => {
        let preselectedStates: Array<IState> = this.companyStates.map((state) => {
            return { abbreviation: state.Abbreviation, name: state.Name }
        });

        // I get an error here that says that dataGrid is undefined.
        this.dataGrid.instance.selectRows(preselectedStates, false);
      }
  }
}

最佳答案

感谢@yurzui的评论,我能够通过以下方式解决我的问题。 [selectedRowKeys]处理所有预选。它的“问题”是当进行其他选择时,它不会自我更新。因此,我听了onSelectionChanged并将包含有关选择的许多内容的数据的事件传递到我的自定义函数中,该函数更新了selectedStates,然后单击“保存”按钮时将其用于将数据保存到数据库。

从数据库获取预选状态

public getCompanyStates = (): void => {
    this.CompanyService.getStates().subscribe((states) => {
        this.selectedStates = states;
    });
}


事件处理程序

public onSelectionChanged = (e): void => {
    this.selectedStates = e.selectedRowKeys;
}


HTML的dx-data-grid部分

<dx-data-grid #statesGrid id="statesContainer"
    (onSelectionChanged)="onSelectionChanged($event)"
    [selectedRowKeys]="selectedStates"
    [dataSource]="states">
    ...
</dx-data-grid>

09-25 22:17