Angular 5 Component input function that takes parameters

CBarr picture CBarr · Dec 28, 2017 · Viewed 51.8k times · Source

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.

Answer

eric99 picture eric99 · Dec 28, 2017

Here's an example of the @Output syntax @toskv was looking for, Angular pass callback function to child component as @Input

So for your example,

<app-example 
  (onComplete)="doThing()" 
  [completedParam]="'someParam'"></app-example>
@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
})
export class ExampleComponent {
  @Output() public onComplete: EventEmitter<any> = new EventEmitter();
  @Input() completedParam;

  runOnComplete(): void {
    this.onComplete.emit(this.completedParam);
  }
}

Does not feel as good as [onComplete]="doThing.bind(this, 'someParam')".