角度将表单对象数据推入MatTableDataSource并将其绑定到表

时间:2018-08-13 05:19:52

标签: datatable angular-material crud

我想通过将数据保存在数组对象中而不将数据保存到任何数据库来对用户表执行CRUD操作。

在此之前,我尝试使用* ngFor =“让userList的用户”进行相同的操作,这对我没有问题。但是,当我添加MatTableDataSource时,它不起作用。

user.model.ts

import { IUser } from './IUser';
import { Injectable } from '@angular/core';

import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class Usermodel {
    user: IUser;    
    userlist: IUser[];

    constructor() { }

    addOject(user: IUser): void {
        this.user = user;
        this.userlist.push(this.user);
    }

    getUsers():  Observable<IUser[]> {
        return Observable.of(this.userlist);
    }
}

userdialog.component.ts

export class UserdialogueComponent implements OnInit {

  userList: IUser[];

  // for table and pagination
  displayedColumns = ['userid', 'firstName', 'mobile', 'lastName'];
  dataSource = new MatTableDataSource<IUser>(this.userList);



  constructor(private dialog: MatDialog, private user: Usermodel) { }

  ngOnInit() {    
    this.user.getUsers()
      .subscribe(result => {
        this.userList = result;
        this.dataSource.data = this.userList;
      });
  }

  openDialog(): void {
    const dialogConfig = new MatDialogConfig(); // for default settings
    dialogConfig.position = { right: '0px' };
    dialogConfig.disableClose = true;
    const dialogRef = this.dialog.open(UserformComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(result => {

      const userData = {
        id: this.generateRandom(),
        firstName: result.data.firstName,
        lastName: result.data.lastName,
        userid: result.data.userid,
        mobile: result.data.mobile,
        accsprofile: result.data.accsprofile
      };

      this.user.addOject(userData);

    });
  }

  editDialog(userData: IUser): void {    
  }


  deleteDialog(userData: IUser): void {
    ....
  }

  generateRandom(): number {
    return Math.floor((Math.random() * 100) + 1);
  }
}

userdialog.component.html

<div class="example-container mat-elevation-z8">
        <mat-table #table *ngIf [dataSource]="dataSource">

          <ng-container matColumnDef="name">
            <mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
            <mat-cell *matCellDef="let user"> {{user.firstName}} </mat-cell>
          </ng-container>      

          <ng-container matColumnDef="userid">
            <mat-header-cell *matHeaderCellDef> User ID </mat-header-cell>
            <mat-cell *matCellDef="let user"> {{user.userid}} </mat-cell>
          </ng-container>

          <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
          <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>

        <mat-paginator #paginator
                       [pageSize]="10"
                       [pageSizeOptions]="[5, 10, 20]">
        </mat-paginator>
      </div>

0 个答案:

没有答案