在Ionic 4中页面切换后触发输入文件点击

12

我想在Ionic 4中通过另一个页面触发/打开文件输入。

在页面1中,我有一个按钮以进入模态窗口,在模态窗口页面中,我想自动触发 <input file> 对话框。

组件

ionViewWillEnter() {
    document.getElementById('file').click(); // Tried with this one 1st, this only works in Internet Explorer / Edge
    this.fileInput.nativeElement.click();    // And also this with @ViewChild
}

HTML

-->

HTML

<input type="file" name="file" #file id="file" (change)="fileChange($event)" required>
4个回答

3
这是我使用的代码来触发对元素的点击:
@ViewChild("file") fileInput: ElementRef;

triggerClick() {
    let event = new MouseEvent('click', {bubbles: true});
    this.renderer.invokeElementMethod(this.fileInput.nativeElement, 'dispatchEvent', [event]);
}

1
既不工作也不出错。事件和fileInput的控制台日志: MouseEvent {isTrusted: false, screenX: 0, screenY: 0, clientX: 0, clientY: 0, …} <input id="file" name="file" required="" type="file"> - Otto

2

将此更改为:

ionViewWillEnter() {
    document.getElementById('file').click(); // Tried with this one 1st
    this.fileInput.nativeElement.click();    // And also this with @ViewChild
}

转化为这样:

ionViewDidLoad() {
    document.getElementById('file').click(); // Tried with this one 1st
}

1
不起作用,还尝试了200毫秒的setTimeout。 document.getElementById('file')console.log <input id="file" name="file" type="file"> - Otto

2
尝试使用ngAfterViewInit()生命周期钩子,该钩子在组件视图完全初始化后调用。
ngAfterViewInit() {
    document.getElementById('file').click();
}

1
这只在Internet Explorer / Edge中有效,而不适用于Chrome。 在Ionic中,生命周期为constructor --> ionViewDidLoad --> ionViewWillEnter --> ionViewDidEnter --> ionViewWillLeave --> ionViewDidLeave --> ionViewWillUnload - Otto
1
@Chumillas 它可以在Chrome和Android设备上运行。我在两个平台上都进行了检查。您可以在此处检查。Ionic是基于Angular构建的,因此Ionic也支持Angular生命周期钩子。 - Tony Stark
你能给我展示一个自动打开输入文件的例子吗?只需从页面A导航到页面B即可打开输入文件。 - Otto
您可以在此处查看,输入文件随着从一页到另一页的导航自动打开。但我认为在Chrome中存在一个错误,因为第一次加载第二个页面时,输入文件对话框不会打开,但在关闭和重新打开后它可以完美地运行。这种方法在firefoxEdge上完美运行。 - Tony Stark
它在Edge中可以工作,但在Chrome中无法工作,我正在寻找一个在第一次尝试中就可以解决Chrome的解决方案。此外,您提供的解决方案已经是此问题的重复答案。 - Otto

1
我在页面1中插入了一个隐藏的输入文件,解决了这个问题。当用户试图转到页面2时,我触发文件输入。
当用户完成选择文件后,我将文件事件更改发送到页面2,并在页面2中管理所有逻辑。

但是在你提出的问题中,你想在模态框中触发方法而不是在第一页中触发。 - Tony Stark
是的,我想在看到第2页/模态页面之前打开文件浏览器。 - Otto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接