Receive error message "ERROR ReferenceError: document is not defined" when using Angular Code Input Component

I have integrated the angular-code-input library into my project. However, upon loading a component that uses the Angular Code Input Component, I encountered an error message:

- Changes detected. Rebuilding...
ERROR ReferenceError: document is not defined
    at _CodeInputComponent.focusOnInputAfterAppearing (c:/Users/X/Documents/sourcecode/web/node_modules/angular-code-input/fesm2022/angular-code-input.mjs:300:52)
    at _CodeInputComponent.ngAfterViewChecked (c:/Users/X/Documents/sourcecode/web/node_modules/angular-code-input/fesm2022/angular-code-input.mjs:103:10)
    ...
   

Details:

The error seems to be originating from the use of the document object in the Angular Code Input Component, which may not be available when navigating to certain routes.

Steps to Reproduce:

  • Initiate the Angular project.
  • Go to the route with the component utilizing the Angular Code Input Component. The component loads, but errors are displayed in the terminal.

Expected Behavior: The component should load without errors after navigation to its route.

Environment:

  • Angular version: 17.1.0
  • Operating System: Windows
  • Node.js version: v18.19.1
  • npm: 10.2.4

Answer №1

The reason for this issue is the internal usage of the `document` object from the window in the angular-code-input library, which is not accessible on the server side.

To resolve this problem, you can implement a browser check as shown below:

export class AppService {

constructor(@Inject(PLATFORM_ID) platformId: Object) {
    this.isBrowser = isPlatformBrowser(platformId);
    this.isServer = isPlatformServer(platformId);
  }
}
<div class="customNavTabs">
   @if (appService.isBrowser) {
     <code-input [isCodeHidden]="true"
              [codeLength]="5"
              (codeChanged)="onCodeChanged($event)"
              (codeCompleted)="onCodeCompleted($event)">
     </code-input>
   }
</div> 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a unique custom complex template typeahead implementation with Angular 2 and Ng2-Bootstrap

I encountered an issue with the ng2-bootstrap typeahead implementation and have created a plunker to demonstrate the problem. Check out the plunker example here <template #customItemTemplate let-model="item" let-index="index"> <h5>This is ...

Add the location of the scss file to enable server side rendering using webpack

While deploying Angular Universal for my Angular 5 application (recently migrated from Angular 4), I came across an issue with the server-side rendering option: ng build --aot --app 1 The path for variables in my SCSS files worked on the client side but ...

Unable to initiate a new Angular project at this time

As a beginner in Angular, I encountered an error message when running the ng new prj-name command in a specific folder: Error: npm ERR! enoent ENOENT: no such file or directory, rename 'Desktop\angular\angular-intro\node_modules&bsol ...

How can I furnish TSC with TypeScript definitions for URI imports in a comprehensive manner?

import Vue from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5b3b0a085f7ebf0ebf7f4">[email protected]</a>/dist/vue.esm.js' If I submit the above code to TSC for compilat ...

Running a loop to utilize data from an array of objects within a Protractor it() spec

I am currently in the process of setting up an end-to-end test suite with specifications to assess the functionality of opening a file within the application. My goal is to collect performance data for each test specification, focusing on variables such as ...

Is there a way to retrieve the chosen value from an ion-alert radio alert?

async showAlertRadio(heading:string){ const alert = await this.alertCtrl.create({ header: heading, inputs :[ { name : 'Radio 1', type: 'radio', label: 'Radio 1', ...

When writing chunks to a writable stream, an issue arises where the resulting file is corrupted and significantly larger than the original file

Seeking to retrieve a file from the server, our C# service provides data chunks of the requested file (HTTP status - 206). On the client side, within a Node.js application, the goal is to merge the chunks and save the complete file. Successfully downloadi ...

Is there a specific pipe in Angular that displays dates in a relative time ago

My current project involves creating a website for sharing posts. One of the features I want to include is a date ago pipe in Angular. import {Pipe, PipeTransform} from 'angular2/core'; @Pipe({ name: 'messageTime', pure: false ...

Angular app - static List mysteriously clears out upon refresh

My goal is to create a login page using Angular. I have an Angular component with HTML, CSS, and TypeScript files that manage this functionality. The HTML file contains two fields (Username and Password) and two buttons (Login and Register). When a user en ...

What is the significance of incorporating react context, createContext, useContext, and useStore in Mobx?

In my Typescript application, I rely on Mobx for persistence and have created a singleton class called MyStore to manage the store: export class MyStore { @observable something; @observable somethingElse; } export myStore:MyStore = new MyStore(); ...

Retrieve the values of a dynamic JSON object and convert them into a comma-separated string using Typescript

I recently encountered a dynamic JSON object: { "SMSPhone": [ "SMS Phone Number is not valid" ], "VoicePhone": [ "Voice Phone Number is not valid" ] } My goal is to extract the va ...

The specified main access point, "@angular/cdk/platform", is lacking in required dependencies

I recently updated my Angular app from version 8 to version 9. After resolving all compilation and linter errors, I encountered one specific issue that is causing me trouble: ERROR in The target entry-point "@angular/cdk/platform" has missing dep ...

File declaring Vue3 Typescript types

I'm working with a Vue3 plugin in JavaScript, here's a snippet of the code: const myPlugin = { install(Vue, config) { // do something } export default myPlugin; This code is located in index.js and will be called by app.use. F ...

Indeed verification using this in a separate constant

I'm currently working with React and TypeScript, and I need to verify if my groupID exists in an array of [2, 3, 4]. I'm unsure about the validity of my validationSchema as I am encountering issues with a keyword that seems to be missing from th ...

Prevent a React component from unnecessarily re-rendering after a property has been set

I am working on a react component that displays a streaming page similar to the one shown in this image. Here is a snippet of the code : const [currentStream, setCurrentStream] = useState<IStream>(); const [currentStreams] = useCollectionData<ISt ...

What is the process for conducting integration tests on a live Angular application?

I'm currently facing a challenge in adding integration testing to my Angular 10 based application. Locally, everything seems to be running smoothly as I define the tests in files with the spec.ts extension and run them using ng test. However, the real ...

What is the process of loading data into mdbCharts following an API call?

I am currently having an issue with loading a PieGraph using mdbChart after making an API call. The problem is that I am getting errors while trying to load the data. Here is my code: public chartType: string = 'pie'; public chartDatasets: Array ...

Converting a ReactNode to an array: Step-by-step guide

I am attempting to develop a component where specific HTMLElements or ReactComponents are provided as follows: <ContentList> <span>Hi</span> // Child No. 1 <span>Hi2</span> // Child No. 2 <CustomComponent prop1={}& ...

What is the process for implementing a unique Angular theme across all components?

I created a unique Angular theme called 'my-theme.scss' and added it to the angular.json file. While it works with most Angular Elements, I am facing issues getting it to apply to certain HTML Elements inside Angular Components. For example: < ...

In my attempt to assess the correlation between value 1 and a value in the preceding object, I am utilizing the *ngFor directive

Attempting to compare 2 entries in an *ngFor loop. The code should compare the value at the current object to a value at the previous object. <ng-container *ngFor="let item of s_1.comments[0]; index as b"> <article class="message i ...