Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 write on console from template click event

Tags:

angular

I wonder whether the following is possible somehow. The question is not limited to console.info but all Javascript functions in general.

<a (click)="console.info(foo)">click me doesn't work</a>

Cannot read property 'info' of undefined

It seems that templates can only access component properties, so you have to create an extra function for that inside your Component:

<a (click)="executeConsole(val)">execute console does work</a>

executeConsole(val) {
  console.info(val);
}

With React you can do something like that:

<a onClick={() => console.info('it works')}>it works</a>
like image 670
zurfyx Avatar asked Jan 11 '17 19:01

zurfyx


2 Answers

You would have to declare a property that can access the console object in the component ts code then call that. For example...

Declare in your component ts...

public c : any;

In the component constructor set the property to the console object...

this.c = console;

In your view you can now call info()...

<a (click)="this.c.info("Hello world")">click me</a>
like image 102
Ben Cameron Avatar answered Sep 28 '22 05:09

Ben Cameron


You can create a service wrapper for your console and inject it in the corresponding components. If you do that in typescript in the constructor, then it can automatically create a public member for you that will be accessible from template, so it will be just a matter of adding it as constructor parameter.

It seems otherwise not possible to have a "global" scope. See e.g. here.

like image 21
Ilya Chernomordik Avatar answered Sep 28 '22 06:09

Ilya Chernomordik