Search code examples
angularangular-pipe

Angular: Pipes vs methods in model


I use functions in models as in this example:

//user.madel.ts
class User {
    getFullname () {
        return this.firstname + '  ' + this.lastName;
    }
}

// in html I can do this:
<span> {{ user.getFullName() }} <span>

Is it proper or should I use pipes?


Solution

  • Angular pipes work best with a single value, because pure pipes have performance advantages. Since both firstname and lastname are expected to be changed, pure pipe isn't an option, and it will end as either

    {{ user.firstname | fullname(user.lastname }}
    

    or

    {{ user | fullname }}
    

    impure pipe that has no performance advantages over getter method.

    If calculations are inexpensive, it can be either getter method or get property accessor:

    get fullname () {return this.firstname + '  ' + this.lastname;}
    

    Otherwise returned value should be cached for performance reasons.