带有参数的Angular 5 Component输入函数 [英] Angular 5 Component input function that takes parameters

查看:198
本文介绍了带有参数的Angular 5 Component输入函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular 2+组件中,如何传递带有参数的回调函数? 我最初的假设是

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>

然后在我拥有的组件中

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
}

但是,最终发生的是doThing('someParam')doSomeThingElse()被立即调用而没有任何交互.

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?

我要在这里解决的实际问题是以后可以运行任何传入的函数.这是一个确认组件,它将询问用户您确定要继续吗?"然后如果他们按下是的"按钮,则传入的功能将运行.

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.

推荐答案

以下是@toskv正在寻找的@Output语法示例,

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

因此,您的示例

<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);
  }
}

感觉不如[onComplete]="doThing.bind(this, 'someParam')".

这篇关于带有参数的Angular 5 Component输入函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