【问题标题】:Trigger input file click in Ionic 4 after page change页面更改后在 Ionic 4 中触发输入文件单击
【发布时间】:2018-07-27 08:07:44
【问题描述】:

我想触发/打开来自 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

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

【问题讨论】:

    标签: javascript html angular ionic-framework


    【解决方案1】:

    这是我用来触发点击-元素的代码:

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

    【讨论】:

    • 既不工作也不出错。事件和文件输入的控制台日志MouseEvent {isTrusted: false, screenX: 0, screenY: 0, clientX: 0, clientY: 0, …}&lt;input id="file" name="file" required="" type="file"&gt;
    【解决方案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
    }
    

    【讨论】:

    • 不起作用,还尝试了 setTimeout 为 200ms console.log of document.getElementById('file') &lt;input id="file" name="file" type="file"&gt;
    【解决方案3】:

    尝试 ngAfterViewInit() 生命周期钩子,它在 组件的视图已完全初始化。

    ngAfterViewInit() {
        document.getElementById('file').click();
    }
    

    【讨论】:

    • 这仅适用于 Internet Explorer / Edge,不适用于 Chrome。同样在 Ionic 中,这是生命周期 constructor --&gt; ionViewDidLoad --&gt; ionViewWillEnter --&gt; ionViewDidEnter --&gt; ionViewWillLeave --&gt; ionViewDidLeave --&gt; ionViewWillUnload
    • @Chumillas 它适用于 chrome 和 android 设备。我在两个平台上都检查过。你可以check here。 ionic 是基于 angular 构建的,因此 ionic 也支持 angular 生命周期钩子。
    • 你能告诉我一个不按任何按钮自动打开输入文件的例子吗?只需从 pageA 导航到 pageB 即可打开输入文件
    • 您可以check here 输入文件自动打开,并从一页导航到另一页。但我认为 chrome 中存在一个错误,因为第一次加载第二页时,输入文件对话框没有打开,但在关闭和重新打开时它工作得很好。此方法在 firefoxEdge 上完美运行。
    • 它在 Edge 中有效,但在 Chrome 中无效,我正在为第一次尝试的 Chrome 寻找解决方案。此外,您提供的解决方案是这个问题的重复答案。
    【解决方案4】:

    我解决了在 page1 中插入隐藏输入文件的问题,当用户尝试转到 page2 时,我触发了文件输入。

    当用户完成选择文件时,我将文件事件更改发送到第 2 页并管理第 2 页中的所有逻辑。

    【讨论】:

    • 但是有问题你问你想在模态而不是第一页中触发方法。
    • 是的,我想在看到第 2 页/模态页面之前打开文件资源管理器。
    猜你喜欢
    • 2015-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-08
    • 2019-10-07
    相关资源
    最近更新 更多