0

In angular2 I have the following component:

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

const dialog = require("electron").dialog;
const xml2js = require('xml2js');
const fs = require("fs");
const ipc = require('electron').ipcRenderer;

@Component({
  selector: 'ct-config-editor',
  templateUrl: 'config.editor.component.html'
})
export class ConfigEditorComponent {

  constructor() {
    this.selected_file = 'Max';
  }


  clicked(event){
    alert("lol");
      ipc.send('open-file-dialog');

      ipc.on('selected-directory', function (event, path) {
        this.selected_file = `You selected: ${path}`;
      });
  }
}

The view has a correctly bound property called selected_file like this :

<h1>{{selected_file}}</h1>

The value of the H1 is max at the start -- however after my callback runs, I don't have access to the this.selected_file because the context of the 'this' is not my class.

How do I access my instance variable within the callback?

1 Answer 1

2

Use arrow function to retain context:

ipc.on('selected-directory', (event, path) => {
   this.selected_file = `You selected: ${path}`;
});

This way this will be referenced to your class

See also more details here

Sign up to request clarification or add additional context in comments.

1 Comment

Is this the best practice? I don't particularly understand what the arrow function is doing!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.