在此代码中,我试图使用外部javascript来切换密码可见性。但这显示了错误。
这是我的HTML代码
<input type="password" value="FakePSW" id="myInput">
<button (click)="func()">Show Password</button>
这是我的组件。
import { Component } from '@angular/core';
declare const myFunction:any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angularSecond';
name:string = 'name';
allowNewServer = false;
constructor()
{
}
func()
{
myFunction();
}
}
这是我的angular.json文件
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"src/assets/jquery.js"
]
这是我的外部javascript文件
function myFunction() {
var x = document.getElementById("myInput");
if (x.type === "password") {
x.type = "text";
} else {
x.type = "password";
}
}
这是网页中显示的错误
AppComponent.html:7 ERROR ReferenceError: myFunction is not defined
at AppComponent.func (app.component.ts:20)
at Object.eval [as handleEvent] (AppComponent.html:7)
at handleEvent (core.js:43993)
at callWithDebugContext (core.js:45632)
at Object.debugHandleEvent [as handleEvent] (core.js:45247)
at dispatchEvent (core.js:29804)
at core.js:42925
at HTMLInputElement.<anonymous> (platform-browser.js:2668)
at ZoneDelegate.invokeTask (zone-evergreen.js:391)
at Object.onInvokeTask (core.js:39680)
答案 0 :(得分:2)
首先,您必须从javascript文件中导出函数。
函数声明:
export function myFunction() {
...
}
然后,您需要将其导入到角度组件的顶部。代替
declare const myFunction:any;
应该是
import {myFunction} from 'filepath to file';
并且应该在角度项目中使用myfunction
。