0

I'm trying to implement a drag and drop directive.

The drag and drop works.

I'm trying to handle the click now, to have the same behaviour that with an input type="file".

My plan is to add an invisible <input> with Renderer2 and to forward click on hit when I receive a click on the host.

I can create the element alright but I can't forward the click on it.

How can I access the nativeElement in order to forward a click on it and react on fileChange event ?

Here is what I tried:

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
}

Note, I hide the input because the directive must not interact with host layout but when I do show it, it works alright (clicking on it works).

Adrien H
  • 643
  • 6
  • 21

1 Answers1

2

First off, You should use the createElement method of Renderer2, you're already using it everywhere else. That method, as well as createElement of document, returns an element, not an elementRef. That's why trying to access nativeElement of this.fileInput returns undefined, this.fileInput is already a nativeElement.

Fredrik_Borgstrom
  • 2,504
  • 25
  • 32