Search code examples
angularangular-ng-if

Angular: function inside *ngIf causes performance issues but what is the alternative?


So I have an issue with performance and figured out throughsearching the web that it's caused by all the functions that I have inside *ngIf's. Some recommedations are to use pipes or to use get accessors. I tried pipes and it does not work and I can't use get accessors as the functions havet parameters.

some functions are simple and others more complex. The state can be changed by the user by adding or deleting things from arrays so it has to stay dynamic. example function

function inBothArrays(id, array1, array2) {
    if(array1.includes(id) && array2.includes(id)){
        return true
    } else {
        return false
    } 
}

Solution

  • What would i do is create a pipe for the job. As stated in Angular documentation

    Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).

    So what you probably need is to create a "inBothArraysPipe" that takes as input both the arrays and the item to check as a single object who's reference changes only when you decide to change it. You would then modify your code like this:

    1) turn your *ngIf in something like

    *ngIf=" checkDto | inBothArrays "
    

    2) define checkDto in your component as

    checkDto : {id: any, array1: any[], array2 : any[]}
    

    3) be sure to change the reference of checkDto every time you:

    • modify array1
    • modify array2
    • modify the id

    To change the reference you can throw in a

    JSON.parse(JSON.stringify(checkDto))
    

    or

    Object.assign({}, checkDto)