0

I have developed a simple application that renders a cube with Angular 4 and three.js. I have an Angular component called ViewerComponent, where the cube is rendered. The code of this component relevant to my question is the following (the code of the init method is not included here for simplicity):

import { Component, AfterViewInit } from '@angular/core';
import * as THREE from 'three';

@Component({
    moduleId: module.id,
    templateUrl: 'viewer.component.html',
    styleUrls: ['viewer.component.css'],
})

export class ViewerComponent implements AfterViewInit{

    constructor() { }

    ngAfterViewInit(){
        this.init();
    }

    init(){
        // define camera, scene, cube, renderer, etc
    }

    Callback_Method(){
        console.log("RESIZE!");
    }

    onWindowResize(){   
        this.Callback_Method();
    }

}

I would like a message to be shown in the browser console when the size of the window of the browser is changed. Trying to implement this functionality, I found the following error.

When I run my application, and change the size of the window of the browser, the following error is raised: ERROR TypeError: this.Callback_Method is not a function. However, if I change the code of the method onWindowResize to the following, I get the expected behaviour:

onWindowResize(){   
    console.log("RESIZE!");
}

I am very new to frontend technologies and three.js, and now I am completely lost. Does anyone have any ideas on why could this be hapenning? Thanks in advance.

1 Answer 1

1

You can use HostListener to get DOM events

import { Component, AfterViewInit, HostListener } from '@angular/core';

export class ViewerComponent implements AfterViewInit{

  @HostListener('window:resize', ['$event'])
    onResize(event: Event) {
      this.Callback_Method();
    }

  constructor() { }

  Callback_Method(){
    console.log("RESIZE!");
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works like a charm, thank you so much! Only one thing: I should define the type of the argument event in the definition of the onResize method, as I am using Typescript. I cannot edit your answer as it is a very small change. Could you do it for me? Thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.