Remove attribute/element from change detection in Angular

316 Views Asked by At

Suppose I have this in my template:

<img src="..." alt="myService.getImgAlt()" />

This works... But at every change detection this function will be called, which is bad for performance. Is it possible to remove this attribute (or entire element) from change detection after the first time getImgAlt() is called?

I want to call myService from the template directly, which means a function call is needed and I can't just use a variable from the component. The component just defines the service so the template has access to it:

export class MyComponent {

    constructor(public myService: MyService) {}
1

There are 1 best solutions below

0
On BEST ANSWER

You can use a (pure) pipe because from there you can call a service, and the pipe only get executed once:

@Pipe({ name: 'myPipe' })
export class MyPipe implements PipeTransform {

    constructor(private someService: SomeService) {}

    transform(someExampleId: string): string {

        return this.someService.getSomething(someExampleId);

    }

}

To use to pipe in the template:

<img src="..." alt="{{ '1234' | myPipe }}" />

Because the input to the pipe (1234) does not change, the pipe is only executed once, which is good for performance.