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

查看:191
本文介绍了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天全站免登陆