CBa*_*arr 11 typescript angular angular5
在Angular 2+组件中,如何传入带参数的回调函数?我最初的假设是这样的
<app-example [onComplete]="doThing('someParam')"></app-example>
Run Code Online (Sandbox Code Playgroud)
有时候我不需要任何参数,比如:
<app-example [onComplete]="doSomeThingElse()"></app-example>
Run Code Online (Sandbox Code Playgroud)
然后在我的组件中
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
}
Run Code Online (Sandbox Code Playgroud)
但是,什么最终情况是,doThing('someParam')或者doSomeThingElse()是直接调用的,没有任何互动.
我应该如何将回调函数传递给稍后要调用的组件?
我试图在这里解决的实际问题是能够在以后运行任何传入的函数.这是一个确认组件,它会询问用户"你确定要继续吗?" 然后,如果他们按下"是的我确定"按钮,传入的功能将运行.
eri*_*c99 20
这是@Output@toskv正在寻找的语法示例,Angular传递回调函数到子组件@Input
所以对你的例子来说,
<app-example
(onComplete)="doThing()"
[completedParam]="'someParam'"></app-example>
Run Code Online (Sandbox Code Playgroud)
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
感觉不如[onComplete]="doThing.bind(this, 'someParam')".
| 归档时间: |
|
| 查看次数: |
36841 次 |
| 最近记录: |