jhorton
jhorton

Reputation: 1059

Angular file input change event not firing at all

Has anyone used a file input with Angular. I'm not able to get the change event to fire when declared as (change), but when using onchange it works but not with the angular method. Has anyone successfully used (change) event? Not sure what I'm missing here.

This works...

<input hidden mat-input onclick="this.value = null" onchange=”alert(‘works’)” #fileInput type="file">

This doesn't work...

<input hidden mat-input onclick="this.value = null" (change)=”alert(‘works’)”  #fileInput type="file">

Upvotes: 1

Views: 3465

Answers (3)

Anton Hirov
Anton Hirov

Reputation: 351

You don't have access to global methods in templates. To fix this you can add a property linked to the Window object:

@Component({...})
export class AppComponent {
    window = window;
}

and call it from the template: <input (change)="window.alert('test')" type="file">

Another approach is to use global methods in component methods:

@Component({...})
export class AppComponent {
    testMethod(text) {
        alert(text)
    }
}

Html: <input (change)="testMethod('test')" type="file">

Note: also please use proper quotation marks: "''", not: ”‘‘”

Upvotes: 0

Issam Abdelhak
Issam Abdelhak

Reputation: 101

//app.component.html

<div>
   <label for="file">file</label>
   <input hidden id="file" #file name="file" type="file" (change)="onFileSelected($event)">
</div>


//app.component.ts

onFileSelected(event){
  const file = event.target.files[0];
  //do what you want with the event
}

Upvotes: 0

Mostafa Zaki
Mostafa Zaki

Reputation: 311

<input mat-input (change)="onChange()" #fileInput type="file" />

Upvotes: 1

Related Questions