如果您使用的是[(ngModel)]
绑定,则文件更改事件将不会触发。相反,您可以使用ViewChild
装饰器来访问文件输入,然后手动绑定change
事件。
在HTML模板文件中:
在组件TS文件中:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
@ViewChild('fileInput') fileInput: ElementRef;
onFileChanged() {
const file = this.fileInput.nativeElement.files[0];
console.log(file);
// 执行文件更改后的操作
}
}