Make @Hostbinding and @Hostlistener Conditional in a Directive or Component for Angular2

I have a directive that accepts an event:

<td calendarEvent [event]=event><td>

Inside the directive, I have HostBindings for adding classes based on the event and HostListeners for listening for mouseenter and mouseleave events. For example:

@HostBinding('class.all-day') get eventIsAllDay() {
  if (this.event) return this.event.is_all_day;
}

A number of <td>s will have undefined for the [event] input. Is there a way for HostBinding and HostListener to be added based upon a condition? On every change detection, it has to run all the bindings and listeners for every single <td> tag, even those that don't have events. Perhaps the computing power needed is negligible, but every little bit helps I'm sure, especially with mobile devices.

1 Answer

There is no way to add those conditionally.

You can use a property and bind to the property instead. Change detection with properties is more efficient than with functions or getters.

@HostBinding('class.all-day') 
eventIsAllDay:boolean = false;

set event(val) {
  this.event.is_all_day === val;
}
5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest