这种错误通常发生在将外部JS脚本添加到Angular的组件中时。为了解决这个问题,我们可以将脚本添加到Angular.json文件的scripts数组中。在这样做之后,我们可以在任何组件中使用这个脚本,避免了重声明错误的问题。以下是示例代码:
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"src/assets/js/custom.js"
]
import { Component, OnInit, AfterViewInit } from '@angular/core';
declare var $: any;
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit, AfterViewInit {
ngAfterViewInit() {
$(function() {
// Your custom code here
});
}
}