0

I've searched a while for this but I feel like this is one of the basics so no one bothers to explain it anymore...

Here's my problem.

I'm writing a component in TypeScript, which is part of an ASPNET core 2 and angular project.

TS file :

import { Component } from '@angular/core';

@Component({
    selector: 'clients',
    templateUrl: './clients.component.html',
    styleUrls: ['./clients.component.css']
})

export class ClientsComponent{
    rows: Array<any>;

    constructor() {
        let btn = document.getElementById("coolbutton");
        if (btn === null) return;
        btn.addEventListener("click", (e: Event) => this.ClickMeButton());
    }

    ClickMeButton() {
        alert("toto");
    }
}

HTML file :

<input type="button" value="Click" id="coolbutton"/>

But an error is raised when the page loads :

An unhandled exception occurred while processing the request.
NodeInvocationException: Uncaught (in promise): ReferenceError: document is 
not defined

I am unable to find any explanations on how to import document in my TS componenet...

2
  • Rather that trying to access document in the component constructor, try using the AfterViewInit lifecycle hook. Commented Feb 7, 2018 at 16:04
  • Hi ! ty for the help, im gonna look into it right now ! Commented Feb 7, 2018 at 16:06

1 Answer 1

1

just put the (click) on the element and call your function:

import { Component } from '@angular/core';

@Component({
    selector: 'clients',
    templateUrl: './clients.component.html',
    styleUrls: ['./clients.component.css']
})

export class ClientsComponent{

    constructor() {}

    public clickMeButton(): void {
        alert("toto");
    }
}

<input type="button" value="Click" (click)="clickMeButton()"/>

Sign up to request clarification or add additional context in comments.

3 Comments

even simpler. the after inits seems really powerfull but this is straight up what i wanted. TY !!
Quick question tho, the only modification was adding parenthesis around the click keyword in HTML, and the public modifier on the method (which is fine by me :). Where can i find a list of those event ? Let's say i want to do it on a text input and on the keyup event.
Hi, this is basically angular. i would suggest you read the official docs of angular: angular.io. For a quick overview about angular event binding see this articel: coursetro.com/posts/code/59/Angular-4-Event-Binding

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.