Reputation: 1059
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
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
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
Reputation: 311
<input mat-input (change)="onChange()" #fileInput type="file" />
Upvotes: 1