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>

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Meh, I was hoping there would be something better than this.
I agree, it would be nice if you could do it without changes to the component ts code.
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.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.