Building a task tooltip custom directive

So far, we have built a highlight directive as well as an error displaying directive. We've learned how to deal with events as well as multiple inputs. 

A short word on tooltip. A tooltip appears when we hover over an element. What you normally do to achieve that is to set the title property on the element like so:

<div title="a tooltip"></div>

There are several approaches to build tooltips generally over such a component. One way is to bind to the title property like so:

<task-icons [title]="task.name"></task-icons>

However, if you have more logic in mind it might not be so nice to add all that in the markup, so at this point, we can create a directive to hide away the tooltip bit like so:

@Directive({ selector : '[task]' })
export class TooltipDirective {
private nativeElement;
@Input() task:Task;
@Input() defaultTooltip: string;

constructor(private elementRef: ElementRef, private renderer : Renderer2) {
this.nativeElement = elementRef.nativeElement;
}

@HostListener('mouseover')
onMouseOver() {
let tooltip = this.task ? this.task.name : this.defaultTooltip;
this.renderer.setProperty( this.nativeElement, 'title', tooltip );
}
}

And using it would be:

<div [task]="task">

However, there is another approach we can take to this. What if we wanted to alter the innerText of another element while hovering over an element? That's quite easy to do, we just need to feed our directive the other element and update its innerText property like so:

<div [task]="task" [elem]="otherElement" defaultTooltip="default text" >
<div #otherElement>

This of course means we need to update our directive a little bit to this:

@Directive({ selector : '[task]' })
export class TooltipDirective {
private nativeElement;
@Input() task:Task;
@Input() defaultTooltip: string;

constructor(private elementRef: ElementRef, private renderer : Renderer2) {
this.nativeElement = elementRef.nativeElement;
}

@HostListener('mouseover')
onMouseOver() {
let tooltip = this.task ? this.task.name : this.defaultTooltip;
this.renderer.setProperty( this.nativeElement, 'innerText', tooltip );
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset