单击排序按钮后将加载角度材料表数据

时间:2018-03-23 05:40:34

标签: angular angular-material angular-material2

你好我在我的项目中使用了角度材料我正在尝试创建一个带有排序和分页的表这是我的相关表的组件代码..表格数据将在我在过滤器或点击分页中写入后显示 怎么解决这个问题? 三江源

@Component({
  selector: 'app-alluser',
  templateUrl: './alluser.component.html',
  styleUrls: ['./alluser.component.scss']
})
export class AlluserComponent implements OnInit {

  constructor(private _user: UserService) {
  }

  public users;

  public tableData = [];

  displayedColumns = ['id', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', 'is_active', 'groups'];
  dataSource = new MatTableDataSource(this.tableData);

  @ViewChild(MatSort) sort: MatSort;

  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngOnInit() {
    this._user.getUsersInfo().subscribe(data => {
      this.users = data;

      for (let user of this.users) {
        this.tableData.push(
          {
            id: user.id,
            username: user.username,
            first_name: user.first_name,
            last_name: user.last_name,
            email: user.email,
            is_staff: user.is_staff,
            is_superuser: user.is_superuser,
            is_active: user.is_active,
            groups: user.groups[0]
          }
        );
      }
    });


  }


  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;

  }


  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

}

1 个答案:

答案 0 :(得分:2)

在ngOnInit中初始化MatTableDataSource

public tableData = [];

  displayedColumns = ['id', 'username', 'first_name', 'last_name', 'email', 'is_staff', 'is_superuser', 'is_active', 'groups'];
  dataSource  : MatTableDataSource<any>; //<== Declaration only

  @ViewChild(MatSort) sort: MatSort;

  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngOnInit() {
    this._user.getUsersInfo().subscribe(data => {
      this.users = data;

      for (let user of this.users) {
        this.tableData.push(
          {
            id: user.id,
            username: user.username,
            first_name: user.first_name,
            last_name: user.last_name,
            email: user.email,
            is_staff: user.is_staff,
            is_superuser: user.is_superuser,
            is_active: user.is_active,
            groups: user.groups[0]
          }
        );
      }
      this.dataSource = new MatTableDataSource(this.tableData); <== assignment
    });


  }

否则,您可以明确地调用角度变化检测

 constructor(private _user: UserService, private ref: ChangeDetectorRef) {
 }

 //And after modifying table's data:
 //this.ref.detectChanges();