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

Mastering Angular: Accessing undefined properties (specifically 'push')

Currently, I am in the process of learning Angular and have encountered an issue while working on an assignment. The error message that I am facing is "Cannot read properties of undefined (reading 'push')." Despite knowing that this is a common e ...

Having Trouble with Building After Fork and NPM Installation on GitHub

https://github.com/czeckd/angular-dual-listbox Discovering a Github repository that caught my attention, I decided to incorporate it into my Angular 5 application. However, after noticing certain styles and functionality that needed modification or additi ...

Transforming Image Annotation from Angular 1 to Angular 4: Overcoming Conversion Challenges and Comparing Equivalents from 1.x to 4

After exploring various options, I am still struggling to resolve the conversion error that occurs when trying to convert my Angular 1.x script for image annotation into Angular 4. The equivalent of angular 1.x code in Angular 4 is not readily available. H ...

The type 'Observable<Subscription>' does not match the type 'Observable<MyData>' in RxJS Angular

When utilizing Angular, I've developed a service that retrieves data from multiple sources and combines it with the original service. Below is the code snippet: searchData(): Observable<MyData> { const url = `${this.context}/search`; ret ...

What could be the reason for the failed authentication HTTP request to Firebase resulting in error 400?

Ensuring the correctness of the API: ''' https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[API_KEY] ''' source Verifying my API Key: https://i.sstatic.net/N4daZ.png The request made from a component: import { In ...

Unable to retrieve iFrame window due to an error

My challenge lies in obtaining the window of an iFrame using this particular code: var frameWindow = document.getElementById("loginframe"); var iWindow = frameWindow.contentWindow; However, I am consistently encountering this error message: Property ...

Access to Angular component generation was denied due to EACCES permissions issue

Every time I attempt to create a new component for my Angular application, I immediately encounter a permission denied error without any clear explanation. The command that triggers this issue is ng g component heroes I have attempted to apply chmod -R 7 ...

Using Angular to pass an index to a pipe function

Currently, I am attempting to incorporate the *ngFor index into my pipe in the following manner: <td *ngFor="let course of courses | matchesTime:time | matchesWeekday:i ; index as i">{{course.courseName}}</td> This is how my pipe is structure ...

Expected single URL matching error in HttpTestingController

While testing my http service class and attempting to test the request, I encountered the following error: Expected one matching request for criteria "Match URL: https://beneficios/api/v1/processobeneficio/1111111111111/timeline", found none. I'm puz ...

Utilizing the spread operator in Typescript to combine multiple Maps into a fresh Map leads to an instance of a clear Object

Check out the code below: let m1 = new Map<string, PolicyDocument>([ [ "key1", new PolicyDocument({ statements: [ new PolicyStatement({ actions: [&q ...

Unexpected behavior observed with field alignment

I've been attempting to align the field in an Angular HTML page, but it's not working out as I expected. Here's how the HTML file looks: <div id="report-prj-search"> <div class="dx-fieldset flex-column"> <div class="fle ...

Running multiple instances of an Angular2 module on a single page using Bootstrap

I have a unique situation where my web forms application dynamically loads User controls onto a page using configurations, similar to a CMS with re-usable widgets. I'm interested in implementing one of these user controls as an Angular2 component. &l ...

How to assign a value to a component variable using props in Vue.js

I am attempting to assign a props value to my component variable. Below is the code I'm working with: export default { props: { // eslint-disable-next-line vue/require-default-prop multiPaginatedTableTitle: { type: Stri ...

Creating a table and filling it with data from any cell is a simple process

I have a question about creating an HTML table similar to the image shown here: image I want to populate the table with data from a JSON response received from a web service: { "ErrorCode": 0, "ErrorMessage": "ok", "Data": [ { ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

Having trouble obtaining the ref.current.offsetWidth?

I have been working on creating a contextMenu. My goal is to retrieve the offsetWidth and offsetHeight from ref.current, but when I console.log it, it shows as undefined. const ContextMenu: React.FC<ContextMenuProps> = props => { const thisCom ...

Tracking button clicks on Angular Material using Google Analytics through Google Tag Manager

I'm currently utilizing the Universal Analytics tag within Google Tag Manager to monitor user interactions. I'm looking to establish click listeners in GTM that will trigger when specific buttons on the page are clicked. These buttons are Angular ...

Postpone the initial click action triggered by the specified directive

Is it possible to create a directive that prompts for confirmation when a button is clicked? This would involve storing the original event and only executing it once the user confirms their choice. A similar behavior has been mocked here: https://stackbl ...

The modification in Typescript's type order from version 1.7 to 1.8 resulted in a significant

A Visual Studio Cordova application with a unique TypeScript source structure: /src /app /appsub1 appsub1.ts -> 4 : 7 /appsub2 appsub2.ts -> 5 : 6 app.ts -> 3 : 5 /mod1 /mod1sub1 mod1sub1.ts -> 7 : 4 m ...

Can someone please explain how to display a specific element from a JSON Array?

Is there a way to display only this specific part? /db/User_DataDb/61500546-4e63-42fd-9d54-b92d0f7b9be1 from the entirety of this Object obj.sel_an: [ { "__zone_symbol__state":true, "__zone_symbol__value":"/db/User_DataDb/61500546-4 ...