将外部JS文件添加到Angular 5 CLI

时间:2018-03-07 03:04:37

标签: javascript angular angular5

我只有一个Javascript函数:

function sidemodalclose() {
    $("#sidemodal").modal('hide');
    var date = new Date();
    date.setDate(date.getDate() + 1);
    document.cookie = "visited=yes; path=/; expires=" + date.toUTCString();
    console.log(document.cookie);
}

我想添加到Angular应用程序的home组件。

由于我的home.component.ts有一些需要访问sidemodalclose()函数的jQuery函数。

import { Component, OnInit } from '@angular/core';

declare var $:any;

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

    constructor() { }

    ngOnInit() {

        $("#no-thanks").click(function() {
            sidemodalclose();
        });

        if (document.cookie.indexOf("visited") == -1) {
            setTimeout(function() {
                $("#sidemodal").modal('show');
            }, 1000)
        }

        $("#submit3").click(function() {
            $("#submit3").html("Just a sec!");
            $.post("https://thirdparty.com/api.php", $("#contact3").serialize(), function(response) {
                $("#submit3").html(response);
            });
            return false;
        });
    }

}

我的问题是在应用程序中包含小型JS功能的最佳方法是什么?

  1. 是否可以在.ts中添加内联JS函数?

  2. 如果我用import { SideModal } from '../../assets/js/sidemodal.js';导入JS文件,为什么会说but '--allowJs' is not set.

  3. 在Angular打样稿文件中包含自定义JS函数的最佳做法是什么?

  4. 欢迎任何见解。感谢。

1 个答案:

答案 0 :(得分:0)

如果您可以在组件中声明您的功能,那么您的所有问题都将得到解决。 您可以使用

来使用组件的任何其他功能

如果你不能,那么最好的方法是将它添加到标签脚本下的.angular-cli.json文件中,以便cli在你的app bundle加载之前加载它。

要在您的类型脚本中使用它,您应该在@Types下搜索定义类型或编写您自己的类型文件。

一旦你的类型可用:

import {sidemodalclose} from 'your-type';