Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 440
Lee Avatar asked Nov 23 '16 15:11

Lee


People also ask

What are HostBinding () and HostListener () in Angular?

@HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives. @HostBinding lets you set properties on the element or component that hosts the directive, and @HostListener lets you listen for events on the host element or component.

Can we use HostListener in component?

@HostListener is Angular's decorator method that's used for listening to DOM events on the host element of both component and attribute directives.

What is the difference between a component and a directive?

The Component is used to break up the application into smaller components. That is why components are widely used in later versions of Angular to make things easy and build a total component-based model. The Directive is used to design reusable components, which are more behavior-oriented.

What is the HostBinding decorator doing in this directive?

HostBindinglink Decorator that marks a DOM property as a host-binding property and supplies configuration metadata. Angular automatically checks host property bindings during change detection, and if a binding changes it updates the host element of the directive.


1 Answers

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;
}
like image 100
Günter Zöchbauer Avatar answered Oct 13 '22 02:10

Günter Zöchbauer