javascript - 在 Angular2 应用程序中使用字符串插值从数组中提取值

标签 javascript arrays angular typescript string-interpolation

在我的 Angular2 应用程序中,我循环访问用户列表,对于列表中的每个用户,我在 View 中填充一个图标来代表该人。完成此工作后,我现在想使用material2的工具提示(mdTooltip)在有人滚动图标时显示名称。当我通过字符串插值将工具提示连接到组件中的单个属性时,我可以使工具提示正常工作,例如“name:'John Smith'”,我可以在组件 HTML 中使用“{{name}}”。但是,当我尝试从同一组件的数组中提取名称时,它不起作用。

这就是我的组件的样子:

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

}

这是我的组件 HTML 的有效版本:

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

但是当我尝试字符串插值从数组中提取一个值并在工具提示中使用它时,它不起作用:

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

最佳答案

在您的情况下,others 是一个数组,因此它没有“name”属性。您已经对其进行了迭代,并将每个值放入“其他”中。
所以这会起作用:

mdTooltip="{{other.name}}"

关于javascript - 在 Angular2 应用程序中使用字符串插值从数组中提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41513754/

相关文章:

javascript - 阻止嵌入式 iframe 重定向

JavaScript 按值复制数组

javascript - Angular 4 模板中的 bool 值

javascript - 通过单击外部关闭下拉菜单(Angular 4)

javascript - 为什么这个 for 循环记录 "undefined"?

Javascript Date 使用 UTC 时间来校正 GMT 时间

javascript - 为什么我的数组在方法调用 live 时更新但在单元测试中不更新?

php - 数组值字符串编辑和循环与其他数组和循环相结合

javascript - 类似于 JavaScript 对象的合并/连接方法.. 不扩展

angular - 使用 @angular/google-maps 将自定义样式添加到 Angular map