I was wondering if there was a drastic difference (and if there is, what is it?) between using @HostBinding
and the host
attribute of the component ?
I have been asking myself that question while I was using animations because I was in these cases (which look rather close) :
@Component({
selector: 'mycomponent',
animations: [
trigger('myTransition', [
state('inactive', style({
backgroundColor: '#eee',
transform: 'scale(1)'
})),
state('active', style({
backgroundColor: '#cfd8dc',
transform: 'scale(1.1)'
})),
transition('inactive => active', animate('100ms ease-in')),
transition('active => inactive', animate('100ms ease-out'))
])],
host: {
'[@myTransition]': '',
},
})
OR
@Component({
selector: 'mycomponent',
animations: [
trigger('myTransition', [
state('inactive', style({
backgroundColor: '#eee',
transform: 'scale(1)'
})),
state('active', style({
backgroundColor: '#cfd8dc',
transform: 'scale(1.1)'
})),
transition('inactive => active', animate('100ms ease-in')),
transition('active => inactive', animate('100ms ease-out'))
])],
})
export class MyComponent {
@HostBinding('@myTransition') get myTransition() {
return '';
}
}
I then thought that it my might be the new way of host binding.
Thanks in advance for your advice and input ;)
The official guidance is to prefer HostListener/HostBinding
from the Angular style guide
HostListener/HostBinding decorators versus host metadata
Style 06-03 Consider preferring the @HostListener and @HostBinding to the host property of the @Directive and @Component decorators.
Do be consistent in your choice.
Why? The property associated with @HostBinding or the method associated with @HostListener can be modified only in a single place—in the directive's class. If you use the host metadata property, you must modify both the property declaration inside the controller, and the metadata associated with the directive.
However, the angular/material2 project says to prefer "host"
Host bindings
Prefer using the host object in the directive configuration instead of @HostBinding and @HostListener. We do this because TypeScript preserves the type information of methods with decorators, and when one of the arguments for the method is a native Event type, this preserved type information can lead to runtime errors in non-browser environments (e.g., server-side pre-rendering).