Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Can a click event run a single statement?

Tags:

angular

In Angular 4, is it possible to execute code in a click event without writing a function for it? e.g.

<button (click)="bool=true; console.log("print"); Function()">Button1</button>

After doing a little reading the reason this may not be possible is that an html element, button in this case, belongs to the typescript component, not the html template, and so you wouldn't have code outside of a function there. But... I'm not sure if that's even close to a right understanding.

Edit:

This post, console.log not working in Angular2 Component (Typescript) , answers the issue with console.log, but still leaves some explanation to be desired in some other cases, such as

<button (click)="bool=true">Button1</button>

The accepted answer explains the limitations of this.

like image 521
slanden Avatar asked Jan 19 '26 10:01

slanden


1 Answers

It is possible to write small expression in click event but with limitations. Please refer to official documentation here

For example you can update the property of component instance right in the expression of click event handler without a need to wrap this simple expression in a function inside component instance.

I have created a simple counter component to demonstrate the inline expression. Please refer to this example

<button (click)="counter=counter+1">INC</button>
<button (click)="decrement()">DEC</button>

Hope this helps

like image 140
Bala Krishna Ragala Avatar answered Jan 21 '26 02:01

Bala Krishna Ragala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!