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

1

7

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

Darryldarryn answered 4/5, 2017 at 19:34 Comment(1)
Have you tried contructor(private ref ChangeDetectorRef){} then in callback ref.detectChanges()?Gond
D
7

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.

Damp answered 6/3, 2021 at 10:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.