Properly implement Angular/Typescript to populate an array with chosen objects

Currently, I have an Angular application that is fetching JSON resources from a Spring Boot REST API. These resources consist of simple player objects with attributes like id, name, position, and value. On the UI, each object is displayed along with a "BUY" button. When the user clicks on the "BUY" button, I want to store the selected object in an array. However, as a newcomer to TypeScript, I'm not sure how to connect the HTML method call to the logic in my .ts file.

Any assistance would be greatly appreciated. This feature is part two of my basic fantasy football-inspired app where the list (similar to an ArrayList in Java) will represent the user's selected players for their custom team.

COMPONENT.HTML:

<ul *ngIf="Ballers">
  <li *ngFor="let player of Ballers">
    <p class="name">{{player.name}}</p>
    <p class="position">{{player.position}}</p>
    <p class="value">£{{player.value}} m</p>
    <button class="buyButton" (click)="buyThisPlayer()">Add to Squad</button>
  </li>
</ul>

COMPONENT.TS:

@Component({
  selector: 'app-player-list',
  templateUrl: './playerList.component.html',
  styleUrls: ['./playerList.component.scss']
})
export class PlayerListComponent implements OnInit {

  Ballers: Object;

  constructor(private httpService: HttpService) { }

  ngOnInit() {
    this.httpService.getPlayers().subscribe(data => {
      this.Ballers = data;
      console.log(this.Ballers);
    });
  }

  buyThisPlayer(){
    selectedKickers.push(this); // Is this the correct way to add the object to the array?
  }
}

Answer №1

If you are solely focused on the click handler, you have the option to pass the player in the method and bind it accordingly:

<button class="buyButton" (click)="buyThisPlayer(player)">Add to Squad</button>
@Component({
    selector: 'app-player-list',
    templateUrl: './playerList.component.html',
    styleUrls: ['./playerList.component.scss']
})
export class PlayerListComponent implements OnInit {

  Ballers: any;
  selectedPlayers: any[] = [];

   constructor(private httpService: HttpService) { }

  ngOnInit() {
      this.httpService.getPlayers().subscribe(data => {
        this.Ballers = data;
        console.log(this.Ballers);
      })
  }

  buyThisPlayer(player){
   this.selectedKickers.push(player);
  }

There are some additional recommendations that I can provide for improving angular best practices. Feel free to reach out if you're interested.

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

Implementing a click event to convert text to input in Angular 5

I'm struggling with setting values instead of just getting them. I want to switch from using divs to input fields and update the values when in "editMode". <div class="geim__sets"> <div *ngFor="let set of game.sets" class="geim__set"> ...

Creating dynamic components in ReactJS allows for versatile and customizable user interfaces. By passing

Within the DataGridCell component, I am trying to implement a feature that allows me to specify which component should be used to render the content of the cell. Additionally, I need to pass props into this component. Below is my simplified attempt at achi ...

What is the best way to utilize nested components in Angular 2's latest stable release?

When using previous RC releases, we were able to use the directive tag for nested components. However, in the final release of Angular 2, the directive tag has been removed from components. So now, what is the best approach for placing one component inside ...

How can you check the status of a user in a Guild using Discord JS?

Is there a way to retrieve the online status of any user in a guild where the bot is present? Although I can currently access the online status of the message author, I would like to be able to retrieve the online status of any user by using the following ...

Is there a method in TypeScript to make an enum more dynamic by parameterizing it?

I've defined this enum in our codebase. enum EventDesc { EVENT1 = 'event 1', EVENT2 = 'event 2', EVENT3 = 'event 3' } The backend has EVENT1, EVENT2, EVENT3 as event types. On the UI, we display event 1, event 2, a ...

Utilizing Typescript to ensure property keys within a class are valid

Looking for advice to make a method more generic. Trying to pass Child class property keys as arguments to the Super.method and have Child[key] be of a Sub class. class Parent { method<T extends keyof this>(keys: T[]){ } } class Child extends P ...

Solving the issue where the argument type is not assignable to the parameter type

I am attempting to filter an array of objects in React using TypeScript and encountered this error. Below is my interface, state, and function: TS2345: Argument of type '(prev: IBudget, current: IBudget) => IBudget | undefined' is not assigna ...

TypeScript equivalent to Python's method for removing non-whitespace characters is achieved by

I understand that I can utilize .trim() to eliminate trailing spaces Is there a method to trim non-space characters instead? In [1]: str = 'abc/def/ghi/' In [2]: s.strip('/') Out[2]: 'abc/def/ghi' I am referring to the funct ...

After successfully binding data in Angular, the Select component is failing to display any content

I encountered an issue where the select option disappeared completely after trying to bind countries data inside a sign-up form. Below is the relevant code snippet: Data Model export class Countries { public name: string; public code: string; ...

Notify other components in Angular when a change has occurred without relying on intervals

In the footer component of my project, I currently have a code snippet that runs a check on LocalStorage every 15 seconds using a timer. ngOnInit() { const checkLocalStorage = interval(15000); checkLocalStorage.subscribe(data => { ...

Utilizing the Angular formArrayName directive in form elements

The Angular official documentation provides the following code example: @Component({ template: ` <form [formGroup]="form"> <div formArrayName="cities"> <div *ngFor="let city of cities.controls; index as i"> ...

Looking to retrieve the AssetLoadedFunc properties in the LoadAssets function? Wondering if you should use TypeScript or JavaScript

When I invoke this.AssetLoadedFunc within the function LoadAssets(callback, user_data) LoadAssets(callback, user_data) { this.glg.LoadWidgetFromURL("assets/Js/scrollbar_h.g", null, this.AssetLoaded, { name: "scrollb ...

Is it correct to implement an interface with a constructor in TypeScript using this method?

I am completely new to TypeScript (and JavaScript for the most part). I recently came across the article discussing the differences between the static and instance sides of classes in the TypeScript handbook. It suggested separating the constructor into an ...

Angular's ng toolkit universal experiencing loading issues and tools are malfunctioning

I encountered the following issue npm run build: prod commands are not functioning correctly ERROR: Cannot read property 'length' of undefined ERROR: If you think that this error shouldn't occur, please report it here: https://githu ...

Guide to developing a private shared Node.js module using TypeScript

I have a unique idea for a nodejs server service, consisting of: a REST API, and various asynchronous workers. My vision is to separate these components into different subnets and git repositories while still enabling them to access the same database en ...

Clicking on an element- how can I find the nearest element?

Encountering an issue with my next js app where I am attempting to assign a class to an element upon clicking a button. The problem arises when trying to access the next div using the following code snippet: console.log(e.target.closest('.request_quot ...

Unable to adjust the text color to white

As someone who is new to Typescript, I'm facing a challenge in changing the text color to white and struggling to find a solution. I'm hoping that someone can guide me in the right direction as I've tried multiple approaches without success ...

Exploring Heroes in Angular 2: Retrieving Object Information by Clicking on <li> Items

Currently, I am delving into the documentation for an angular 4 project called "Tour of Heroes" which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt2.html. <li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}< ...

Chrome stack router outlet and the utilization of the Angular back button

I'm experiencing an issue with the back button on Chrome while using Angular 14. When I return to a previous page (URL), instead of deleting the current page components, it keeps adding more and more as I continue to press the back button (the deeper ...

When using TypeORM's findOneBy method, if the search result

In order for the entity to have both identifiers, I require it to possess the Id and the _id export class ScriptSequencesExecutionEntity { @PrimaryGeneratedColumn({ name: 'id' }) _id!: string; @ObjectIdColumn() id: number; @AutoMap() ...