在Directive Angular 2中调用Component方法

问题描述 投票:1回答:1

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

在这里,我将把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));
}
angular2-directives
1个回答
1
投票

使用组件作为服务是一种错误的方法,您应该从html传递“this”值然后将其分配给gridComponent变量并将参数传递给指令您可以使用输入装饰器

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

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

[appControl]="this"
© www.soinside.com 2019 - 2024. All rights reserved.