Visitar URL original
Component-local pipes · Issue #60849 · angular/angular · GitHub
The Wayback Machine - https://web.archive.org/web/20250720203514/https://github.com/angular/angular/issues/60849
Skip to content

Component-local pipes #60849

@junpls

Description

@junpls

Which @angular/* package(s) are relevant/related to the feature request?

core

Description

It's often tempting to make function calls in template bindings instead of using a pipe, due to the amount of boilerplate and setup that creating a pipe currently entails. This can result in performance bottlenecks, especially if the function is not cheap to compute and/or returns a value of a non-primitive data type.

I find this situation to usually occur, when there is derived state within items of an iterated collection. In the following example, consider formatUserName to be a function that is not cheap to compute and very specific to the component (i.e. low potential for app-wide reusability):

<ul>
    @for (user of users; track user.jd) {
        <li>{{ formatUserName(user) }}</li>
    }
</ul>

The typical approaches in this situation would be:

  • Writing a pure | formatUserName pipe. (-> boilerplate)
  • Wrapping the list item in a component with OnPush change detection. (-> boilerplate, especially when the parent is not a standalone component).

Proposed solution

Introducing a decorator for creating pipes from component-local functions, e.g.:

@Component({
    template: `<ul>
        @for (user of users; track user.jd) {
            <li>{{ user | formatUserName }}</li>
        }
    </ul>`,
    // ...
})
class ContactListComponent {
    // ...

    @LocalPipe() // `name` defaults to the name of the function, `pure` defaults to `true`
    formatUserName(user: User): string {
        // some computation ...
    }
}

Alternatives considered

In our project, we added generic @Cached() and @AsyncCached (adding shareReplay to the returned observable) function annotations that fulfill a similar purpose, but don't offer the same degree of optimization and syntactic sugar.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions