What is the best way to showcase a variable from a typescript file in an HTML file with Angular?

In my TypeScript file, I have the following function:

ngOnInit() {
        if (sessionStorage['loyalPage']) {
          this.page = Number(sessionStorage['loyalPage']);
        }
    
        this.webService.getLoyalPlayers(this.page).subscribe((player_vars:any)=> {
          this.player_list= player_vars;
    
          for (let i=0; i< this.player_list.length; i++) {
            let clubJoined: Date = new Date(this.player_list[i].club_joined);
            let todayDate: Date = new Date();
    
            var clubJoinedYear = clubJoined.getUTCFullYear();
            var currentYear = todayDate.getUTCFullYear();
    
            var years_at_club = currentYear - clubJoinedYear;
          }
       })
    }
    
  • player_list: an array that contains players retrieved from MongoDB
  • clubJoinedYear: stores only the year when a player joined the current club
  • currentYear: holds the current year
  • years_at_club: calculates how many years a player has been at the club

I want to display the integer variable years_at_club in my HTML file and I am currently attempting it like this:

<div class="p-year">
        {{ years_at_club }}
    </div>
    

However, I encounter the following error:

Compiled with problems:

    ERROR

    src/app/loyal.component.html:71:24 - error TS2339: Property 'years_at_club' does not exist on type 'LoyalComponent'.

        {{ years_at_club }}
        ~~~~~~~~~~~~~

    src/app/loyal.component.ts:6:16
    6   templateUrl: './loyal.component.html',
                    ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoyalComponent.
    

https://i.stack.imgur.com/lw8a8.jpg

How can I resolve this issue and successfully print this value in my HTML file?

Answer №1

To access a variable from the HTML-file, you need to declare a public variable in the corresponding typescript file like this:

public years_at_club: number;

The use of var is limited to variables within a component, such as in a method. This type of variable is specific to the component instance and cannot be accessed from the linked HTML-file.

In the scenario of a for-loop, you can store each value of years_at_club retrieved from MongoDB into an array, defined as

public years_at_club_array: number[]
. New entries can be added using
this.years_at_club_array.push(currentYear - clubJoinedYear)
.

To display the array in the HTML-file, utilize a loop using *ngFor.

<div *ngFor="let item of years_at_club_array">
    <p>item</p>
</div>

Answer №2

yearsSpentAtClub:number;

initializeComponent() {
    if (sessionStorage['loyalPage']) {
      this.page = Number(sessionStorage['loyalPage']);
    }

    this.webService.fetchLoyalPlayers(this.page).subscribe((playerData:any)=>{
      this.playerList=playerData;

      for (let i=0; i< this.playerList.length; i++) {
        let datePlayerJoined: Date = new Date(this.playerList[i].join_date);
        let currentDate: Date = new Date();

        var yearPlayerJoined = datePlayerJoined.getUTCFullYear();
        var currentYear = currentDate.getUTCFullYear();

        this.yearsSpentAtClub = currentYear - yearPlayerJoined;
      }
   })
}

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

Encounter an error message "Expected 0 type arguments, but received 1.ts(2558)" while utilizing useContext within a TypeScript setting

Encountering the error mentioned in the title on useContext<IDBDatabaseContext> due to the code snippet below: interface IDBDatabaseContext { db: IDBDatabase | null } const DBcontext = createContext<IDBDatabaseContext>({db: null}) Despite s ...

Getting a date object that is three months prior to the current date in Typescript

I need to retrieve the date object that is 3 months before the current date by using the following code snippet: toDate = new Date(); fromDate = this.toDate.getMonth() - 3; The issue I am facing is that the variable fromDate only contains a number, but I ...

Issue with setting value using setState in TypeScript - what's the problem?

