0

I am writing typescript code in angular project, a problem is that i can't modify my global variable in a function as i expect, can any one tell me why?

In the following code, I want to modify global value selectFileName in function showImgName() and it not work...

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

@Component({
  selector: 'app-fbpage',
  templateUrl: './fbpage.component.html',
  styleUrls: ['./fbpage.component.css']
})


export class FbpageComponent implements OnInit {

  constructor() { }

  selectFileName = "not choice yet...";  //the name of images which is going upload 

  ngOnInit() {
    var inputs = document.getElementById('inputfile');
    inputs.addEventListener('change', this.showImgName);
  }

  showImgName(){
    var fileName = (<HTMLInputElement>document.getElementById('inputfile')).value;
    this.selectFileName = fileName;
    alert( this.selectFileName);
  }



  test(){
    alert(this.selectFileName);
  }

}
  • Also, if you're accessing dom elements by ID from inside a component and adding change listeners that way, you're completely missing the point of Angular. Learn the Angular basics of templates and event binding. – JB Nizet Aug 10 '19 at 07:30

1 Answers1

0

Bind the right this here to use inside of showImgName:

ngOnInit() {
  var inputs = document.getElementById('inputfile');
  inputs.addEventListener('change', this.showImgName.bind(this));
}
Vadi
  • 3,279
  • 2
  • 13
  • 30