Home > Software engineering >  Only call method once when binding attribute in Angular
Only call method once when binding attribute in Angular

Time:06-16

In the [data] attribute in the object tag, a method is called that returns a link to a PDF, which then the browsers default PODF viewer. The problem that I am encountering is that the PDF viewer keeps flashing because the method keeps getting called and returning the URL. Is there a way I can only fire this method once?

 <div *ngSwitchCase="'pdf'"
       id="pdf"
       >

    <object style="width: 100%; height: 100%;"
            [data]="returnEncodedLink()"> </object>

  </div>

CodePudding user response:

Use getter method and it will be only trigger if its return value changed. Ts file:

encodedLinkData = ''
...
get returnEncodedLink(){
return encodedLinkData
}

Html file:

 <div *ngSwitchCase="'pdf'"
       id="pdf"
       >

    <object style="width: 100%; height: 100%;"
            [data]="encodedLinkData"> </object>

  </div>

CodePudding user response:

Every time change detection fires it will check all variables in your template to see if they have changed.

If you provide a function, change detection will need to call the function in order to see if it returns a different value.

If you only want your function to be called once, then just call it in the ngOnInit lifecycle hook, and assign the result to a variable. Then change detection can simply check the identity of this variable rather than calling your function.

In component ts file

encodedLink = '';

ngOnInit(){
   this.encodedLink = this.returnEncodedLink();
}

html

<div *ngSwitchCase="'pdf'" id="pdf" >
  <object
    style="width: 100%; height: 100%"
    [data]="encodedLink"
  ></object>
</div>
  • Related