无法从Angular 6中的Typescript调用javascript函数 [英] Unable to call javascript function from Typescript in Angular 6

查看:56
本文介绍了无法从Angular 6中的Typescript调用javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否未从ngOnInit()调用下面的javascript函数(帮助)?

The javascript function (help) below is not being called from ngOnInit()?

在Web控制台中:错误ReferenceError:未定义帮助"

In web console: ERROR ReferenceError: "help is not defined"

您知道如何做到吗?

src/assets/myjs.js:

src/assets/myjs.js:

function help() {
    console.log("hilfe");   
}


src/app/highlight.directive.ts:


src/app/highlight.directive.ts:

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

declare function help() : any;

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {

  constructor(el: ElementRef) { 
    el.nativeElement.style.backgroundColor = 'yellow';
  }

  ngOnInit() {
    help();
  }

}


angular.json:


angular.json:

...

    "styles": [
         "src/styles.css"
    ],
    "scripts": [
        "src/assets/myjs.js"
    ],
},
...

推荐答案

ES6/TS

只需在help.ts中导出功能帮助

Simply export your function Help in help.ts

export default function Help(){}

通过...导入任何地方

Import anywhere by

import Help from 'help'

这篇关于无法从Angular 6中的Typescript调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