在angular中使用js

angular可以直接使用js代码,以下用jQuery为例子:

官网下载jQuery的js文件,另存为jQuery.js
将jQuery.js放在angular项目的assets目录下

assets

在tsconfig.json中声明对js的支持

allow js

因为将js文件放在了assets中,所以确认angular.json中有assets的声明

angular.json

然后在ts中就能直接导入js了:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import { Component, OnInit } from '@angular/core';
import * as jquery from 'src/assets/jquery.js'; //从js文件导入js代码,jquery是自定义的名字
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  title = 'angularjs';

  ngOnInit(): void {
    alert(jquery('body').html()); //调用jquery的代码
  }
}

运行程序后就可以看到结果,成功取得了body中的html内容:

result