首页 > 解决方案 > 如何在自定义 NgbDatepickerKeyboardService 中从 NgbDatepicker 获取 ElementRef?

问题描述

我有一个扩展 NgbDatepickerKeyboardService 的自定义服务,我需要在processKey方法中获取一个 ElementRef 到 datepicker。主要思想是获取 ElementRef 并从该参考中查询,试图找到第二天的 div(我需要检查 div 是否有一个类)。

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
}

标签: angularng-bootstrapngb-datepicker

解决方案


您不能在服务中使用 ViewChild/ViewChildren,但您可以使用纯 JS 访问 DOM。您只需声明一个“id”属性或“类”即可从服务中指出。在使用“id”属性的情况下,您可以查询如下:

document.getElementById('myDatePicker')

上面的句子将是组件中的一个示例:

this.myDatePickerViewChild.nativeElement

如果有多个控件,您可以通过以下方式指出其中的一个公共类:

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

通过这种方式,您可以获得所有选择器并迭代它们以执行您想要的操作。


推荐阅读