TS2339:类型“HTMLElement”上不存在属性“href”

Vag*_*eis 7 typescript angular

我遇到这个问题:

我无法访问HTML 元素的属性href 。我收到此错误:

Property 'href' does not exist on type 'HTMLElement'.ts(2339)
Run Code Online (Sandbox Code Playgroud)

这是代码:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  title = 'clientes-app';

  ngAfterViewInit(){
    (function($) {
        "use strict";
    
        var path = window.location.href; 
            $("#layoutSidenav_nav .sb-sidenav a.nav-link").each(function() {
                if (this.href === path) {
                    $(this).addClass("active");
                }
            });
    
        // Toggle the side navigation
        $("#sidebarToggle").on("click", function(e) {
            e.preventDefault();
            $("body").toggleClass("sb-sidenav-toggled");
        });
    })(jQuery);
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 12

并非所有HTMLElements 都有href属性。在访问当前迭代的元素之前检查它是否HTMLAnchorElement具有href属性。

if (this instanceof HTMLAnchorElement && this.href === path) {
     $(this).addClass("active");
}
Run Code Online (Sandbox Code Playgroud)