Every time I attempt to update the value of currentRole, it appears highlighted in red. Here is a screenshot for reference: const Container: React.FC<ContainerProps> = ({ children }) => { const [role, setRole] = useState<string>(); useE ...

Why does TypeScript struggle to recognize the properties of a type within a function parameter?

I am working with a `packages` object where I add items of the `Package` type ( See my code here and also Playground link), like this: type Callback = (obj: { source: string, types: string[], meta?: {} }) => void; interface Package { callback: ...

What is the best way to set up TSLint to apply specific rules with one line and different rules with another line

There is a unique method in which I can specify the code to format, such as forcing the else statement to be on the same line as the ending brace of an if statement. "one-line": [ true, "check-open-brace", "check-catch", "check-else", "check-fin ...

transfer information from a Node.js server to an Angular client using the get() method

I am trying to access an array of data from a node.js file using angular. In my node.js file, I have the following code: app.get('/search', function(req, res){ res.send(data); }); However, I am facing difficulties retrieving this data in an ...

React-file-viewer shrinks any document to a compact size

I have been searching extensively for information on how to adjust file sizing in react-file-viewer without any success. My objective is to utilize the react-file-viewer to allow users to click on a filename hyperlink and open the file (be it an image, do ...

What's the reason for the malfunction of the "required" attribute in my Angular form?

I'm a beginner when it comes to using Angular. Here's the template I've set up for a Register page in Angular. All labels and inputs are enclosed within the form tag. However, I'm facing an issue where the default behavior of 'requ ...

A step-by-step guide on importing stompjs with rollup

My ng2 app with TypeScript utilizes stompjs successfully, but encounters issues when rollup is implemented. The import statement used is: import {Stomp} from "stompjs" However, upon running rollup, the error "EXCEPTION: Stomp is not defined" is thrown. ...

Why won't my code work with a jQuery selector?

I'm struggling to retrieve the value from a dynamically generated <div> using jQuery. It seems like the syntax I'm using doesn't recognize the div with an id tag. The HTML code is stored in a variable, and below is a snippet of code w ...

Using TypeScript to convert a JSON date string into a Date object

The backend is sending me a JSON data structure that resembles the following: [{ "schedulingId": "7d98a02b-e14f-43e4-a8c9-6763ba6a5e76", "schedulingDateTime": "2019-12-28T14:00:00", "registrationDateTime": "2019-12-24T16:47:34", "doctorVie ...

Accessing element from view within controller in Ionic version 3.5

I am currently working on a project in Ionic 3.5, where I need to implement a feature that automatically loads an image "ad" after the page finishes loading. Right now, clicking a button successfully displays the image. However, I want this functionality ...

Error TS2322: You cannot assign a Promise<any> to a string type

Having an issue in my react app where I am attempting to import the img source but encountering an error: TS2322: Type 'Promise<any>' is not assignable to type 'string'. What is the correct way to import an element into a variabl ...

Utilizing Observable to dynamically bind ngClass in Angular

I currently have a container with the following structure <mat-sidenav-container [ngClass]="{'sidepanel-opened': ((isSidePanelVisible$ | async) as isSidePanelVisible) == true }"> </mat-sidenav-container> I am trying to u ...

Tips for Disabling ML5 Posenet

Looking to halt Posenet after completing app task private sketch(p: any) { p.setup = () => { this.poseNet = ml5.poseNet(p.createCapture(p.VIDEO), { outputStride: 8 }); this.poseNet.on(&apos ...

The promise was not handled properly as it was rejected with the message: "The constructor xhr2

Currently, I am working on developing an application using ASPNetCore and Angular 5 with Webpack. However, after upgrading to Angular 5, I encountered the following error: Unhandled Promise rejection: xhr2.XMLHttpRequest is not a constructor ; Zone: <r ...

Testing event handling in CdkDragDrop functionality

I've been experimenting with unit testing for my Angular application. Utilizing Angular Material, I have a component that incorporates the drag-drop CDK cdk drag-drop API. Here's what the HTML code looks like: <mat-card class="interventionCa ...

Unable to use console log in shorthand arrow function while working with Typescript

When debugging an arrow function in JavaScript, you can write it like this: const sum = (a, b) => console.log(a, b) || a + b; This code will first log a and b to the console and then return the actual result of the function. However, when using TypeSc ...

Bovine without Redis to oversee queue operations

Can Bull (used for job management) be implemented without utilizing Redis? Here is a segment of my code: @Injectable() export class MailService { private queue: Bull.Queue; private readonly queueName = 'mail'; constructor() { ...

Encountering an issue with Angular Material's MatTable when trying to set the datasource data to an interface

My angular material mat-table previously used a data type interface, which looked like this: dataSource : MatTableDataSource<IAddress>; dataSource.data = this.testData; interface IAddress { name: string; address: string: city: string; state: ...