Build Desktop apps with the power of Angular
Tags: javascript, electron, angular, typescript
Published: 2019-01-02 00:34:21

---
title: Build Desktop apps with the power of Angular
published: true
description: How to build desktop apps using electron and angular
tags: JavaScript, Electron, Angular, Typescript
---

![angular and electron](https://thepracticaldev.s3.amazonaws.com/i/8nrdksll7i842jrkfckz.png)

> *If you can build a website, you can build a desktop app.*

That’s true if you know how to write Javascript code, you can build a desktop application that looks and behaves like the native one. not just that, you also can bring the power of Angular into the world of desktop apps to make your IU look stunning 😍, enough talking, go get yourself a cup of coffee and let’s get started.

# What are we going to do?!!

We’re going to build a basic desktop application using [Electron](https://electronjs.org/) and [Angular](https://angular.io/).

> Before we start I expect that you have some basic knowledge of NodeJs and Angular.

# Set up Angular

If you don’t have Angular cli installed already, run the following command to install it.


```
$ npm install -g @angular/cli
```

Now let’s start a new Angular application.


```
$ ng new angular-electron
```

It’ll ask you about the styles compiler you want to use and if you want to use the Angular router and so on, this configuration doesn’t matter at all select whatever you want.

You can see your application now in action by running…

```
$ cd angular-electron
$ ng serve
```

Then open your browser at [http://localhost:4200/](http://localhost:4200/), anyway that’s not the funniest part, let’s move forward.

We need to modify the index.html file at the src folder of our project, add a period to the base tag, so our app can find the static files, don’t skip this step it’s very important.

```
<base href="./">
```

# Set up Electron

Now we going to add Electron to our application.

```
$ npm install --save-dev electron
```

And we’ll also need some dependencies.

```
$ npm install --save-dev app-root-path
```

Now let’s create a new folder for our Electron application.

```
$ mkdir bin && cd bin && touch main.ts
```

As you can see we created bin folder with a `main.ts` file in it, and the reason we created the main file with `ts` extension and not `js` is that we already using Typescript for the Angular application, so why not use Typescript for the entire project?!!

Now let’s add some code to our `main.ts` file (lastly we writing some code 😅)

```
import { app, BrowserWindow } from 'electron';
import { resolve } from 'app-root-path';

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win: BrowserWindow;

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 800,
    height: 600
  });

  // Load the angular app.
  // Make sure that this path targets the index.html of the
  // angular application (the distribution).
  win.loadFile(resolve('dist/angular-electron/index.html'));

  // Emitted when the window is closed.
  win.on('closed', () => {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi-windows, this is the time
    // when you should delete the corresponding element.
    win = null;
  });
}

// This method will be called when the Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  // On macOS, it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (win === null) {
    createWindow();
  }
});

// In this file, you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
```

The code above is exactly the same as mentioned at the [official website](https://electronjs.org/docs/tutorial/first-app) but in Typescript syntax, also note that the `win.loadFile` function linking to the entry file of the Angular application “we didn’t build it yet”.

Okay, we need to check if what we are doing is even working, right!!

Let’s add a script to our `package.json` file so we can build and run this application.

```
"main" : "bin/main.js",
"scripts": {
 ...
   “electron”: “tsc bin/main.ts && ng build && electron bin/main.js”
}
```

And now let’s see it in action.

```
$ npm run electron
```

For now, you should see the application up and running with the angular logo in it, so far so good 😉.

Okay, now we have our application running, but who could we use the Electron API within the Angular application itself?!!

Don’t panic it’s as easy as running…

```
$ npm install --save-dev ngx-electron
```

# Access Electron API from within the Angular application.

We just installed [ngx-electron](https://github.com/ThorstenHans/ngx-electron) which going to make our life a lot easier, so let’s see how to use it.

We need to import this module like any other module we used to use with Angular inside `app.module.ts` file.

```
import { NgxElectronModule } from 'ngx-electron';
@NgModule({
imports: [
  ...
  NgxElectronModule
]
})
export class AppModule {}
```

That’s it now we can use it in our components like…

```
import { ElectronService } from 'ngx-electron';
export class AppComponent {
   constructor(private _electronService: ElectronService) {
   // now we have access to electron api through this service
   }
}
```

Let’s see if we really have access to Electron API.

Replace the content of your `app.component.ts` file with the following.

```
import { Component } from '@angular/core';
import { ElectronService } from 'ngx-electron';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'angular-electron';

  versions = { node: '', chrome: '', electron: '' };

  constructor(private _electronService: ElectronService) {
    // Make sure that app is being executed inside of electron.
    if (this._electronService.isElectronApp) {
      // We have access to node process.
      this.versions.node = this._electronService.process.versions.node;
      this.versions.chrome = this._electronService.process.versions.chrome;
      this.versions.electron = this._electronService.process.versions.electron;
    }
  }
}
```

And replace the content of the `app.component.html` file with the following

```
<!--The content below is only a placeholder and can be replaced.-->

<div style="text-align:center">

  <h1>Welcome to {{ title }}!</h1>

  <ul>
    <li>Node version {{ versions.node }}</li>
    <li>Chrome version {{ versions.chrome }}</li>
    <li>Electron version {{ versions.electron }}</li>
  </ul>

</div>
```

So, what do you think? don’t think a lot let’s see it in action 😅.

```
$ npm run electron
```

For now, you should see the application up and running with the versions of code, chrome, and electron we using, hmmm we did it 😉.

# Conclusion

Building desktop apps isn’t that hard, and we can use some powerful tools like node, angular, electron, and typescript to do awesome work, and you know what? even if you're web developer it’s not bad to try some new techs in your free time, I'm pretty sure that you going to learn something new from trying new techs 😉.

I may add a new post to write some unit tests for our application if I have free time.

And if you stuck you can always refer to the [Github repo](https://github.com/AhmedMKamal/angular-electron) of this application.

This post was originally published at [Medium](https://medium.com/@en.ahmed.mk/build-desktop-apps-with-the-power-of-angular-1e44d13d77a4)