在Directive Angular 2中调用Component方法

时间:2018-01-02 09:19:42

标签: angular2-directives

我有一个指令应该从组件调用一个方法,但它没有这样做,应该是什么错误?

在这里,我将DirectiveComponent的片段用于理解问题。

  

指令

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);
    }
}
  

这是它应该调用的组件方法

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));
}

1 个答案:

答案 0 :(得分:1)

将组件用作服务是错误的方法, 你应该通过"这个"来自html的值,然后将其分配给gridComponent变量,并将参数传递给指令,您可以使用输入装饰器

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

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

[appControl]="this"