6

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>
zurfyx
  • 31,043
  • 20
  • 111
  • 145

3 Answers3

6

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>
Ben Cameron
  • 4,335
  • 6
  • 51
  • 77
1

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.

Community
  • 1
  • 1
Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
0

How to use a global variable in an Angular component.

I know this is old, but I thought this would be helpful. You don't have to create a wrapper method. You just have to tell your component about an outside global you would like to use, then map it to your component.

Use the declare keyword:

https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html

Just write this in your component.

// Import statements...

declare const console;

@Component({
// Your Component Config
})

export class YourComponentClassName {
    public console = console;
}

Then inside your HTML file can use console like this:

<div (click)="console.info('Hello')"> </div>
Damian C
  • 2,111
  • 2
  • 15
  • 17