Troubleshooting: Resolving the issue of the 'innerHTML' property not being able to be set in Angular 6

Having trouble creating a custom calendar in my Angular 6 app after migrating code from JavaScript. Can't seem to resolve the run-time error that Angular is throwing.

Any help would be greatly appreciated!

Here is the StackBlitz link I am working on: StackBlitz!

showCalendar(month, year) {
const firstDay = (new Date(year, month)).getDay();
const daysInMonth = 32 - new Date(year, month, 32).getDate();

console.log('\n val \n' + new Date(year, month, 32).getDate());

const tbl = document.getElementById('calendar-body');

// clearing all previous cells
tbl.innerHTML = '';

// filing data about month and in the page via DOM.
this.monthAndYear.innerHTML = this.months[month] + ' ' + year;

 // creating all cells
let date = 1;
for (let i = 0; i < 6; i++) {
    const row = document.createElement('tr');

    for (let j = 0; j < 7; j++) {
        // let cell = document.createElement('td');
        if (i === 0 && j < firstDay) {
            const cell = document.createElement('td');
            const cellText = document.createTextNode('');
            cell.appendChild(cellText);
            row.appendChild(cell);
        } else if (date > daysInMonth) {
            break;
        } else {
            const cell = document.createElement('td');
            const cellText = document.createTextNode(date.toString());
        if (date === this.today.getDate() && year === this.today.getFullYear() && month === this.today.getMonth()) {
            // cell.classList.add("bg-info");
        } // color todays date
            date++;
        }
    }
    tbl.appendChild(row); // appending each row into calendar body.
  }
}

constructor() {
 this.today = new Date();
 this.currentMonth = this.today.getMonth();
 this.currentYear = this.today.getFullYear();
 this.monthAndYear = document.getElementById('monthAndYear');
}

ngOnInit() {
 this.showCalendar(this.currentMonth, this.currentYear);
 console.log('ngOnInit');
}

Expected result is It show a calendar.

But it is giving the error as:

ERROR TypeError: Cannot set property 'innerHTML' of null
    at CustomCalendarComponent.push../src/app/components/custom-calendar/custom-calendar.component.ts.CustomCalendarComponent.showCalendar (custom-calendar.component.ts:67)

Answer №1

Consider moving the code

document.getElementByid('monthAndYear')
to ngOnInit since there is no attached DOM when the constructor is called.

Check out this link for more details

In addition, it seems like the calendar generation logic needs some work as rows and cells are being added but left empty. It's worth looking into why this behavior is occurring.

Answer №2

Angular utilizes a separate API for manipulating the DOM. The Renderer2 provided by Angular is in the form of a service that allows you to manipulate elements of your app without directly touching the DOM.

If you need to select a specific element from the DOM, you can use a template variable and then access the element inside the component class using the ViewChild decorator.

component.html

<h3 class="card-reader" id="monthAndYear" #monthAndYear> Month and Year</h3>

component.ts

@ViewChild('monthAndYear') monthAndYear: ElementRef;

To create a new element, you can use Renderer2:

constructor(private ren: Renderer2) {}
const cell = this.ren.createElement('td');
const cellText = this.ren.createText('');
cell.appendChild(cellText);

Reference:https://alligator.io/angular/using-renderer2/

Forked Example:https://stackblitz.com/edit/angular-up1ibg

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

Building a frontend and backend using Typescript with a shared folder for seamless integration

I am currently exploring the idea of transitioning to TypeScript, but I am facing challenges in figuring out how to create a shared folder between the frontend and backend. This is the project structure that I have come up with: frontend - src -- server.t ...

Having difficulty updating an angular variable within a callback function

