gary.zhang
gary.zhang

Reputation: 275

Can I use Angular2 service in DOM addEventListener?

Issue: When I try to call service within addEventListener, service seems to be empty.

Html:

<div id="_file0">

Service:

@Injectable()
export class FilesService {
  constructor(private http : Http) { }

}

Component:

export class NoteComponent implements OnInit {

  constructor(private filesService : FilesService) { }

  ngOnInit() {
    this.addEvent(document.getElementById("_file0"));
  }
  addEvent(div){
    console.log("tag1", this.filesService);
    div.addEventListener("click", function(){
        console.log("tag2", this.filesService);
      });
  }

}

Console output:

tag1 FilesService {http: Http}
tag2 undefined

Upvotes: 1

Views: 1007

Answers (1)

Hung Cao
Hung Cao

Reputation: 3208

Try using this code to maintain this context

div.addEventListener("click", () => {
    console.log("tag2", this.filesService);
});

Additional info: this is called Arrow function or lamda function. What it actually does is when Typescript compiles your code into javascript, it creates another _this variable to store the real this and whenever you call this it gets replaces by _this.

That's why your original code gets compile, this is undefined because it was the context of click event not your Angular component.

Upvotes: 4

Related Questions