简体   繁体   English

在Angular 2中动态隐藏/显示工具提示

[英]Dynamically hide / show tooltip in Angular 2

I have some elements inside ngFor loop. 我在ngFor循环中有一些元素。 Some of them have tooltips while others don't. 其中一些有工具提示,而另一些则没有。 When I use the following code like this: 当我使用以下代码时:

<div ngFor="let item of items">
    <div [title]="item.title">

items that don't have tooltips will show undefined . 没有工具提示的项目将显示undefined Is there a way to hide it if the item doesn't have one while other items' tooltips still get to show? 有没有办法隐藏它,如果项目没有一个,而其他项目的工具提示仍然显示?

Use the || 使用|| operator to set the default value as an empty string if item.title is not defined. 如果item.title则运算符将默认值设置为空字符串。 This will prevent the tooltip from being displayed. 这将阻止显示工具提示。 An example is shown in this stackblitz . 这个stackblitz显示了一个例子。

<div [title]="item.title || ''"> Some content </div>

I thought I would just add another couple approachs, in case you weren't aware, you can also do this: 我想我会添加另外几种方法,如果你不知道,你也可以这样做:

<div [title]="getTitle()"> Some content </div>

Then in your typescript: 然后在你的打字稿中:

public getTitle(): string{
   return item.title || '';
}

Alternatively to this, you could take advantage of typescript getter/setters : 除此之外,您还可以利用typescript getter / setter

export class Item{
  private _title:string;
  get title():string {
      return this._title || '';
  }
  set title(value:string) {
      this._title = value;
  }
}

This way, title will never return null or undefined . 这样,title将永远不会返回nullundefined

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM