Gopikrishna Mandapati
Gopikrishna Mandapati

Reputation: 93

How to call a user defined method in angular material table?

How to call a user defined method in angular material table? I am using a class object instead of an Interface and when I call that method and its not working. I was able to display the properties but not the method output.

Here is the code snippet.

export class User implements IUser {

constructor(public id:number, public email: string,
  public first_name: string, public last_name: string, public avatar: string) {
    console.error("Construcor Eroor.")
  }

  upper(): string {
    console.log(this.email.toUpperCase())
    return this.email.toUpperCase();
  }
}



<ng-container matColumnDef="upper">
    <mat-header-cell *matHeaderCellDef>
        upper
    </mat-header-cell>
    <mat-cell *matCellDef="let user ">
        {{user.upper}} <!-- calling a method in the User class -->
    </mat-cell>
</ng-container>

Here is the complete stackblitz link. https://stackblitz.com/edit/angular-material-reactive-table-ddcsq4

Upvotes: 0

Views: 1481

Answers (2)

wentjun
wentjun

Reputation: 42536

You should map your response from your service (sampleSvc) into an array of User objects, such that you will be able to access the User instance, thus able to call the upper() method from the User class.

this.sampleSvc.findByKey(key).subscribe(data => {
  const users = data.map(obj => new User(
    obj.id,
    obj.email,
    obj.first_name,
    obj.last_name,
    obj.avatar,
  ));
  this.userSubject.next(users);
});

In addition, on your template component.html, you will need to call the upper() method

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

I have fixed it in your demo over here.

Upvotes: 1

prashant.kr.mod
prashant.kr.mod

Reputation: 1692

Here is the modified code:

app.component.html:

<hello [name]='name'></hello>
<app-sample></app-sample>

With the above edited code, you will be able to see the name as Angular:
enter image description here

Hope this helps!!!

Upvotes: 0

Related Questions