【问题标题】:How to access the target of an $event bound to a DOM element using a custom directive?如何使用自定义指令访问绑定到 DOM 元素的 $event 的目标?
【发布时间】:2018-11-05 09:36:14
【问题描述】:

我已经创建了一个指令

import {
  Directive, AfterContentInit, Output, EventEmitter
} from '@angular/core';

@Directive({ selector: '[attached]' })
export class AttachDirective implements AfterContentInit {

  @Output("attached")
  private ee: EventEmitter<AttachDirective> = new EventEmitter();

  ngAfterContentInit() { setTimeout(() => this.ee.next(this)); }

}

定义一个自定义事件,当它绑定到的 DOM 元素“附加”到视图时应该触发该事件。例如,&lt;input (attached)="do something" ... 会在 &lt;input&gt; 出现在页面上时立即执行某些操作。

事件触发得很好,但是我的问题是,当我想像&lt;input (attached)="$event.target.something = 'anything'" 这样访问它的目标时,我得到一个错误,例如

无法设置未定义的属性“某物”

如何升级我的指令以便我可以访问事件的目标?

【问题讨论】:

    标签: angular angular-directive dom-events angular-event-emitter


    【解决方案1】:

    要以$event.target 访问元素,请定义一个target 属性,该属性返回应用该指令的HTML 元素:

    @Output("attached") private ev: EventEmitter<AttachDirective> = new EventEmitter();
    
    constructor(private elementRef: ElementRef) { }
    
    public get target(): HTMLElement {
      return this.elementRef.nativeElement as HTMLElement;
    }
    
    ngAfterContentInit() {
      this.ev.next(this);
    }
    
    <input type="text" (attached)="$event.target.disabled = true" >
    

    请参阅this stackblitz 以获取演示。

    【讨论】:

      【解决方案2】:

      当您使用输出发出组件实例时,没有 $event.target。但是,您可以使用 this.ee.next(this.elementRef)

      发出组件的 elementRef

      在你的构造函数中注入 elementRef:

      constructor(elementRef: ElementRef) { }

      【讨论】:

      • 我已导入 ElementRef,进行了您建议的更改,还将 ee: EventEmitter&lt;AttachDirective&gt; 更改为 ee: EventEmitter&lt;ElementRef&gt;(可以吗?)但我仍然遇到同样的错误。
      • 您正在访问哪些属性?请注意,ElementRef 只是引用,DOM 的 API 在 elementRef.nativeElement 中。在 Angular 中使用 nativeElement 时有一定的影响。谷歌渲染器2
      • 使用next(this.elementRef.nativeElement) 代替next(this.elementRef) 可以,但现在我必须使用$event.disabled = 'disabled' 而不是$event.target.disabled = 'disabled' 让我们说禁用视图中的&lt;input&gt;。或访问任何其他属性。所以现在目标应该是 $event。我尝试编写 next({target: this.elementRef.nativeElement}) 但这显然不是这样做的方法。有任何想法吗?也许我应该检查一下 Renderer2...
      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 1970-01-01
      • 2020-01-26
      • 1970-01-01
      • 2013-10-26
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      相关资源
      最近更新 更多