以编程方式在输入类型文件上触发 onchange 事件

Fire onchange event on input type file programmatically

我有一个用 Angular 编写的项目,我想设置输入类型文件的样式。所以在互联网上我找到了解决方案,我必须隐藏输入类型文件并以编程方式调用它的事件。但是下面的代码不起作用:

   <input type="button" id="addImgFile" value="Add file" 
onclick="var addImgFile = document.getElementById('addImgFile'); var event = new Event('change'); addImgFile.dispatchEvent(event);" />
    <input type="file" name="avatar" id="addImgFile" style="display:none;" 
(change)="onFileChange($event)" />

不太清楚你想要实现什么,但如果你只是想在开始时隐藏输入字段并仅在单击“添加文件”按钮时显示它,那么你可以尝试按照下面的代码更改按钮的事件。

<input type="button" id="addImgFile" value="Add file" onclick="var addImgFile = document.getElementById('addImgFile1'); var event = new Event('change'); addImgFile.dispatchEvent(event);" />

<input type="file" name="avatar"  id="addImgFile1" style="display:none;" onchange=" event.target.style=''; event.target.click()" />

您可以使用 label 来获得您想要的风格,而不是使用另一个 inputHere is an example

在 Angular 中,您应该使用 ViewChild 属性 定向器来访问元素。然后,您可以从打字稿文件中手动执行所需的任何方法。这是一个基本示例:https://stackblitz.com/edit/angular-nfdvsr

<input type="button" id="addImgFile" value="Add file" (click)="onAddFile()" />
<input #file type="file" name="avatar" id="addImgFile" style="display:none;" 
(change)="onFileChange($event)" />
@ViewChild('file', { static: true })
private file: ElementRef;

onAddFile() {
   // manually click the file element
   this.file.nativeElement.value = null;
   this.file.nativeElement.click();
}