The Typescript function is unable to locate the variable. It is showing an error message 'Cannot find name 'height'.ts(2304)'

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-portfolio',
  templateUrl: './portfolio.component.html',
  styleUrls: ['./portfolio.component.css']
})
export class PortfolioComponent implements OnInit {

  height = window.innerHeight;
  windowHeight: any;

  constructor() {
   }


  ngOnInit(): void {

    const button = document.getElementById("btn");
    button?.addEventListener("click", this.listenerFunction);

    const button2 = document.getElementById("btn2");
    button2?.addEventListener("click", this.listenerFunctionButton);
  }

  listenerFunction(this: HTMLElement, ev: Event) {
    ev.preventDefault();
    console.log("clicked");
    window.scrollTo({top:height, behavior:'smooth'})
    this.height+= 100;
  }

  listenerFunctionButton(this: HTMLElement, ev: Event) {
    const height = window.innerHeight;
    ev.preventDefault();
    console.log("clicked");
    window.scrollTo({top:-height, behavior:'smooth'})
  }

}

I'm currently developing a functionality that involves scrolling up and down on my website using two buttons. While the current setup allows for one page scroll up and one page scroll down, I need to make it possible for users to scroll further with each button press. The issue lies in trying to access a variable within a function which is proving to be more challenging than expected.

The specific problem is related to how I can't use my 'height' variable inside the function without encountering errors. Despite trying different approaches like initializing 'height' above the constructor, the error message persists: "Property 'height' does not exist on type 'HTMLElement'.ts(2339)". It seems like I'm overlooking a simple solution to this issue. Any assistance would be greatly appreciated.

TLDR: Struggling to utilize local variable in a function.

Answer №1

Your code has a few issues that need to be addressed. Firstly, the variable height is being declared inside the constructor which means it won't be accessible outside of that scope. It would be better to declare height as a property of your class so it can be accessed throughout the component. Additionally, avoid using reserved keywords like this as arguments in your class methods. Furthermore, directly accessing the DOM with functions like document.querySelector() is not recommended in Angular due to various reasons. It's best to utilize the provided abstractions by Angular instead.

Angular is indeed a powerful framework but it does demand a strong grasp of JavaScript. I recommend brushing up on your JS skills before diving into TypeScript and Angular development.

Answer №2

Instead of using let, opt for this when declaring a variable within the constructor, and also add a class-variable outside of it.

This way, you can declare the variable as a class-variable (allowing access to it from the HTML file), and then initialize it within the constructor like in the code snippet below:

export class PortfolioComponent implements OnInit {

  public height: any;

  constructor() {
      this.height = windows.innerHeight;
  }
}

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

The seamless transformation from HTML table to angular material table (mat-table)

I am a beginner in Angular Material and I am attempting to transition a basic Angular table into an Angular material table using mat-table Uncertain of where to start, how can I convert the following table into mat-table? This is my .html file that conta ...

Retrieve a specific key from a TypeScript interface

