Angular2 通过属性将函数传递给指令 [英] Angular2 passing a function to a directive via attribute

查看:25
本文介绍了Angular2 通过属性将函数传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将父组件中的函数绑定到子组件上的属性中.

I'm trying to bind a function in a parent component into a property on a child component.

这就是我所拥有的

@Component({
  selector: 'awesome',
  templateUrl: 'awesome.html'
})
export class AwesomeComponent {

@Input() callback: Function;

ngOnInit() {

    this.callback();//Error, this.callback is not a function,  but contains a string value on the fuction call
    }
}

这就是我使用它的方式

<awesome callback="nameOfFuncFromAnotherComponent"></awesome>

但它似乎不起作用

推荐答案

您的代码仅将字符串 nameOfFuncFromAnotherComponent 绑定到 callback 属性(和属性,如果存在).Angular 根本不解释该值.

Your code only binds the string nameOfFuncFromAnotherComponent to the callback attribute (and property if it exists). Angular doesn't interpret the value at all.

让Angular管理绑定使用

To make Angular manage the binding use

<awesome [callback]="nameOfFuncFromAnotherComponent"></awesome>

使用这种语法,Angular 也会计算值

With this syntax Angular also evaluates the value

<awesome callback="{{nameOfFuncFromAnotherComponent}}"></awesome>

但在赋值之前将结果转换为字符串(调用 .toString()).

but converts the result to a string (calls .toString()) before the assignment.

感谢@MarkRajcok 的澄清:)

Thanks to @MarkRajcok for clarification :)

这篇关于Angular2 通过属性将函数传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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