jamie
jamie

Reputation: 690

AngularI/O & Renderer2: Trigger click event on <input type=file> elmt by clicking a separate button element

tl;dr: How can I trigger <input file=type> in this case without using nativeElement.click?. In better accordance with Renderer2 in other words

The idea of working with a dom element object in angular4+ component class isn't clear for this use case. This works in the current browser.

Specifically, this.picInput.nativeElement.click(); But this as I understand it is not recommended (using the element method directly ie. nativeElement.click()). Because it will not work in other platforms.

app.component.html

<!-- button element not hidden -->
<div fxFlex="10" style="text-align: center;">
  <a md-raised-button (click)="clickTheInput()">Add Pic</a>
</div>

<!-- input element hidden on the page --> 
<div class="row2ofheader">
  <div fxFlex="10" style="text-align: center;">

    <input #picInput type="file" (change)="alert('changed in input')">

    </div>
  </div>

app.component.ts

export class AppComponent implements OnInit, AfterViewInit {

    @ViewChild('picInput') picInput;

    constructor(private _auth: AuthService, private renderer: Renderer2) { }

    ngAfterViewInit(): void {}

    alert(input) {
    window.alert(input);
    }

    clickTheInput() {
    this.picInput.nativeElement.click();
    }

Upvotes: 1

Views: 917

Answers (1)

Vega
Vega

Reputation: 28708

From the docs:

A template reference variable is often a reference to a DOM element within a template. .... You can refer to a template reference variable anywhere in the template.

So #picInput gives you that reference to <input> tag as DOM element properties and methods within the template.

You might want consider also this:

  .....
  <a md-raised-button (click)="picInput.click()">Add Pic</a>

  .....
  <input #picInput type="file" (change)="alert('changed in input')">


UPDATE

There is an other way to make it sure it works everywhere. Call the same method from both button and input:

HTML:

  .....
  <a md-raised-button (click)="onChange()">Add Pic</a>

  .....
  <input #picInput type="file" (change)="onChange()">

Typescript:

onChange(){
  console.log("input changed")
}

If you need to detect which one of them fired onChange(), pass an argument:

  <input #picInput type="file" (change)="onChange($event, 'input')">

or if you need to do something after but different from the other:

  <input #picInput type="file" (change)="onChange(): somethingElse()">

Upvotes: 2

Related Questions