简体   繁体   中英

Adding an external JS file to Angular 5 CLI

I have this just one Javascript function:

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);
}

which I want to add to the home component of an Angular app.

As my home.component.ts has some jQuery functions which need to access the sidemodalclose() function.

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;
        });
    }

}

My question is what is the best way to include the small JS function in the app?

  1. Is it possible to add JS functions inline in .ts?

  2. If I import the JS file with import { SideModal } from '../../assets/js/sidemodal.js'; why does it say but '--allowJs' is not set. ?

  3. What is the best practice to include custom JS functions in Angular typescript file?

Any insight is welcome. Thanks.

If you can declare your function inside your component, all your problems is solved. You can use like any other function of your component using this

If you can not, so the best way is to add it to your .angular-cli.json file under the tag scripts so the cli load it for your before your app bundle get loaded.

And to use it in your type script you should search for Definition Type under @Types or write your own type file.

Once your type is available:

import {sidemodalclose} from 'your-type';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM