0

I have a custom service that extends NgbDatepickerKeyboardService and I need to get an ElementRef to datepicker in processKey method. The main idea is to get ElementRef and to query from this reference trying to find a div of the next day (I need to check if div has a class).

public processKey(event: KeyboardEvent, datepicker: NgbDatepicker): void {
    const state = datepicker.state;
    // how to get it here? NgbDatepicker does not have any public prop to do it
}
blackhard
  • 502
  • 7
  • 26
  • Is ElementRef mandatory? or Would it work for you the native element only? – Christian Gálvez Sep 28 '20 at 19:05
  • @ChristianGálvez It doesn't matter. I need any HTMLElement in the end to check classList. I have several datepickers on the page, so it's the reason why I need to have a concrete root html element of the current datepicker. – blackhard Sep 28 '20 at 19:09

1 Answers1

0

You cannot use ViewChild/ViewChildren in Services but you can access to DOM with plain JS. You just have to declare an "id" attribute or "class" to point out from the service. In the case of utilize an "id" attribute you can query as follow:

document.getElementById('myDatePicker')

The above sentence would be an example in a component:

this.myDatePickerViewChild.nativeElement

If there are several controls you can point out to a common class in them with:

document.getElementsByClassName('<<your common class name>>');

In that way you get all pickers and iterates them to do what you want.

  • The second parameter of processKey is NgbDatepicker object. I found out that I can take a ref to html element writing this: datepicker.dayTemplate.elementRef.nativeElement.parentElement, but I was just wondering if there is a better way. I understand your solution and I like it, but I need an id value in this case and I don't see any place how I can get this information too: https://ng-bootstrap.github.io/#/components/datepicker/api#NgbDatepicker – blackhard Sep 28 '20 at 19:28
  • I understand, it is for that reason that I asked you if native element was sufficient for you. – Christian Gálvez Sep 28 '20 at 20:58