A guide to setting initial values in Angular 2 using TypeScript

My Rank class includes attributes for "loses" and "wins" obtained from a web service. I need to calculate the "points" attribute based on these values.

For example:

for(int i = 0; i<loses; i++{
   points += 1;
}
for(int i = 0; i<wins; i++{
   points += 2;
}

Rank Class

class Rank{
  $id?:number;
  loses?:number;
  team?:string;
  wins?:number;
  points: number;

  constructor(){}
}

Where should I implement this logic?

Answer №1

My suggestion is to perform the calculation within the Rank constructor.

class Rank {

  public points: number;

  constructor(public id: number, public losses: number, public teamNum: number, public victories: number) {
    this.points = victories - losses;
  }
}

The reason why points are not passed to the constructor is because they are determined during the object's creation process. For further information on the purpose of constructors, you can visit this link

Answer №2

To incorporate your logic within the Rank class, you can utilize a setter function as demonstrated below:

class Rank{
  $id?:number;
  loses?:number;
  team?:string;
  wins?:number;
  points: number;

  constructor(){}

       set updatePoints( wins: number, loses:number) {
       this.points += loses; // Adjust points for losses
       this.points += wins*2; // Adjust points for wins
       // Alternatively, you can modify points like this: this.points += loses + (wins*2)
        }
}

I trust this information proves beneficial to you.

Answer №3

After much searching, I have finally discovered a solution. Instead of initializing the points value inside the class, I moved it inside the component.

export class RankingComponent implements OnInit {

  ranks: Rank[];;
  constructor(private firebaseService: FirebaseService) { }

  ngOnInit() {
    this.firebaseService.getRanks().subscribe(ranks => {
      for(let rank of ranks){
        rank.points = (rank.loses) + (rank.wins*2)
      }
      this.ranks = ranks;
      console.log(ranks);
    })
  }

}

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 Console.log function first displays an Object, and then changes to display an Array containing a single object when clicked

When I utilize MobX to call an observable within my React component, something peculiar happens. Upon console logging the observable, initially it appears as an Object. However, upon clicking on it, the object transforms into an Array for that one particul ...

How can I get the class name of the drop destination with react-dnd?

Imagine having this component that serves as a drop target module. import { useDrop } from 'react-dnd'; import './css/DraggableGameSlot.css'; type DraggableGameSlotProps = { className: string, text: string } function Draggable ...

Issue TS2769: No matching overload found for this call. The type 'string | null' cannot be assigned to type 'string | string[]'

export class AuthService { constructor(private http: HttpClient, private webService: WebRequestService, private router: Router) { } login(email: string, password: string) { return this.webService.login(email, password).pipe( shareReplay(), ...

Can you explain the significance of the | symbol in TypeScript?

My journey with TypeScript is just beginning, and I recently encountered the symbol | while working on a problem in LeetCode using Typescript. I believe it has something to do with defining variable types. Can anyone provide more insight into this? /** ...

How to Show Concealed Text in Material UI Multiline TextField and Obtain Unveiled Text

I am currently using the Material UI TextField component to create a multiline input for messages. My aim is to display a masked version of the text in the GUI while retaining the unmasked text value for processing purposes. Below is the code snippet for ...

Changing field visibility in Angular Reactive form (form validation) by toggling based on a checkbox in another component

I'm facing a challenge with a complex form where the fields depend on toggling checkboxes in a separate component (parent). My goal is to dynamically validate the form, with some fields being enabled and others disabled based on the toggling of the ch ...

Injecting singletons in a circular manner with Inversify

Is it possible to use two singletons and enable them to call each other in the following manner? import 'reflect-metadata'; import { Container, inject, injectable } from 'inversify'; let container = new Container(); @injectable() cla ...

Warning: React Hook Form, NumericFormat, and Material-UI's TextField combination may trigger a reference alert

I'm currently working on a Next.js project using TypeScript and MUI. I'm in the process of creating a form that includes a numeric field for monetary values. In order to validate all fields upon form submission, I have decided to utilize yup, rea ...

Guide on setting a default value for a variable within a Typescript class

In the process of developing a component to manage information about fields for form use, I am in need of storing different data objects in order to establish generic procedures for handling the data. export class DataField<T> { /** * Field ...

Navigating through multiple pages using an Observable in Angular

After countless attempts, I still haven't been able to figure it out. Any assistance would be greatly appreciated; I recently came across Angular and RxJs. The issue I'm facing involves a service that fetches resources from various URLs of the s ...

Tips for assigning multiple Angular2 variables in Jquery on change

I am having trouble assigning more than one variable in jQuery within Angular2. Here is my current code: jQuery('.source-select').on('change',(e) => this.updateForm.value.sources = jQuery(e.target).val().split('--')[0]); ...

Create interfaces for a TypeScript library that is available on npm for export

I have a project in TypeScript that I am packaging as a library to be used by both JavaScript and TypeScript projects. After compiling, I upload the .js and .d.ts files to npm. The main.ts file exports the following: interface MyInterface{ // ... } clas ...

Typescript error: Cannot access property "status" on type "never".ts(2339)

Currently, I have a method that utilizes nextjs/auth to sign in with credentials from a form. However, I am encountering a type checking error Object is possibly 'undefined'.ts(2532) const doStuff = async (values: any) => { const result: S ...

Quick tip: Adding a close 'X' button to an ng-bootstrap popover

As a newcomer to angular 5, I have been working on adding an 'x' button in the top right corner of a popover. Once this 'x' is clicked, the popover should be closed. Is there a way to achieve this using ng-bootstrap popover? Below is my ...

What is the best way to instantiate objects, arrays, and object-arrays in an Angular service class?

How can I nest an object within another object and then include it in an array of objects inside an Angular service class? I need to enable two-way binding in my form, so I must pass a variable from the service class to the HTML template. trainer.service. ...

In Angular 4, I encountered an issue where adjusting the height of the navigation bar caused the toggle button to no longer expand the menu in Bootstrap

In the process of developing an angular application, I encountered a situation where I needed to adjust the height of the nav bar using style properties. After making the necessary changes, everything was working fine. However, a problem arose when I mini ...

The Child/Parent arguments in Typescript methods cannot be assigned

Why is this not working in TypeScript? class Parent { id: string = '' } class Child extends Parent{ name: string = '' } const fails: (created: Parent) => void = (created: Child) => { return }; const failsToo: ({ create ...

transformation of categorized unions in software development

Experimenting with routing-controllers and its built-in class-transformer feature, I tried creating an interface for executing a search query based on either a location id or location coordinate. My aim was to utilize a discriminated union as a body parame ...

Creating Empathetic User Experiences with Next 12 and SWC: A Guide to Harnessing import.meta.url

In my Next.js 12 App with the Rust Compiler, I am utilizing Jest and WebWorkers. In one of my files, I am using import.meta.url. to create the worker. The issue arises when Jest throws an error, stating that import.meta.url cannot be used outside of an ES ...

Develop a novel object framework by merging correlated data with identical keys

I am trying to organize the related data IOrderData by grouping them based on the productId and brandId. This will help create a new array of objects called IOrderTypeData, where the only difference between the objects is the delivery type. Each product id ...