开发者问题收集

当我将 javascript 文件导入到 angular 时,我发现 Uncaught TypeError: 无法读取 null 的属性(读取“querySelector”)

2022-06-16
241
**the js files doesnt see the component element**

此 js 函数中发生错误 (showMenu,perspective,cont,wrapper) 返回 null 当我启动我的应用程序时,我收到以下错误

function init() {
        var showMenu = document.getElementById( 'showMenu' ),
            perspectiveWrapper = document.getElementById( 'perspective' ),
            cont = perspectiveWrapper.querySelector( '.cont' ),
            contentWrapper = cont.querySelector( '.wrapper' );
            

       
    }

    init();

这是 index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Assignment1</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body >
      <app-root></app-root>
 <!-- javascript libraries -->
    <script src="/assets/js/jquery-3.2.1.js"></script>
    <script src="/assets/js/bootstrap.min.js"></script>
    <script src="/assets/js/jquery.appear.min.js"></script>
    <!-- push nav -->
    <script src="/assets/js/push_nav.js"></script>
</body>
   
   
</html>

这是我的 component.ts,我收到错误 ReferenceError:Init 未在 HomeComponent.ngAfterViewInit 中定义

import { Component, OnInit,ViewEncapsulation  } from '@angular/core';
declare function init():any;
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  encapsulation: ViewEncapsulation.None,

})
export class HomeComponent implements OnInit {

  constructor() { 
    
  }

  ngOnInit(): void {
  }
  ngAfterViewInit():void{
    init();
  }

}
2个回答

您确定要调用的方法名称

Init()

init()

edjm
2022-06-16

在 component.ts 中写入此内容以将 js 文件与 component.html 链接起来

myScriptElement: HTMLScriptElement ;
this.myScriptElement = document.createElement("script");
    this.myScriptElement.src ="/assets/js/push_nav.js";
    document.body.appendChild(this.myScriptElement);
Fayrouz Hussien
2022-06-18