【问题标题】:Angular using directive for common logic用于通用逻辑的 Angular using 指令
【发布时间】:2020-10-14 16:04:20
【问题描述】:

我有多个组件,它们共享共同的逻辑。我想将该逻辑移动到单个文件中,因此我不必将代码复制到每个组件中。我虽然关于使用指令。 这是正确的方法吗?

该逻辑用于构建拖放样式图。 (处理定位等...) 所以我还需要监听 (onmousedown)(onmouseup) 事件,然后调用相应的处理程序,这些处理程序也位于指令中。

所以组件的模板应该是这样的:

<div class="entity-wrapper" (mousedown)="onMouseDown($event)" (mouseup)="onMouseUp($event)">
    <span>{{entityData.name}}</span>
</div>

其中onMouseDown()onMouseUp() 将是指令中的方法。

指令看起来像这样:

@Directive({
  selector: '[appDiagramElement]'
})
export class DiagramElementDirective {

  @Input() position: Vector2;

  constructor(private _elRef: ElementRef) { }

  onMouseDown($e: MouseEvent){
    ...
  }

  onMouseUp($e: MouseEvent){
    ...
  }

  @HostListener('document:mousemove', ['$event'])
  onMouseMove($e: MouseEvent){
    ...
  }
}

当我尝试这样做时。它不起作用,因为该组件没有方法onMouseDown()onMouseUp()。所以我想,我可能想在组件本身中创建这些方法,然后在指令的方法中调用正确的实现。

我该怎么做或者有更好的方法?

编辑:添加模板代码,我在其中实例化组件:

<div #wrapper class="diagram-wrapper">
  <app-entity [entityData]="testEntity" class="diagram-element" appDiagramElement [position]="testEntity"></app-entity>
</div>

【问题讨论】:

    标签: angular dry angular-directive angular-components


    【解决方案1】:

    是的,该指令是正确的方法。 您需要在指令中动态添加事件侦听器。例如,在您的指令构造函数中:

    constructor(elementRef: ElementRef, renderer: Renderer2) {
        // Listen to mousedown events in the component
        renderer.listen(elementRef.nativeElement, 'mousedown', (event) => {
          // Do something with 'event'
        })
    );
    

    【讨论】:

    • 我很好奇;是否需要删除ngOnDestroy()中的监听器?
    • 非常感谢。我设法让它使用它工作。我使用了 Renderer2,您可能想更新答案,所以它是最新的。
    • @Silvermind 好像可以这样:stackoverflow.com/a/44454508/12511130 Renderer2 也一样
    • @JanKrüger 感谢您的回复。我怀疑有人可以做到,但我不确定你是否需要。在某些情况下,当组件被破坏时,angular 会清理注入的服务,然后它可以自动“取消监听”。但是,我认为答案也可以添加该信息,以便完整。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 2022-12-04
    • 2010-10-23
    • 1970-01-01
    相关资源
    最近更新 更多