错误:无法读取 null 的属性“classList”(角度)

时间:2021-01-17 17:34:40

标签: angular typescript dom

urlpatterns = [
    path('admin/', admin.site.urls),
    # You'll obviously have to import it if it is not  in the same file
    path('featured_products', ProductView.as_view()) 
]

我不确定我在操作 DOM 元素时做错了什么。我试图通过 id 类和名称获取元素,但我仍然收到错误 看我的脚本:

TypeError: Cannot read property 'classList' of null

和我的 html:

  onDropDown(): void {
    document.querySelector("#dropdown").classList.toggle("show")
  }

错误:对象可能为“空”。

1 个答案:

答案 0 :(得分:1)

原生JS的使用,并不是获取元素的最佳方式,你可以在你的html元素中添加#dropdown,然后在你的TS文件中通过@ViewChild获取它。我们称之为“模板变量”。 在 HTML 中:

    ...... 在 TS 中: @ViewChild('someVar') el:ElementRef;

    现在el是一个DOM元素,你可以根据需要切换类