Leveraging String Interpolation for Retrieving Array Values in Angular2 Application

In my Angular2 application, I have implemented a functionality where I loop through a list of users and display an icon to represent each user. Now, I want to enhance the user experience by using material2's tooltip (mdTooltip) feature to display the name of the person when hovering over the icon. While I was able to successfully implement the tooltip with a singular property using string interpolation, I faced challenges when trying to extract the name from an array in the same component.

Below is an excerpt from my component:

import { User } from './../../views/user/user';
import { Component, OnInit, Input } from '@angular/core';
import { AuthenticationService } from './../../data/authentication.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-room',
  templateUrl: './room.component.html',
  styleUrls: ['./room.component.less']
})
export class RoomComponent implements OnInit {

  otherImg = 'app/img/photo-ph.png';
  model: any;
  loading = false;
  name = 'John Smith';

  others = [
    { id: 1, name: 'John Smith', avatar: 'app/img/photo-ph.png' },
    { id: 2, name: 'Javier Sanchez', avatar: 'app/img/photo-ph.png' }
  ];

  user;
  token;
  nickname;

  constructor(private authenticationService: AuthenticationService,
              private router: Router) { }


  isLoggedIn() {
    this.loading = true;
    if (this.authenticationService.isAuthenticated()) {
      return true;
    }
  }

  ngOnInit() {
  }

}

The following snippet shows the version of my component HTML that functions correctly:

<div *ngIf="isLoggedIn()" class="others">
    <span *ngFor="let other of others"><i [ngClass]="'material-icons'" [routerLink]="['/chat']" mdTooltip="{{name}}" tooltip-position="below">person</i></span>
    <a [routerLink]="['/login']">Logout</a>
</div>

However, when I attempted to use string interpolation to fetch a value from an array and utilize it in the tooltip, it did not yield the desired result. Below is the troublesome part of my component code:

<div *ngIf="isLoggedIn()" class="others">
    <span *ngFor="let other of others"><i [ngClass]="'material-icons'" [routerLink]="['/chat']" mdTooltip="{{others.name}}" tooltip-position="below">person</i></span>
    <a [routerLink]="['/login']">Logout</a>
</div>

Answer №1

If others is an array in your scenario, it does not possess a "name" property. However, you are already iterating over it and assigning each value to "other".
Therefore, the following code will function as intended:

mdTooltip="{{other.name}}"

Answer №2

It seems like you are accessing the array instead of the instance variable

{{others.name}}

It should be

{{other.name}}

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

Deleting graphic lines from google maps

After using the DirectionsRenderer to display a path, I'm struggling to remove the polyline and move on. It seems like I have no control over the markers and polylines created by this function. Does anyone have a solution for removing such polylines? ...

Adjust `theme-color` as the class and theme of the page are switched

My website has a JavaScript toggle that changes the color/theme of the page by adding/removing classes on the html element. The default theme is white, the second theme is black (.dark-mode), and the third theme is beige (.retro). The JavaScript code for ...

Discover Repetitive Entries within the Gridview employing Javascript

I need assistance with a specific requirement. My Gridview has two columns: Name of Model Model Description Model A Model A Description Edit Update Cancel Model B Model B Description Edit Update Cancel Model C Model C Description Edit Update C ...

Error: The AjaxMethod "Class" is not defined

I have an older asp.net project that utilizes Ajax.AjaxMethod() to invoke server-side code from Javascript. It used to function properly, but now it has suddenly ceased to work. Here is the C# code behind: public partial class Signup : System.Web.UI.Page ...

Getting data into Highstock from a PHP MySQL database through an AJAX call

I'm working on plotting a graph with Highstock using data from MySQL fetched through an AJAX call. While the data and dates print correctly in console.log(), I encounter a discrepancy in the date values when displaying the graph. Below is my index.ph ...

In Angular 8, create a custom message for ngFor to display when the data from the pipe filter is empty

One of my components utilizes a custom pipe called PlanCodePipe to filter documents based on plan codes. However, there are times when the filter results in 0 matches. <div *ngIf="(StatementData$ | async) as stmtData; else stillLoading"> ...

