2

I need to run a javascript code in my angular project, and following other questions on SO I could run a hello world js file. However, there is no example for usage of more advanced js files like cases in which js needs html elements of the angular component.

Following is my simplified myGame.js file:

export function greeting(){
    alert("Greeting from javascript");
}

var canvas, context;
export function initializeScenes() {
    canvas = document.getElementById("canvas");
    if (canvas)
        context = canvas.getContext("2d");
    else
        alert("No canvas");

}

and my runjavascript.component.ts:

import * as myGame from "../../../../assets/myGame.js"
.
.
.
export class RunJavascriptComponent {
    constructor() {
       myGame.greeting();
       myGame.initializeScenes()

    }    
}


and my runjavascript.component.htm:

<div class="container">
    <canvas id="canvas" width="600" height="400"></canvas>
</div>

When I run ng serve, I see "Greeting from javascript", which means greeting() is called successfully, but then I get the alert "No canvas", which I think means canvas element of my angular component.html is not recognized!

Does anyone know how to solve the problem? Thank you in advance.

0

1 Answer 1

3

If you want to access the HTML contents using angular you can use ngAfterViewInit hook, which is called after the HTML is initialized.

import * as myGame from "../../../../assets/myGame.js"
.
.
.
export class RunJavascriptComponent {
    
    ngAfterViewInit() {
       myGame.greeting();
       myGame.initializeScenes();
    }    
}

If you are open to modifying myGame.js convert the querySelector with a viewChild which is the angular way of accessing HTML elements.

import * as myGame from "../../../../assets/myGame.js"
.
.
.
export class RunJavascriptComponent {
    canvas = viewChild('canvas');
    
    ngAfterViewInit() {
       myGame.greeting();
       if (this.canvas()?.nativeElement) {
         myGame.initializeScenes(this.canvas().nativeElement);
       }
    }    
}

Then modify the JS as below:

export function initializeScenes(canvas: any) {
    if (canvas) {
        context = canvas.getContext("2d");
    } else {
        alert("No canvas");
    }
}

We need a template reference variable to refer the element, that is used inside the viewChild:

<div class="container">
    <canvas #canvas id="canvas" width="600" height="400"></canvas>
</div>
Sign up to request clarification or add additional context in comments.

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.