0

I want to do crud operations by saving the data in array object(IUser[]). So, I done adding form data to array and showing it in datatable and edit, delete is also completed by normal table with *ngFor.

Now I want to create the same using MatDataSource. I am trying since a day. Can anybody help me out. tq usermodel.ts

export class Usermodel {
    user: IUser= [];        
    userlist: any;

    constructor() { }

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

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

userdialogue.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 {
    const dialogConfig = new MatDialogConfig(); // for default settings
    dialogConfig.position = { right: '0px' };
    dialogConfig.disableClose = true;
    dialogConfig.data = userData;
    const dialogRef = this.dialog.open(UserformComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(result => {
      // console.log('Data inserted into records', result);
      if (this.isAnObject(result) && this.isEmptyObject(result)) {
        const userFormData = {
          id: result.data.id,
          firstName: result.data.firstName,
          lastName: result.data.lastName,
          userid: result.data.userid,
          mobile: result.data.mobile,
          accsprofile: result.data.accsprofile
        };

        this.user.updateUser(userFormData);
        console.log('update done', result);
      }
    });
  }      

  deleteDialog(userData: IUser): void {
    const dialogConfig = new MatDialogConfig(); // for default settings
    // dialogConfig.position = { right: '0px' };
    dialogConfig.disableClose = true;
    dialogConfig.data = { userid: userData.userid, id: userData.id };
    const dialogRef = this.dialog.open(UserdeleteComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(result => {          
      if (result) {
        this.user.deleteUser(result.id);
        console.log('deleted userid:', result.id);           
      }
    });
  }

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

userdialogue.componet.html

<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>


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

          <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
          <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
        </mat-table>
chandoo
  • 1,276
  • 2
  • 21
  • 32
  • Can you create a working stackblitz (https://stackblitz.com/fork/angular/) of this? And try this: in your `ngOnInit()` put the array you receive into your datasource: `this.dataSource.data = result;`. – Agash Thamo. Aug 10 '18 at 13:32
  • I tried using stackblitz but, could not make it. when I tried in my local I got error Cannot read property 'push' of undefined – chandoo Aug 13 '18 at 04:58
  • Well, since you are are using your `userlist` (inside your `Usermodel` class) variable as an array, you should define it like one too and initialize it so you can push your object into it: `private userlist: IUser[] = [];`, please try it again and update the question or comment on further errors. – Agash Thamo. Aug 13 '18 at 07:16
  • @AgashThamo. I updated the question and removed the edit and delete as they are not required now. Please help me to show the inserted data in the table. Tq a lot. – chandoo Aug 13 '18 at 07:47

1 Answers1

2

Based on your comments and your code I made a small example showing you how to use Observables in a service so you can change, delete and subscribe to changes.

Just returning an Observable of an array wont work since the changes are not published to the subscriber. Use a BehaviorSubject instead. Here is a good answer on SO explaining the differences.

I removed code that was not necessary for the example and made a table showing you how to edit, delete or add new data, using hardcoded data since you already got your dialogs up and running, you just need to use the functions as an example.

Here is the stackblitz. I used the latest versions of Angular and Angular Material, since it was not clear for me which version you use. I hope this helps.

Agash Thamo.
  • 748
  • 6
  • 18
  • Thamo, Tq for the support. I will try to solve the issue by following your stackblitz link. – chandoo Aug 13 '18 at 10:47
  • 1
    Sure go ahead, ask if you need some more information about the code or usage. If your Angular version is different, please tell me what version you use so I can adjust the answer and create a new stackblitz for it. – Agash Thamo. Aug 13 '18 at 11:12