从另一个组件更新angular数据源会导致angular数据表分页无法工作



在我的ComponentA中,我从服务中获取角数据表所需的数据,并将其存储在我在服务中创建的变量数据源中

@ViewChild(MatPaginator) paginator: MatPaginator;
this.service.data = this.service.GetDataFromService();
this.service.datasource = new MatTableDataSource<this.service.data>
this.service.datasource.paginator = this.paginator;
<mat-table [dataSource]="this.service.datasource">
</mat-table>

用户可以点击编辑数据表上的行,一个表单(ComponentB)将被打开,用户可以更改该行的数据…我想从关闭后立即刷新数据表数据....数据更新,但它使分页停止工作

当用户提交表单

时,我在ComponentB中这样做
this.service.datasource = new MatTableDataSource<data>
this.service.datasource.paginator = this.paginator;

这次是这个。Paginator变得未定义,尝试了许多方法来避免在数据源刷新时混淆分页,但没有任何工作…任何建议都是非常感谢的

shared.service.ts =祝辞

@Injectable({ providedIn:'root' })
export class SharedService{
commonDataSource = new MatTableDataSource<YourDataArrayInterface>(yourDataArray);
// your data array data type array
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
}

componentA.component.ts

import { SharedService } from './path_to_sharedService';
@Component({
...
})
export class ComponentA {
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(public sharedService: SharedService){}
ngAfterViewInit() {
this.sharedService.dataSource.paginator = this.paginator;
}

componentA.component.html

<table mat-table [dataSource]="sharedService.commonDataSource">
<!-- rest of your table content -->
</table>

componentB.component.ts

import { SharedService } from './path_to_sharedService';
@Component({
...
})
export class ComponentB {  
constructor(
public sharedService: SharedService,
private fb: FormBuilder
){}
dataTableForm: FormGroup;
ngOnInit(){
this.initForm();
}

initForm(){
this.dataTableForm = this.fb.group({
... your formControls
});
}

onSubmitForm(){
if(this.dataTableForm.valid){
// based on your data you have changed change the array of service here
} else {
this.dataTableForm.markAllAsTouched();
}
}

componentB.component.html

<table mat-table [dataSource]="sharedService.commonDataSource">
<!-- rest of your table content -->
</table>

最新更新