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}}</li>

Upon selecting a HERO, the function onSelect() is triggered, passing the specific "hero" object, which then gets assigned to selectedHero in order to display that particular information using the this functionality.

I'm curious about how exactly we obtain the detailed information about the selected "hero," enabling us to pass it through the onSelect() function by just selecting the HERO.

Answer №1

If you're feeling a bit lost on this line of code, don't worry, let's break it down together.

<li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}</li>

Firstly, the *ngFor directive is responsible for generating a list of items based on the "heroes" array. This functionality is made possible through Angular's structural directives.

To simplify further, when we look closely at "*ngFor="let hero of heroes"," what it essentially means is that for each element in the heroes array, a new < li > tag is created. Within the context of this newly created < li > tag, a variable named "hero" is introduced to represent the corresponding element from the heroes array. It's worth noting that this "hero" variable is only valid within the scope of the specific < li > tag it belongs to.

Let's illustrate with an example: if we had an array like myNumArray = [1,5,7,8], and utilized a structure like this:

<li *ngFor="let num of myNumArray" (click)="console.log(num)">{{num}}</li>

The outcome would display:

  • 1
  • 5
  • 7
  • 8
  • Each instance of "num" within the < li > tags references the respective value from myNumArray, establishing a direct connection via the ngFor directive. Furthermore, every < li > tag responds to click events by logging its own unique number to the console. Clicking on 1 will log "1," clicking 5 will log "5," and so forth.

    The ability to access the local variable "hero" within the same element where "ngFor" is invoked is due to Angular's template magic. The * symbol actually operates beyond the initial container and generates a template. For additional insights into leveraging * and ngFor effectively, refer to this resource: https://angular.io/guide/structural-directives#the-asterisk--prefix

    I trust this breakdown has addressed your concerns and shed light on how individual "hero" entities are formulated distinctively within the setup.

    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

    Having trouble managing TypeScript in conjunction with React and Redux

    As a newcomer to TypeScript, I find myself struggling to grasp the concepts and know where to start or stop. While there are abundant resources available online, I have not been able to effectively utilize them in my project. I am hopeful for some guidance ...

    Converting coordinates of latitude and longitude into JSON format

    I'm currently facing some challenges with organizing map waypoints, defined by latitude/longitude pairs, within a JSON array. This is the progress I've made so far. var llData = {}; var waypointData = {}; for (i = 0; i < routeArray.length; ...

    What could be causing the JSON.parse() function to fail in my program?

    Currently utilizing Django and attempting to fetch data directly using javascript. Below are the code snippets. Within the idx_map.html, the JS section appears as follows: var act = '{{ activities_json }}'; document.getElementById("json") ...

    Is it possible to avoid sending multiple $http requests in Angular? Are there more efficient methods available?

    I have developed a rather intricate method for retrieving resources using $http. This method returns a promise and first checks my local cache to see if the resources are already available. If they are, it will return the cached data; if not, it will make ...

    Utilizing Array Elements to Populate the Title Attribute in <TD> Tags

    I am trying to display text on hover of a cell in my dynamically created HTML table, using the title attribute. However, instead of reading the contents of the array, it is displaying the array name as a string. Below is the code for generating the table ...

    What is the best way to retrieve the following database results after clicking a button with Node.js?

    Currently, my Node.js setup is successfully connected to my webpage and pulling data from a MySQL database. I have managed to display the first row of data as button values in the HTML code below. However, what I now want is for the user to be able to cl ...

    Encapsulate ng-style within quotation marks

    I am trying to hide a span if the value of filters[*index*] is empty. var span = "<span ng-style='{ 'display': filters[" + filterIndex + "] == '' ? 'none' : 'inline-block' }'></span>" cell.html ...

    Angular 13 ModuleWithProviders Bug: A Dilemma Worth Solving

    After creating a module and adding a service provider to its forRoot() static method, I imported the module into my app.module.ts file and included it in the imports section as ZooModule.forRoot(). However, when I attempted to inject the service from the Z ...

    Transmitting data from the front end to the server in React/Shopify for updating API information using a PUT request

    After successfully retrieving my API data, I am now tasked with updating it. Within my component, I have the ability to log the data using the following code snippet. In my application, there is an input field where I can enter a new name for my product an ...

    The Ionic view is not reflecting updates in real-time when there are changes to the component properties

    Having an issue with updating stock data on the view in my ionic 3 project. I am able to see frequent updates in my component and console, but these changes are not reflected on the view as frequently. For every 10 updates in the component, only 1 update i ...

    Using JSON data to populate an HTML page

    I'm currently working on a project that involves creating a "Twitter" page. The idea is to utilize the JSON file available at to display some of its content. However, I'm facing an issue where my page only shows the table headers and nothing els ...

    Using JavaScript to parse JSON and set the value of a DatePicker

    I have a text input field in my .cshtml page which is a Date type field. <div class="form-group"> <label for="comments">ETA:</label> <input class="form-control text-box single-line" data-val="true" id="MilestoneETAEdit" name ...

    Guide to deploying Angular application on a weblogic server using a WAR/EAR file

    I am facing difficulties deploying an Angular application on a WeblogicApplication server. My current approach is not yielding successful results: This is what I have done: 1) Built my Angular application using exec-maven-plugin and placed the result i ...

    Clicking to Load Images - Angular

    Implementing a feature to load sets of images on button click instead of loading all at once. Although lazy load plugins are available, I decided to experiment with this approach. Here's the logic: Start with a data array called 'Images' co ...

    Tips for handling two JSON array objects with JavaScript

    This particular function public function groups_priviledges($user_id = NULL){ $data['groups'] = $this->priviledges_model->admin_groups(); $data['member'] = $this->priviledges_model->empAdminGroup($user_id); echo ...

    The arrow keys (up and down) are unresponsive when using mat-table in an Angular application

    There seems to be an issue with my code. When I press the down arrow key for the first time, it goes to the next row as expected. However, when I press the down arrow key again, it does not function properly. (https://i.stack.imgur.com/4qznx.jpg) **HTML* ...

    How can I modify the value of a CSS animation rule in AngularJS?

    I am looking to dynamically change the value assigned to stroke-dashoffset based on a custom input. @-webkit-keyframes donut-chart-1 { to { stroke-dashoffset: 100; } } @keyframes donut-chart-1 { to { stroke-d ...

    Issues with ngClass in AngularAngular's ngClass feature is failing

    In my ngClass condition, it looks like this: <div [ngClass]="{'alert alert-danger': alert.type == 0,'alert alert-success': alert.type == 1}" When alert.type == 1, the class is set to alert alert-success. But when alert.type = 0, th ...

    Preserving the button's state when clicked

    Here is my code snippet: <blink> const [thisButtomSelected, setThisButtomSelected] = useState(false); var thisButton = []; const onAttributeClick = (e) => { thisButton[e.currentTarget.value] = { thisID: e.currentTarget.id, thisName: e. ...

    Scrape JSON Data and Convert Military Time to Standard Time Using JavaScript

    I have a question about scraping JSON data from a URL. The timestamps are in military time and I'm looking for a way to convert them to standard time on the client side. Here is the JSON snippet: [ { SaturdayClose: "21:00", SaturdayOpen: " ...