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>
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 }
An inline HTML template for a component is defined using template config in @Component decorator, as shown below. It can be a single line template wrapped inside double quotes or single quotes. It can also be a multi-line template wrapped inside backticks char `.
Because expression are so powerful, they can easily grow in complexity when our views become more complex. While function calls in Angular templates are super convenient and technically valid, they may cause serious performance issues.
Example 1. C++ Copy. // inline_keyword1.cpp // compile with: /c inline int max( int a , int b ) { if( a > b ) return a; return b; } A class's member functions can be declared inline, either by using the inline keyword or by placing the function definition within the class definition.
A member function that is defined inside its class member list is called an inline member function. Member functions containing a few lines of code are usually declared inline.
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 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).
Just leaving this for future viewers:
I found this documentation which states that the supported syntax is limited (not every valid Javascript statement will be valid)
Like template expressions, template statements use a language that looks like JavaScript. However, the parser for template statements differs from the parser for template expressions. In addition, the template statements parser specifically supports both basic assignment, =, and chaining expressions with semicolons, ;. The following JavaScript and template expression syntax is not allowed: new, increment and decrement operators, ++ and -- operator assignment, such as += and -= the bitwise operators, such as | and & the pipe operator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With