如何避免“元素'.ts(2339)类型上不存在属性'点击'”错误

时间:2020-06-18 02:28:19

标签: jquery angular typescript

我正在尝试在我的Angular应用中使用以下jQuery代码,这是选择下拉组件所需的。

document.querySelector('.dropdown-el').click(function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).toggleClass('expanded');
  $('#' + $(e.target).attr('for')).prop('checked', true);
});
$(document).click(function() {
  $('.dropdown-el').removeClass('expanded');
});

问题是,尝试使用它时出现TS错误:Property 'click' does not exist on type 'Element'.。有什么办法可以避免这种情况?

2 个答案:

答案 0 :(得分:0)

document.querySelector()返回的元素上不存在单击。您需要将其强制转换为HTMLElement

答案 1 :(得分:0)

您需要通过以下方式将元素转换为HTMLElement

let myElement: HTMLElement = document.querySelector() as HTMLElement;
myElement.click();

希望这会有所帮助。