RenegadeAndy RenegadeAndy - 1 year ago 102
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;

selector: 'ct-config-editor',
templateUrl: 'config.editor.component.html'
export class ConfigEditorComponent {

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


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 :


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

How do I access my instance variable within the callback?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download