RenegadeAndy RenegadeAndy - 1 month ago 6
Javascript Question

Angular2 accessing binding instance variable within callback

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?

Answer

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