Eugen-Andrei Coliban
Eugen-Andrei Coliban

Reputation: 1090

Call a method from a component, in the same component

So, I have an Angular 2 component, and there I have also a @HostListener. What I want to do is to call a method from this component with the @HostListener, bellow is shown the component with my attempt of calling the method with @HostListener.

The Component

import { Component, HostListener, Input, OnInit } from '@angular/core';
import { Cell } from '../../cell';
import { Direction } from '../../direction';
import { GridService } from '../../services/grid.service';
import { Directive } from '@angular/core/src/metadata/directives';

@Component({
    selector: 'app-grid',
    templateUrl: 'grid.component.html',
    styleUrls: ['grid.component.css'],
})

@Directive({
    selector: '[appControl]'
})

export class GridComponentDirective implements OnInit {

@Input() score: number;
         best: number;
         itemArray: Cell[];

@HostListener('keyup.ArrowUp') Move(itemArray, UP) { } // That's what I was talking about

    constructor(private gridService: GridService) { }

    ngOnInit() {
        this.itemArray = JSON.parse(localStorage.getItem('Grid'));
        this.score = 0;
        if (this.gridService.countEmpty(this.itemArray) === this.itemArray.length) {
        this.gridService.randomiser(this.itemArray);
        this.gridService.randomiser(this.itemArray);
    }
}

Move(array: Cell[], direction: Direction) {
    array = this.gridService.move(array, this.score, direction);
    localStorage.setItem('Grid', JSON.stringify(array));
    }
}

Upvotes: 0

Views: 362

Answers (1)

EvgenyV
EvgenyV

Reputation: 1256

Just write:

   @HostListener('keyup.ArrowUp') MoveUp() {this.Move(itemArray, UP)}

Upvotes: 2

Related Questions