Home > Software design >  Execute a function after template has been render in ngIf. Which one is better Pipe or Directive
Execute a function after template has been render in ngIf. Which one is better Pipe or Directive

Time:12-07

Here is code example for the above question.

<div *ngIf="condition">
   <button>Save</button>
<div>

I want to call a function after button is created. I have found two solution for this.

First one is to use Directive

<div *ngIf="condition">
   <button ngInit="callback()">Save</button>
<div>

Second one is to use pipe

<div *ngIf="condition">
   {{callback| ngInit}}
   <button>Save</button>
<div>

My question is which one is better based on performance. Or do you have some other solution.

CodePudding user response:

Using pipes might be a solution but not a good one. According to angular Documentation; pipes are used for transforming data.

Using Directive could be a solution, but you would need to create an extra file for it.

Your could instead use ngAfterViewInit in your component class and check if condition true execute callback.

ngAfterViewInit() {
    this.callback();
}

If your condition value could change after the view is rendered, then you must call your callback each time the condition is changed to true.

In this case you do not need to create extra files to handle this calls for you.

CodePudding user response:

I would use ViewChild with a setter to watch changes of the actual button. If the button is shown/hidden the setter will execute. In that, you can check if the element exists, if it does, then execute your function.

So, attach a ref to your button, for example conditionButton:

<button #conditionButton>Save</button>

In component, declare the ViewChild with a setter:

@ViewChild('conditionButton') 
  set watch(button: ElementRef) {
    if(button) { 
      console.log("button exists, do something!");
    }
  }
}

STACKBLITZ, where button is initially hidden, after 2 seconds it is shown, after 4 seconds hidden again:

  • Related