(Angular 2 RC4)
With @HostBinding
we should be able to modify properties of the host, right? My question is, does this apply to @Input()
properties as well and if so, what is the correct usage? If not, is there another way to achieve this?
I made a Plunker here to illustrate my problem: https://embed.plnkr.co/kQEKbT/
Suppose I have a custom component:
@Component({ selector: 'custom-img', template: ` <img src="{{src}}"> ` }) export class CustomImgComponent { @Input() src: string; }
And I want to feed the src
property with an attribute directive:
@Directive({ selector: '[srcKey]' }) export class SrcKeyDirective implements OnChanges { @Input() srcKey: string; @HostBinding() src; ngOnChanges() { this.src = `https://www.google.com.mt/images/branding/googlelogo/2x/${this.srcKey}_color_272x92dp.png`; } }
Why can't this directive change the [src]
input property of the custom component?
@Component({ selector: 'my-app', directives: [CustomImgComponent, SrcKeyDirective], template: `<custom-img [srcKey]="imageKey"></custom-img>` }) export class AppComponent { imageKey = "googlelogo"; }
Thanks!
@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. In this article, you will use @HostBinding and @HostListener in an example directive that listens for a keydown event on the host.
HostBinding - Declares a host property binding. Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive. @HostBinding - will bind the property to the host element, If a binding changes, HostBinding will update the host element.
HostListener Example We use the HostListner decorator to decorate functions onMouseOver & onMouseLeave . We apply the directive on a host element ( p in the example) as shown below. Whenever the mouse is moved over the p element, the mouseover event is captured by the HostListener.
HostListenerlinkDecorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.
You need to combine the decorators like this:
@HostBinding('class.active') @Input() active: boolean = false;
If your @Input
is an object, you can do:
@Input() settings: Settings; @HostBinding('class.active') public get isActive(): boolean { return this.settings.isActive; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With