如何在 Angular 7 中使用 JavaScript 代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53482324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use JavaScript code in Angular 7?
提问by harshit raghav
I'm trying to make a collapsible navbar with the help of MaterializeCSS when used on mobile screen and need to use JavaScript code in it. Where should I write this JavaScript code?
当在移动屏幕上使用时,我试图在 MaterializeCSS 的帮助下制作一个可折叠的导航栏,并且需要在其中使用 JavaScript 代码。我应该在哪里编写这段 JavaScript 代码?
This is the code I want to use:
这是我想使用的代码:
**$(document).ready(function(){
$('.sidenav').sidenav();
});**
回答by harshit raghav
Step-1: Created a js folder inside the assets folder.
步骤 1:在资产文件夹中创建一个 js 文件夹。
Step-2: Created a new .js file inside the js folder. Assets -> js -> example.js
第 2 步:在 js 文件夹中创建一个新的 .js 文件。资产 -> js -> example.js
Step-3: Added path of the example.js in angular.json inside the scripts array.
步骤 3:在脚本数组内的 angular.json 中添加 example.js 的路径。
Step-4: Declared the js function created in example.js inside the component.ts file where that function is needed.
第 4 步:在需要该函数的 component.ts 文件中声明在 example.js 中创建的 js 函数。
Step-5: Made a call to the declared function inside ngOnInIt().
第 5 步:调用 ngOnInIt() 中声明的函数。
回答by Oen44
- Install jQuery
npm install jquery - Install MaterializeCSS
npm install materialize-css@next - Install types
npm install --save @types/materialize-css @types/jquery - Open
angular.jsonand findscriptsfield - Add
node_modules/jquery/dist/jquery.min.jsandnode_modules/materialize-css/dist/js/materialize.min.jsinside array:
- 安装 jQuery
npm install jquery - 安装 MaterializeCSS
npm install materialize-css@next - 安装类型
npm install --save @types/materialize-css @types/jquery - 打开
angular.json并查找scripts字段 - 添加
node_modules/jquery/dist/jquery.min.js和node_modules/materialize-css/dist/js/materialize.min.js内部数组:
"scripts": [ "node_modules/jquery/dist/jquery.min.js", "node_modules/materialize-css/dist/js/materialize.min.js" ]
"scripts": [ "node_modules/jquery/dist/jquery.min.js", "node_modules/materialize-css/dist/js/materialize.min.js" ]
- Go to your component and add at the top
declare var jQuery: any;
- 转到您的组件并在顶部添加
declare var jQuery: any;
Example
例子
(function ($) {
$('.sidenav').sidenav();
})(jQuery);
You can use that inside ngOnInit.
你可以在里面使用它ngOnInit。
回答by MysterX
Find and open angular.json, then add to projects.architect.build.optionsobject next field and change filepath to your own:
查找并打开angular.json,然后添加到projects.architect.build.options对象下一个字段并将文件路径更改为您自己的:
"scripts": [
"path/to/js/you/want/use.js"
]
Angular will add those custom files to result build
Angular 会将这些自定义文件添加到结果构建中

