angular - 我想将指令中的变量连接到组件
问题描述
每个指令都有一个
// 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 轴的事件组成。布尔变量可移动应该以某种方式识别。
解决方案
如果您的指令导出为
@Directive({
selector: '[appMovable]',
exportAs: 'appMovable'
})
当您使用模板引用变量时,您可以指示“exportAs”并使用它(如果您愿意,您可以调用函数)
<div appMovable #d="appMovable">{{d.movable}}</div>
推荐阅读
- wordpress - 禁止您无权访问此资源。Apache/2.4.48 (Win64) OpenSSL/1.1.1k PHP/7.3.29 服务器在 localhost 端口 80
- tensorflow - Tensorboard 个人资料页面中的“运行”是什么意思?
- c# - .NetCore 3-tier:如何编写 API 获取列表 DepartmentName:部门中的员工人数?,使用 Linq 方法语法
- javascript - 来自 github 设置的项目
- python - 子类属性从父类指向同一个对象引用
- azure - Azure 管道命令行:给予确认
- postgresql - 如何在 Odoo 的 create 方法中编写 SQL 查询?
- vuepress - 如何不将“asp.net”视为 VuePress 中的链接
- c# - 通过命令行为 testrail 运行测试
- reactjs - 我们如何在 chartist.js 中更改 pie-donut 的颜色