Why can't I define inline functions inside Angular templates ? How else to do it?

Viewed 12565

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 }

3 Answers

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

In Angular when ever you call any function it checks for that specific function in its component.ts file.

So for example when you calling console it will be looking for a object named console with log as a function in that object in the corresponding component.ts file so console will come undefined.

you can create a function named log in the component file and then call it in the template where ever you want.

component.ts

log(value) {
    console.log(value);
}

html template

<button class="btn btn-primary" (click)="log('message')">

Click Me

Related