Eugen-Andrei Coliban
Eugen-Andrei Coliban

Reputation: 1090

Call a Component method in Directive Angular 2

I have a directive which is supposed to call a method from component, but it fails doing this, what should be wrong ?

Here I will put the Directive, and a fragment of Component for understanding the problem..

Directive

import { Directive, EventEmitter, HostListener, Input, OnInit, Output } from '@angular/core';

import { GridComponent } from '../components/grid/grid.component';

import { Cell } from '../cell';
import { KEY_CODE } from '../keyCode.enum';

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

export class GridDirective {

    constructor(public gridComponent: GridComponent) {}

    @HostListener('window:keydown', ['$event'])
    handleKeyDown(event: KeyboardEvent) {
        console.log(event.key);
        const ITEMS = JSON.parse(localStorage.getItem('Grid'));
        let key;
        switch (event.key) {
            case 'ArrowLeft': key = KEY_CODE.LEFT_ARROW;
                break;
            case 'ArrowUp': key = KEY_CODE.UP_ARROW;
                break;
            case 'ArrowRight': key = KEY_CODE.RIGHT_ARROW;
                break;
            case 'ArrowDown': key = KEY_CODE.DOWN_ARROW;
                break;
        }
        this.gridComponent.move(ITEMS, key);
    }
}

And here's the component method which it is supposed to call

move(array: Cell[][], key: KEY_CODE) {
    localStorage.setItem('lastMove', JSON.stringify(key));
    const DATA = this.gridService.move(array, this.score, key);
    array = DATA.dataSheet;
    this.score = DATA.rating;
    this.best = this.gridService.scoreSender(this.score, this.best);
    localStorage.setItem('Grid', JSON.stringify(array));
}

Upvotes: 1

Views: 641

Answers (1)

Khaled Ahmed
Khaled Ahmed

Reputation: 1134

it's a wrong way to use a component as a service, you should pass the "this" value from html and then assign it to gridComponent variable and for passing parameter to directive you can use input decorator

gridComponent :GridComponent;
@Input('appControl') set setGridComponent(gridComponent) {
   this.gridComponent = gridComponent;
}

/// in html use property binding to pass the value to it

[appControl]="this"

Upvotes: 1

Related Questions