It seems like there might be a problem with this code snippet: interface import {BrowserService} from "../services/browser/index"; export interface IPrimaryNavigation { opts:IPrimaryNavigationOpts; } export interface IPrimaryNavigationOpts { .. ...

Convert an interface type variable to a string representation

I'm just starting to learn angular and I'm attempting to convert my response from an interface type into a string so that I can store it in session storage. However, when I try to save them, they are being stored as [object] in the session storag ...

The appearance of DC charts can vary when constructing an Angular application in production mode

Currently, I am in the process of developing an application that utilizes d3, dc, and crossfilter for rendering charts. crossfilter2: v1.4.6 d3: v3.5.17 dc: v2.2.1 I have been working on adjusting the Y scale to display only w ...

In Angular 2, when creating an assignment expression, the left-hand side must either be a variable or a property access

I am encountering an issue that states: The left-hand side of an assignment expression must be a variable or a property access. Whenever I use this block of code, it triggers the error mentioned above. Can someone assist me in resolving this? this.i ...

How can we toggle a function to expand or collapse fields generated in an ngFor loop?

One of my challenges involves managing a div that is repeated using *ngFor in Angular. This results in multiple divs on the page, each containing collapsible fields that can toggle. Essentially, I have nested collapsible fields within other collapsible fie ...

Utilizing the Querystring in place of semicolons: A beginner's guide

Currently, I have been working on developing an internal tool specifically designed for developers utilizing Angular2 beta 15, backed by a C# WebApi. As new versions of Angular2 are released, I ensure to upgrade accordingly. While I have incorporated rou ...

Ways to adjust the size of ngx-datatable when the navigation bar is being toggled

When you first open the page, the <ngx-datatable> appears like this https://i.sstatic.net/BQvBw.png But once you click on the navbar, it transforms into this https://i.sstatic.net/p8Bfd.png In the second image, you can see that the navbar column ...

Generating a customizable PDF using jSPDF

I am in need of creating a dynamic PDF document with text content that could change along with their positions. The header columns are defined as an object array below: [ { "title": "Occupied Vacancies", "dataK ...

Is it possible to refresh the component view using the service?

I am interested in developing a NotificationService that will be utilized to showcase a notification from another section. My inquiry is, how can I refresh the view of a component using a service? My ultimate goal is to have the capability to embed a comp ...

Components in Angular 4 that are loaded dynamically using attribute directives are enclosed within a <div> element

My goal is to dynamically generate components based on the configuration options, specifically creating a toolbar with different "toolbar items". Following the Angular guide at: https://angular.io/docs/ts/latest/cookbook/dynamic-component-loader.html, I h ...

Encountering Error 404 while submitting a form on Prisma, Axios, and NestJS

Currently, I am working on a Sign Up page using SolidJs and NestJS with Prisma. However, when I try to submit the form, I encounter an error that says POST 404 (Not Found) and this error is also returned by axios. Additionally, my setup includes postgres ...

A practical guide to troubleshooting typescript errors when exporting a map component

I encountered a typescript error when trying to export the map component with GoogleApiWrapper. It works fine when not wrapped in GoogleApiWrapper, but all my attempts to resolve the issue have failed. I would appreciate it if someone could review the code ...

Struggling with consolidating values in an array of objects - seeking assistance with Javascript

Currently, I am handling a project where I receive data in the form of an Object Array. My task is to merge values with the same key into one key and convert the values into an array of strings. Below is the sample data I am working with: inputArray = [ ...

It appears that the ChangeDetectionStrategy.OnPush is not functioning properly in the case of receiving a destructured object from a service

Implementing the OnPush strategy, a service is utilized to update some data. However, upon receiving the data in the component, it requires a click on the screen to reflect the changes. Parent.ts // Click initiates the logic click() { this. ...

Jest fails to pass when encountering tsx syntax errors

Currently, I am incorporating jest tests into my project. The project is comprised of both TypeScript (.ts) and TypeScript JSX (.tsx) files. Below is a snippet from my jest.config.js file. module.exports = { preset: "ts-jest", testEnvironment: "jsdom" ...

Exploring TypeScript interfaces with optional properties and returning types

As a newcomer to TypeScript, I am currently exploring the documentation and came across an example in the "Optional Properties" section that caught my attention: interface SquareConfig { color?: string; width?: number; } function createSquare(config: ...

Angular and Bootstrap join forces to create collapsible rows

I'm implementing bootstrap collapse feature to display a details row upon clicking a button. However, the details row always appears below the first row instead of below the selected row. How can I make it show up below the clicked row? Here is my cod ...

Testing the Angular router-outlet using Jasmine

When testing web-app navigation using Jasmine spec with RouterTestingModule, I am facing challenges with nested fixture.whenStable().then(() => {}). For instance: After clicking on multiple links where the router-outlet changes the displayed component ...

The TypeScript Type inside the Node Module Doesn't Seem to Be Functioning

In my React project, I am using the material-ui@next library along with typescript. Below is the code snippet that I have written: <CardMedia image={item.image_url} style={{ width: 238, height: 124.5 }} /> However, when I try to compile this code, ...