Angular2 - Object toString method

11.6k views Asked by At

I noticed an interesting application to add toString this object, I wonder if it's a good solution? Is this expected behavior template interpolation?

For example:

class Person {
   name: string;
   surname: string;

   toString(): string {
       return this.name + ' ' + this.surname;
   }
}

When we display this object in template, insted of [object Object] we see toString method result.

Username: {{ person }} // Result "Name Surname" insted of "[object Object]"

What do you think about it? I know that this is due to the fact that the angular convert object to string, but is it good to use this solution?

1

There are 1 answers

4
Günter Zöchbauer On BEST ANSWER

I think toString() should be used for debugging purposes only.

For production I would rather use something like

class Person {
   name: string;
   surname: string;

   fullName(): string {
       return this.name + ' ' + this.surname;
   }
}
Username: {{ person.fullName }}