Search code examples
angular6popover

Hide popover if value is undefined in Angular 6


I am using ngx-popover for tooltip in Angular 6. Everything is working fine but if am getting empty value then also its showing empty popver

My code is :

<div class="vertical sub-child active{{item._id}}" [ngClass]="{'shortlen': item.category.length>36 }" 
                        popover="{{item.description}}"
                            popoverPlacement="right"
                            [popoverOnHover]="true"
                            [popoverCloseOnClickOutside]="true"
                            [popoverCloseOnMouseOutside]="true"
                            [popoverDisabled]="false"
                            [popoverAnimation]="true"> {{item.category}} </div>

{{item.description}} is empty sometimes at that time my tooltip have to disappear


Solution

  • When item.description is undefined, or an empty string, it's falsy, so you can use the existence of a value to determine the [popoverDisabled] attribute. To be doubly sure, you can use the bang, bang boolean approach (!!) along with it, although it shouldn't strictly be required.

    <div class="vertical sub-child active{{item._id}}" [ngClass]="{'shortlen': item.category.length>36 }" 
                        popover="{{item.description}}"
                            popoverPlacement="right"
                            [popoverOnHover]="true"
                            [popoverCloseOnClickOutside]="true"
                            [popoverCloseOnMouseOutside]="true"
                            [popoverDisabled]="!!item.description"
                            [popoverAnimation]="true"> {{item.category}} </div>
    

    Alternatively, if there are other keys in item that may be empty, and require the popover hidden, use a function in your component instead;

    <div class="vertical sub-child active{{item._id}}" [ngClass]="{'shortlen': item.category.length>36 }" 
            popover="{{item.description}}"
            popoverPlacement="right"
            [popoverOnHover]="true"
            [popoverCloseOnClickOutside]="true"
            [popoverCloseOnMouseOutside]="true"
            [popoverDisabled]="hasRequiredValues(item)"
            [popoverAnimation]="true"> {{item.category}} </div>
    

    In your component;

    /**
     * Do all your data tests here, and return the result
     */
    hasRequiredValues(item: Item) {
       return !!item.description && !!item.category;
    }