Angular + Material - How to refresh a data source (mat-table)

前端 未结 23 1354
自闭症患者
自闭症患者 2020-11-28 01:59

I am using a mat-table to list the content of the users chosen languages. They can also add new languages using dialog panel. After they added a language and returned back.

23条回答
  •  一生所求
    2020-11-28 03:04

    Trigger a change detection by using ChangeDetectorRef in the refresh() method just after receiving the new data, inject ChangeDetectorRef in the constructor and use detectChanges like this:

    import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
    import { LanguageModel, LANGUAGE_DATA } from '../../../../models/language.model';
    import { LanguageAddComponent } from './language-add/language-add.component';
    import { AuthService } from '../../../../services/auth.service';
    import { LanguageDataSource } from './language-data-source';
    import { LevelbarComponent } from '../../../../directives/levelbar/levelbar.component';
    import { DataSource } from '@angular/cdk/collections';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/of';
    import { MatSnackBar, MatDialog } from '@angular/material';
    
    @Component({
      selector: 'app-language',
      templateUrl: './language.component.html',
      styleUrls: ['./language.component.scss']
    })
    export class LanguageComponent implements OnInit {
      displayedColumns = ['name', 'native', 'code', 'level'];
      teachDS: any;
    
      user: any;
    
      constructor(private authService: AuthService, private dialog: MatDialog,
                  private changeDetectorRefs: ChangeDetectorRef) { }
    
      ngOnInit() {
        this.refresh();
      }
    
      add() {
        this.dialog.open(LanguageAddComponent, {
          data: { user: this.user },
        }).afterClosed().subscribe(result => {
          this.refresh();
        });
      }
    
      refresh() {
        this.authService.getAuthenticatedUser().subscribe((res) => {
          this.user = res;
          this.teachDS = new LanguageDataSource(this.user.profile.languages.teach);
          this.changeDetectorRefs.detectChanges();
        });
      }
    }
    

提交回复
热议问题