我正在用angular项目编写打字稿代码,问题是我无法按我期望的那样修改函数中的全局变量,有人可以告诉我为什么吗?
在下面的代码中,我想在函数showImgName()中修改全局值selectFileName,但它不起作用...
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);
}
}
答案 0 :(得分:0)
在此处绑定右this
以便在showImgName
内部使用:
ngOnInit() {
var inputs = document.getElementById('inputfile');
inputs.addEventListener('change', this.showImgName.bind(this));
}