In an Angular 2+ component, how do I pass in a callback function that takes parameters? My initial assumption was something like
<app-example [onComplete]="doThing('someParam')"></app-example>
And sometimes I won't need any parameters, like this:
<app-example [onComplete]="doSomeThingElse()"></app-example>
And then in the component I have
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
})
export class ExampleComponent {
@Input() public onComplete: () => void;
//run `this.onComplete()` somewhere as needed
}
But, what ends up happening is that the doThing('someParam') or doSomeThingElse() is immediately called without any interaction.
How am I supposed to pass callback functions in to a component to be called later?
EDIT:
The actual problem I am trying to solve here is to be able to run any passed in function at a later time. This is for a confirmation component that will ask the user "are you sure you want to continue?" and then if they press the "Yes I'm sure" button, the passed in function will run.
bindmethod will return new function every time angular calls change detection cycle. So i agree we shouldn't reinvent the wheel)@Outputto pass values back to a parent controller, but I'm not sure how I would use that here in this context. Feel free to add an answer to this question with the details, and I'll mark it as correct. Telling me to "read about" something is not very helpful to me right now.@Inputparams and then have event bound with@Outputand event will be raised with whatever arguments you want. When event is raised, your parent component will call whatever function it wants (your callback in case above) with whatever parameters it got through event.