Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 view not updating after receiving ipcRenderer.on from Electron

I'm using ipcRenderer to retrieve the folder path from a browser dialog in my main.js.

But for some reason it does not update my the text string on my view.

I know in order for this to work I need to do a setTimeout for it to update (thanks google!). But for some reason this does not work.

Code I use is the following.

import { Component, OnInit } from '@angular/core';

declare var electron: any;

@Component({
  selector: 'my-app',
  template: 
  //added (click)="debug()" in order to update the {{path}} manually
  `<h1 (click)="debug()">My First Angular 2 App with Electron</h1> 
  <br />Project Path: {{[(path)]}} 
  <button (click)="btnClick()">Select project path</button>
  <br /> <br />`
})
export class AppComponent implements OnInit {
  ipc:any;
  path:string;

  constructor(){
    this.path = __dirname;

  }

  ngOnInit(){
    electron.ipcRenderer.on('project-path-reply', (event, arg) => {
      setTimeout(() => {
        this.path = arg.return[0];
        console.log('updated')
      })
    })
  }

  btnClick(){
    electron.ipcRenderer.send('project-path',1);
  }
  debug(){
    console.log(this.path);
  }
 }

Can someone point me in the right direction this is my first app using electron.

Kind Regards,

Thyvo

like image 411
Thyvo Avatar asked May 04 '17 19:05

Thyvo


1 Answers

For this case, use NgZone

import { Component,NgZone } from '@angular/core';

Now, update your app within the .run() function provided by NgZone

constructor(zone:NgZone) {

ipcRenderer.on('project-path-reply', (event, arg) => {
  this.zone.run(()=>{
     // the code that requires change detection here, just like below //
     this.path = arg.return[0];
     console.log('updated')
  });
});

}

This is most likely the because electron is updating the value outside the Angular change detection zone.

like image 156
Nam Dao Avatar answered Oct 17 '22 19:10

Nam Dao