Rajesh Kumar
Rajesh Kumar

Reputation: 313

How to use id of an input element for a button click event in Angular

I have a template as

<input class="ng-hide"  id="{{f}}" multiple type="file" style="display:none;"
(change)="getFiles($event)" />
<button mat-raised-button type="button" class="mat-raised" color="primary"
onclick="document.getElementById('{{f}}').click()">{{f}}</button>

Here f is a string variable with dynamic value and want to pass the same onclick function but I am getting error as

error NG8002: Can't bind to 'onclick' since it isn't a known property of 'button'.

4     onclick="document.getElementById('{{f}}').click()">{{f}}</button>

How to resolve this issue. I am using Angular 9.

Upvotes: 0

Views: 5105

Answers (1)

Barremian
Barremian

Reputation: 31145

Instead of document.getElementById() you could use Angular template reference variable. In addition to providing more functionalities, it is the Angulary way of doing things. Also in Angular you need to bind to the (click) event instead of the onclick event. Try the following

<input #inputFile class="ng-hide" multiple type="file" style="display:none;"
(change)="getFiles($event)" />

<button mat-raised-button type="button" class="mat-raised" color="primary"
(click)="inputFile.click()">{{f}}</button>

Here inputFile is the template reference variable.

Upvotes: 2

Related Questions