You cannot do this reliably. After the component is created, event listener (@HostListener
) are setup and ngOnInit
is called by the framework. The listener will only react to the event you specify (in your case document:mousemove
). If you wanted this value, the event would need to be fired between component creation (calling the constructor) and calling ngOnInit
, which, as I explained, is called immediately after. This is nearly impossible.
In your case the workaround is pretty simple: Just do the same work in ngOnInit
as you do in @HostListener
:
export class AppComponent {
public currentMinute:number;
public addedMinute:number;
constructor(private datePipe: DatePipe){ }
@HostListener('document:mousemove',['event'])
public mouse(e):void {
this.setDates();
}
public ngOnInit():void {
this.setDates();
// Here this.currentMinute and this.addedMinute are defined now
}
private setDates():void {
this.currentMinute=new Date().getMinutes();
this.addedMinute=new Date().getMinutes()+2;
}
}
1
solved how to call method of event in ngOnInit