Home > OS >  How to integrate steelseries in Angular project?
How to integrate steelseries in Angular project?

Time:11-27

I am trying to integrate steelseries in an Angular project. Following their example, my code looks like this: app.component.html:

<!DOCTYPE html>
<html>
  <!-- <body (BeforeRender)="displayCanvas($event)"> -->
  <body >
    <div>
      <canvas id="myCanvas"></canvas>
    </div>

    <script src="C:\\ProiecteAngular\\Test\\TestDev\\node_modules\\steelseries\\srcdocs\\index.js"></script>
  </body>
</html>
<router-outlet></router-outlet>

app.component.ts:

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import * as steelseries from "steelseries";
import { Compass } from "steelseries";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
 // template: `<canvas #myCanvas></canvas>`
})
//export class AppComponent implements AfterViewInit {
export class AppComponent  {
  title = 'TestDev';
  // @ViewChild('myCanvas', { static: true })
  // myCanvas: ElementRef<HTMLCanvasElement>;

  displayCanvas(event) {
    const compass = new Compass(document.querySelector("myCanvas"), {
      size: 200
    });
  }
  // public context: CanvasRenderingContext2D;

  // ngAfterViewInit(): void {
  //   this.context = this.myCanvas.nativeElement.getContext('2d');
  //   const compass = new Compass(document.querySelector("myCanvas"), {
  //     size: 200
  //   });
  // }
}

With this code, nothing is displayed on my web page. My thought is that canvas is not rendered correctly. I have seen that this could be done using ViewChild. I did some unsuccessfully tests (see the commented code from .ts file). What am I missing or doing wrong? Thanks in advance!

CodePudding user response:

First of all, you don't need to add index.js file to html.

example

stakblitz

html

<div>
  <canvas id="myCanvas"></canvas>
</div>

script

ngOnInit(): void {
  const compass = new Compass(document.querySelector('#myCanvas'), {
    size: 200,
  });
}

CodePudding user response:

  1. you don't need the script tag in the index.html. You are importing the js in the app.component.ts file.
  2. you use document.querySelector in the displayCanvas function. To make that work you would need to prefix myCanvas with # for the id like document.querySelector("#myCanvas") and add id="myCanvas" to the canvas html tag. (That is not the same as just #myCanvas as attribute in the tag. See an working example here: https://stackblitz.com/edit/angular-ivy-gol2jx?file=src/app/app.component.html
    But that way is not best practise for angular, because you could not use that for multiple components, because document.querySelector("#myCanvas") looks for the id in the whole html document and uses only the first. To make it more 'angular-like' you would need as you already mentioned ViewChild. Just use const compass = new Compass(this.myCanvas.nativeElement, ... )
  • Related