Currently, I am utilizing the Google Maps directions service to determine the estimated travel time. this.mapsAPILoader.load().then(() => { const p1 = new google.maps.LatLng(50.926217, 5.342043); const p2 = new google.maps.LatLng(50.940525, 5.35362 ...

Attempting to utilize Pinia without a corresponding component will result in an error indicating that there are no

In my Vue.js 3 project using the ViteSse template, I encountered an issue when trying to access my Pinia store named notificationStore outside of the setup component. When running the dev command, I received an error message saying "getActivePinia called w ...

Best Practices for Utilizing NPM Modules with TypeScript

I am interested in developing an npm module using TypeScript. Can anyone suggest a best practice guide on how to start? Here are my questions: Node.js does not natively support TypeScript, so what is the recommended way to publish an npm module? Shoul ...

Send the Children prop to the React Memo component

Currently, I am in the stage of enhancing a set of React SFC components by utilizing React.memo. The majority of these components have children and the project incorporates TypeScript. I had a notion that memo components do not support children when I en ...

Retrieving individual property from JSON with an array of values provided

Is there a way to extract names from the provided JSON, based on an array of IDs? [ { "id": 0, "name": "salesTransNo" }, { "id": 1, "name": "terminalNo" }, { "id": 2, "name": "salesTransDate" } ...

Tips for avoiding rule `@angular-eslint/template/i18n` from checking `mat-icon` tags

A strategy I implement is using the rule @angular-eslint/template/i18n to analyze template elements containing text nodes without an i18n attribute. In Angular Material, the identification of icon keys is done through the inner text of mat-icon elements, ...

Why is it so difficult for the TypeScript compiler to recognize that my variables are not undefined?

Here is the code snippet in question: function test(a: number | undefined, b: number | undefined) { if (!a && !b) { console.log('Neither are present'); return; } if (!b && !!a) { console.log('b is not present, we ...

A function in Angular 2 that subscribes to an Http Observable callback

I am facing an issue with the .subscribe function in my code. Firstly, I have a function that sends a request to the server. protected sendRequest(data:string,url:string):Observable<any>{ let headers = new Headers({ 'Content-Type': &a ...

Is it possible to view the list of errors displayed by vscode when opening a JS file exclusively through the terminal?

Is there a default configuration file that vscode uses to display errors and warnings? I want to identify all issues in my JavaScript project. I don't have any jsconfig.json or tsconfig.json files, only using the //@ts-check directive in some files. ...

Allowing the use of a string as a parameter in a Typescript constructor

Currently, I am utilizing TypeScript to create a constructor for a model within Angular. One of the attributes in the model is configured as an enum with specific string values. Everything functions well if an enum value is passed to the constructor. The i ...

Enums in Typescript that are based on strings

After going through all the information on String Based Enums in Typescript, I have yet to find a solution that fits my specific needs. These are the requirements I am looking for: Enums that offer code completion Enums that can be looped over No need to ...

Steps to perform a task that relies on two observables

I'm currently working on a function that requires two responses from two separate asynchronous functions, both returning observables. 1. Func1 returns an observable 2. Func2 returns an observable These functions are independent and can be executed sep ...

What is the correct method for service injection in Angular 8?

I have encountered an issue while trying to inject a service into my main "App" component. The error message is shown in the screenshot below: constructor(private newsApi: NewsApiService) {} Upon importing the service using the code above, I received the ...

The patchState function is iterated within the NGRX component-store effect

My program is stuck in an infinite loop and I can't figure out why. interface LatestAppointmentsWidgetState { loading: boolean; page: number; pagedData: Paged<Appointment>; } @Injectable() export class LatestAppointmentsWidg ...

Error detected in Ionic socket.io chat page

I'm encountering a minor issue with my chat page. I'm trying to create a chat application, and everything is working fine except for the chat button, which causes the app to crash. Being a beginner, I might be missing something obvious. The issue ...

This TypeScript issue in ServiceStack ignores namespaces, leading to duplicate declarations

Currently, I am exploring NativeScript and Angular2 with ServiceStack in C# as the backend. To develop the application, I utilized the typescript-ref command to generate TypeScript classes for use with the JsonServiceClient in ServiceStack: >typescrip ...

Using a double exclamation mark after a postfix in TypeScript

I understand the concept of using double negation prefixes and TypeScript's single postfix (non-null assertion). However, I am curious about the usage of a double postfix exclamation mark. /.*verification code is (\d{6}).*/.exec(email.body!!)!! ...

Using the VSCode debugger to place a breakpoint within a Typescript package that has been symlinked using `npm link`

I'm currently troubleshooting a NodeJS application and its associated typescript packages, which have been linked using `npm link`. The directory structure is as follows: /root/package-a # typescript package /root/package-b # another typescript packa ...

Creation of Card Component with React Material-UI

I am facing difficulties in setting up the design for the card below. The media content is not loading and I cannot see any image on the card. Unfortunately, I am unable to share the original image due to company policies, so I have used a dummy image for ...