I'm beginner in typescript and angular 2, I have error in my code! Would you please help me to fix this?
import { Component, HostListener } from '@angular/core'
export class TooltipComponent {
public show: boolean = false;
@HostListener('document:click',['$event'])
documentClick(event: MouseEvent) {
this.show = false;
}
showTooltip() {
this.show = true;
this.documentClick('????');
}
}
I'm beginner in typescript and angular 2, I have error in my code! Would you please help me to fix this?
import { Component, HostListener } from '@angular/core'
export class TooltipComponent {
public show: boolean = false;
@HostListener('document:click',['$event'])
documentClick(event: MouseEvent) {
this.show = false;
}
showTooltip() {
this.show = true;
this.documentClick('????');
}
}
Share
Improve this question
edited Apr 6, 2017 at 15:37
Torben Pi Jensen
8709 silver badges28 bronze badges
asked Apr 6, 2017 at 6:34
Na30mNa30m
2592 gold badges5 silver badges11 bronze badges
1
- 1 Check this fully working example plnkr.co/edit/jqr1czIu9GZ3DAAidFiG?p=preview – Saulius Next Commented Apr 6, 2017 at 15:45
4 Answers
Reset to default 12 @HostListener('document:click', ['$event'])
public documentClick(event: Event): void {
//doSomething () --> Your logic when there is a document click
}
Question is bit unclear, But the code above would get fired when there is a document click
Other way how to register listener over DOCUMENT (plunker example):
import {Component, Inject, OnInit, HostListener, VERSION} from '@angular/core';
import { DOCUMENT } from "@angular/platform-browser";
@Component({
selector: 'demo-app',
template: `
<div>
{{ text }}
</div>
`
})
export default class DemoAppComponent implements OnInit{
public text: string
public show: boolean
//constructor
constructor(@Inject(DOCUMENT) private document: Document) {
document.addEventListener('click', this.onDocument1Click);
this.text = "Angular " + VERSION.full
}
//init
ngOnInit() { }
onDocument1Click(){
this.show = !this.show
alert(this.show)
}
//add hostlistner on document:click
//@HostListener("document:click", ['$event'])
//onDocumentClick(event: Event): void {
// this.show = !this.show
// alert(this.show)
//}
}
Maybe, you create new component, define host property in your new component and use other components
You can use (document:click) event:
@Component({
host: {
'(document:click)': 'onClick($event)',
},
})
class SomeComponent() {
constructor(private _eref: ElementRef) { }
onClick(event) {
// Your codes...
}
}
I fixed it:
import {ChangeDetectorRef, Renderer } from '@angular/core';
export class TooltipComponent {
public show: boolean = false;
clickListener: Function;
constructor(
private elementRef: ElementRef,
private renderer: Renderer,
) {
this.clickListener = renderer.listenGlobal(
'document',
'click',
(event: MouseEvent) => this.documentClick(event)
);
}
documentClick(event: MouseEvent) {
console.log(event.target);
if (!this.elementRef.nativeElement.contains(event.target)) {
this.show = false;
}
}
}