求助:Angular4中JS文件加载后theWYSIWYG未定义问题
Hey there, let's break down what's going on here and fix that error step by step.
First, let's nail down the root cause: The error is popping up in your LoginForm component, but the theWYSIWYG element only exists in your Dashboard component. That means somewhere in your LoginForm's code (or a global script that runs on page load), your app is trying to access theWYSIWYG before the Dashboard's DOM is even rendered—so naturally, it can't find it.
Here's how to fix it:
1. Check for accidental references to theWYSIWYG in LoginForm
First, dig into your login-form.component.ts and its template file. Did you accidentally copy over code that references theWYSIWYG? Maybe leftover test code or a stray function call? If you find any, delete it—your LoginForm doesn't need to interact with that element at all.
If the issue comes from a global script that auto-initializes the WYSIWYG editor on page load:
- Open the external JS file you added to
angular-cli.jsonand modify it to stop auto-executing. Instead, wrap the initialization logic in a manually callable function. For example:// Replace auto-run code like this: // $(document).ready(function() { // window.theWYSIWYG = initializeWYSIWYG('#theWYSIWYG'); // }); // With a manual function: window.initTheWYSIWYG = function() { return initializeWYSIWYG('#theWYSIWYG'); // Use your actual initialization function here }
2. Initialize the WYSIWYG only in the Dashboard component
Since the theWYSIWYG element lives exclusively in the Dashboard, we should wait until that component's DOM is fully rendered before initializing the editor. Use Angular's AfterViewInit lifecycle hook for this:
In dashboard.component.ts:
import { Component, AfterViewInit } from '@angular/core'; // Declare the global function to avoid TypeScript errors declare var initTheWYSIWYG: any; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html' }) export class DashboardComponent implements AfterViewInit { ngAfterViewInit(): void { // At this point, the Dashboard's DOM is loaded, so #theWYSIWYG exists window.theWYSIWYG = initTheWYSIWYG(); } }
3. Double-check your script loading order
Even though you said the script loads successfully, make sure it's listed after any dependencies it needs (like jQuery) in angular-cli.json (or angular.json if you're on Angular 6+). For example:
"scripts": [ "../node_modules/jquery/dist/jquery.min.js", "../path/to/your/wysiwyg-editor.js" ]
4. Clean up any stray global code
If you have any other global scripts that might be trying to access theWYSIWYG early, tweak them to only run when the Dashboard component is active, or remove those calls entirely.
That should resolve the ReferenceError—your LoginForm won't try to access an element that doesn't exist, and the WYSIWYG will initialize properly once you land on the Dashboard.
内容的提问来源于stack exchange,提问作者Haider Ali Shafqat

