0

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) {}
BigJ
  • 1,990
  • 2
  • 29
  • 47
  • Does this answer your question? [function gets called several times](https://stackoverflow.com/questions/45207357/function-gets-called-several-times) – R. Richards Dec 12 '20 at 14:57
  • @R.Richards Let me check, because I don't want to use variables and want to call a service from the template. Maybe a pipe can work, I'll have to check. – BigJ Dec 12 '20 at 14:59
  • Either create the alt text in ngOnit, or write a pipe. – David Bulté Dec 12 '20 at 20:06
  • @DavidBulté I'll try the pipe, and will post the answer if I succeed. I'm sure it will be helpful for others. – BigJ Dec 12 '20 at 22:22
  • @R.Richards Almost, but not completely: that answer did not use a service in the pipe, which threw me off, but obviously it's possible to call a service from a pipe. – BigJ Dec 23 '20 at 16:24

1 Answers1

0

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.

BigJ
  • 1,990
  • 2
  • 29
  • 47