Using String Interpolation to Pull Value from an Array in Angular2 App

3k views Asked by At

In my Angular2 app I am looping through a list of users, and for each user in the list, I am populating an icon to the view to represent that person. With that working, I'd like to now use material2's tooltip (mdTooltip) to show the name when someone scrolls over the icon. I can get the tooltip working when I connect it to a singular property in my component via string interpolation, like for "name: 'John Smith'" I can just use "{{name}}" in my component HTML. But when I try and pull the name out of an array from that same component, it doesn't work.

This is what my component looks like:

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() {
  }

}

And here's the version of my component HTML that works:

<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>

But when I try string interpolation to pull a value out of an array and use it in the tooltip, it doesn't work:

<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>
2

There are 2 answers

0
Alexey Soshin On BEST ANSWER

In your case others is an array, so it doesn't have a "name" property. By you already iterate over it, and put each value into "other".
So this will work:

mdTooltip="{{other.name}}"
0
Lockless On

I think you are using the array and not the instance var

{{others.name}}

should be

{{other.name}}