1

I have some elements inside ngFor loop. 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. Is there a way to hide it if the item doesn't have one while other items' tooltips still get to show?

Viv
  • 913
  • 1
  • 7
  • 18

2 Answers2

2

Use the || operator to set the default value as an empty string if item.title is not defined. This will prevent the tooltip from being displayed. An example is shown in this stackblitz.

<div [title]="item.title || ''"> Some content </div>
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
1

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:

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.

Zze
  • 18,229
  • 13
  • 85
  • 118