首页 > 解决方案 > 我想将指令中的变量连接到组件

问题描述

每个指令都有一个

// Modules and Components
import { Directive, Input, ElementRef, HostBinding, HostListener } from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

// Directive
import { DraggableDirective } from '../draggable/draggable.directive';

// Interfaces
import { Position } from '../../../../interfaces/draggable-system/move-position';

/**
 * Allows to move the objects.
 */

@Directive({
  selector: '[appMovable]'
})
export class MovableDirective extends DraggableDirective {

  // ********** DECLARATIONS **********//

  // Overview of the Inputs, Outputs and HostBindings
  @Input('appMovable') set movable(movable: boolean) {
    this.enabled = movable;
  }

  @HostBinding('class.moving') moving = false;

  // Check the positions
  position: Position = { x: 0, y: 0 };
  private startPosition: Position;
  private reset = false;

  constructor(
    public element: ElementRef,
    private sanitizer: DomSanitizer) {
    super();
  }

  // Use HostBindings and HostListener

  @HostBinding('style.transform') get transform(): SafeStyle {
    return this.sanitizer.bypassSecurityTrustStyle(
      `translateX(${this.position.x}px) translateY(${this.position.y}px)`
    );
  }

  @HostListener('dragStart', ['$event']) onDragStart(event: PointerEvent): void {
    this.moving = true;
    this.startPosition = {
      x: event.clientX - this.position.x,
      y: event.clientY - this.position.y
    };
  }

  @HostListener('dragMove', ['$event']) onDragMove(event: PointerEvent): void {
    this.position = {
      x: event.clientX - this.startPosition.x,
      y: event.clientY - this.startPosition.y,
    };
  }

  @HostListener('dragEnd') onDragEnd(): void {
    this.moving = false;

    if (this.reset) {
      this.position = {
        x: 0,
        y: 0,
      };
    }
  }
}

我需要将此指令中的变量绑定到组件中。我该怎么做呢?该指令由在鼠标事件期间检测到 x 轴和 y 轴的事件组成。布尔变量可移动应该以某种方式识别。

标签: angulartypescriptangular-directiveangular-components

解决方案


如果您的指令导出为

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

当您使用模板引用变量时,您可以指示“exportAs”并使用它(如果您愿意,您可以调用函数)

<div appMovable #d="appMovable">{{d.movable}}</div>

推荐阅读