[英]Store reference of nativeElement created with renderer2
我正在嘗試實現拖放指令。
拖放有效。
我正在嘗試處理單擊,使其具有與input type="file"
相同的行為。
我的計划是使用Renderer2添加一個不可見的<input>
,並在我收到對主機的單擊時轉發對hit的單擊。
我可以創建該元素,但無法轉發該元素。
我如何訪問nativeElement以便對其進行點擊並響應fileChange事件?
這是我嘗試過的:
ngOnInit(): void {
// was using this.document.createElement... edited
this.fileInput = this.renderer.createElement('input'); // What do I even get here ? Seems like a string
this.renderer.setStyle(this.fileInput, 'visibility', 'collapse');
this.renderer.setStyle(this.fileInput, 'position', 'absolute');
this.renderer.setAttribute(this.fileInput, 'type', 'file');
this.renderer.appendChild(this.elementRef.nativeElement, this.fileInput);
}
@HostListener('click', ['$event'])
public onClick(evt) {
console.log('this.fileInput', this.fileInput); // alright
console.log('this.fileInput.nativeElement', this.fileInput.nativeElement); // undefined
console.log('this.fileInput.el.nativeElement', this.fileInput.el.nativeElement); // undefined has no nativeElement
}
注意,我隱藏了輸入,因為該指令不能與主機布局交互,但是當我顯示它時,它可以正常工作(單擊它可以工作)。
首先,您應該使用Renderer2的createElement方法,您已經在其他地方使用了它。 該方法以及文檔的createElement返回一個元素,而不是elementRef。 這就是為什么嘗試訪問this.fileInput的nativeElement返回未定義的原因,this.fileInput已經是nativeElement。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.