Maximizing the efficiency of a personalized hook that facilitates data sharing in React

I have developed a unique Custom Hook that looks like the following: import { useEffect, useState } from 'react'; import axios from 'axios'; const myCustomHook = () => { const [countries, setCountries] = useState([]); const [i ...

Error encountered when using prisma findUnique with where clause

Trying to set up a Singup API using ExpressJS and Prisma is proving to be a bit challenging. The issue arises when I attempt to verify if a given email already exists in my database. Upon passing the email and password, an error is thrown stating Unknown ...

Querying MySQL for unique values stored in an array and then utilizing them in a function

// Querying MySQL to retrieve distinct Schools from the database // Storing the distinct schools in an array named $allSchools $sllSchoolsQuery = "SELECT DISTINCT stud_school AS schools FROM students"; $schoolNames = mysqli_query($conn, $sllSchoolsQuery); ...

Setting up the Angular 2 environment with angular-cli: A step-by-step guide

Attempting to configure environment settings using angular-cli following the guide at https://github.com/angular/angular-cli#build-targets-and-environment-files However, even after running "ng build --prod -aot", the output pages continue to display conte ...

The Typescript hello world example encounters an issue with Karma

Recently, I encountered an issue while working on a TypeScript project with Jasmine and Karma. It seems that Karma is unable to execute the compiled unit tests due to an error showing up in Chrome: Uncaught ReferenceError: define is not defined To illust ...

What is the best way to launch the Playwright browser in Jest using the setupFilesAfterEnv hook, to ensure accessibility within the test file while incorporating TypeScript?

When using Jest and Playwright, I encountered an issue where I wanted to launch the browser from setupFilesAfterEnv in order to avoid repeating the process in every test file. Despite successfully launching the browser and having global variables accessibl ...

React-Native 0.1.17 Navigator Bar: Enhancing User Navigation Experience

An issue arose after upgrading my react-native 0.1.15 app to version 0.1.17 - I'm now encountering an 'Unable to download JS bundle error'. Upon investigation, I found the error in my code: var SportsSocial = React.createClass({ component ...

Getting an Angular TypeError after upgrading to version 9? It seems that the property 'selectors' cannot be read from null

After upgrading my Angular app from v7 to v8 and then v8 to v9, I encountered an issue. My app works perfectly locally when I run ng serve, but when I build for production using ng build --prod and deploy the app, I get an error in the application's c ...

What steps can I take to prevent ng-bootstrap modal from automatically centering the content within the modal?

Looking for a solution to a UX issue with my Angular ng-bootstrap modal. The problem arises when displaying messages of varying lengths - if the message is longer than the screen's vertical resolution, it gets centered on the screen. This causes incon ...

Is RxJS more suitable than Redux/context for handling and accessing state in various components and handler methods?

Redux is commonly seen as an improved version of Flux, simplifying application state management. Although I have heard about reactive programming (RxJS), I have yet to explore it myself. My query is: do Redux and RxJS share any similarities or are they c ...

Ways to conceal <td>s in angularjs on specific rows during ng-repeat

In the first <tr>, I have a table with many <td> elements that I am populating using ng-repeat. <tr ng-repeat="receipt in $data"> <td data-title="voucher number"> <span>{{receipt.voucher_no}}</span> </td ...

What is the reasoning behind exporting it in this manner in the index file?

As I was going through a tutorial about nests, there was this step where the instructor made a folder named "dtos" and inside it, they created two dto files (create-user.dto and edit-user.dto). Following that, they also added an index file in the same fold ...

Mastering Cookies in Javascript

I have been exploring the world of cookies in Javascript and decided to create an experimental log-in page. The page is fully functional, but I am interested in displaying the user's username and password using cookies. Is this possible with Javascrip ...

`How can TypeScript be used to designate the type of a variable within the useState hook?`

I defined a variable called 'text' and a hook named 'setText'. I'm using them to update the value of a form input field. How can I ensure that 'text' is always of type string? This is what I attempted: interface TextInt ...