为什么我不能在Angular模板中定义内联函数?还有其他办法吗? [英] Why can't I define inline functions inside Angular templates ? How else to do it?

查看:67
本文介绍了为什么我不能在Angular模板中定义内联函数?还有其他办法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Angular 2,它是新手.我想为按钮单击调用一个小函数.所以我尝试这样做(也许我是来自React的bcos):

I'm using Angular 2 and is new to it. I wanted to invoke a small function for a button click. So I tried doing this (maybe bcos I come from a React background):

<button class="btn btn-primary" (click)="(() => { console.log('hi') })()">
  Click Me
</button>

我对(点击)属性使用了IIFE.但这没有用.为什么它不起作用,还有其他方法来声明匿名函数并在单击按钮时调用它吗?
我实际上想要做的是分配一个像这样的值:(val)=>{value = val}

I used an IIFE for the (click) attribute. But it didn't work. Why does it not work, and is there any other way to declare an anonymous function and invoke it upon button click ?
What I actually want to do is assign a value like so: (val) => { value = val }

推荐答案

如果您只提供希望Angular评估的表达式,则此方法很好用.如果您的组件具有属性,例如 value ,您可以使用以下代码:

This works fine if you just provide the expression you want Angular to evaluate. If you have a property on your component e.g. value, you can just use the following:

<button class="btn btn-primary" (click)="value = 'hi'">
    Click Me
</button>

Angular本质上只是像在函数内部一样调用您提供的代码(这是一个很大的简化,但是可以满足您的目的).

Angular essentially just calls the code that you provide as if it were inside a function (that's a big simplification, but works for your purposes).

这篇关于为什么我不能在Angular模板中定义内联函数?还有其他办法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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