【问题标题】:How to open an Electron dialog from angular 2 component?如何从 Angular 2 组件打开电子对话框?
【发布时间】:2017-09-09 23:21:43
【问题描述】:

我想单击一个按钮以在我的组件中打开文件夹对话框。这是我想要做的:

HTML:

<div>
    <input class="u-full-width" placeholder="Folder" type="text" [(ngModel)]="folder">
    <button id="browse" class="button-primary" (click)="browse()">Browse</button>
    <input id="fileInput" type="file" style="display: none" />
</div>

组件.ts

// var remote = require('remote');
// var dialog = remote.require('dialog');

  folder: string;
  browse() {
    dialog.showOpenDialog({title: 'Select a folder', properties: ['openDirectory']}, (folderPath) => {
        if (folderPath === undefined){
            console.log("You didn't select a folder");
            return;
        }
        this.folder = folderPath;
    });
  }

那么,如何导入遥控器和对话框?

【问题讨论】:

    标签: angular electron


    【解决方案1】:

    只需使用 es6 import 导入“远程”模块,然后你的 ts 文件就会像

    import { remote } from 'electron';
    
    folder: string;
    browse() {
        remote.dialog.showOpenDialog({title: 'Select a folder', properties: ['openDirectory']}, (folderPath) => {
            if (folderPath === undefined){
                console.log("You didn't select a folder");
                return;
            }
            this.folder = folderPath;
        });
      }
    

    【讨论】:

    【解决方案2】:

    您可以使用 ngx-electron 库尝试一下

    import {ElectronService} from 'ngx-electron'
    
    export class DialogHelper {
    
        private static alert = new ElectronService().remote.dialog;
    }
    

    【讨论】:

    • 这应该是被接受的答案,尽管@shobhit-sharma 可以使用 DI 而不是调用 new
    • 尽管这是正确的,但最好的做法是在不做任何假设的情况下对答案给出完整的答复……即人们如何使用您的解决方案。
    • @Alex,是的,你可以通过 DI 完成
    • 我正在尝试使用它,但 ElctronService.remote 未定义,有人知道为什么吗?
    【解决方案3】:

    你已经接近了。根据文档 (https://github.com/electron/electron/blob/master/docs/api/dialog.md),要在渲染器中使用它,您需要执行 const {dialog} = require('electron').remote,因此不需要您的第一个 remote 变量。

    【讨论】:

    • 感谢您的回答。但是,当我尝试此代码时,我在浏览器控制台中收到错误Uncaught TypeError: fs.existsSync is not a function at Object.&lt;anonymous&gt; (vendor.bundle.js:72631)...,并且应用程序只显示“正在加载...”
    • 我明白了。在您创建窗口的主要过程中,您是否禁用了节点集成?如果是这样,那么您可能需要将上面的代码放入预加载脚本中。有关更多详细信息,请参阅此对话github.com/electron/electron/issues/5113
    • 其实我从https://github.com/onehungrymind/electrogram切换到另一个示例代码库,里面有打开对话框的代码。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2021-06-26
    • 1970-01-01
    相关资源
    最近更新 更多