![](/img/trans.png)
[英]Angular 6, How to get the target element for an 'onSelectionChange' dom event?
[英]How to access the target of an $event bound to a DOM element using a custom directive?
我創建了一個指令
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元素“附加”到視圖時觸發。 因此,例如<input (attached)="do something" ...
就會在頁面上顯示<input>
時立即執行操作。
該事件觸發得很好,但是我的問題是,當我想訪問其目標,例如<input (attached)="$event.target.something = 'anything'"
,出現諸如以下錯誤
無法設置未定義的屬性“內容”
如何升級我的指令,以便我可以訪問事件的目標?
使用輸出發出組件實例時,沒有$ event.target。 但是,您可以使用this.ee.next(this.elementRef)
發出組件的this.ee.next(this.elementRef)
在您的構造函數中注入elementRef:
constructor(elementRef: ElementRef) { }
要將元素作為$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" >
有關演示,請參見此堆疊閃電戰 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.