ASP.NET Core 2+Angular中TypeScript组件访问HTML Document的问题
Hey there, I totally get how frustrating it is when basic stuff throws errors that seem like they should be straightforward. Let's break down how to fix this document-related issue in your project:
First, check your TypeScript configuration
TypeScript recognizesdocumentas a global DOM object, but only if it knows to include DOM type definitions. Open yourtsconfig.jsonfile and make sure thelibarray incompilerOptionsincludes"dom":"compilerOptions": { // other options... "lib": ["es2017", "dom"] }This tells the TypeScript compiler to load DOM-related type definitions, which will make
documentvisible without needing an explicit import.Use Angular's
DOCUMENTinjection token (recommended)
While using the globaldocumentworks, Angular provides a better way via dependency injection that makes your components easier to test (you can mock the document in unit tests). Here's how to implement it:import { Component, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent { constructor(@Inject(DOCUMENT) private readonly document: Document) { // Now use this.document instead of the global one const element = this.document.getElementById('your-element-id'); if (element) { // Do something with the element } } }This approach aligns with Angular's best practices and avoids relying on global variables directly.
Verify type definition packages are installed
If you're still seeing errors, it's possible your project is missing essential type definitions. Run this command to install the Node.js/DOM type packages (which includedocumenttypes):npm install @types/node --save-devMost ASP.NET Core 2 Angular templates come with these pre-installed, but it's worth checking if they got removed accidentally.
Once you make these changes, restart your Angular development server (if it's running) to pick up the config updates, and the error should disappear.
内容的提问来源于stack exchange,提问作者soca

