In angular 2, I try to bind a string component property to an input directive parameter. It looks like that the two way binding doesn't work with primitive property even though I use "banana in a box".
Component :
@Component({
selector: "pairs-result",
template: `
<ul class="search-list">
<li [(rowHover)]="showDetail">{{showDetail}}<pair-row></pair-row></li>
</ul>
`,
directives: [HoverDirective]
})
export class PairsComponent {
public showDetail: string = "initial value";
}
Directive :
@Directive({
selector: '[rowHover]'
})
export class HoverDirective {
@Input('rowHover') hover: any;
@HostListener('mouseenter') onMouseEnter() {
this.hover = "mouse enter";
}
@HostListener('mouseleave') onMouseLeave() {
this.hover = "mouse leave";
}
}
Code with Primitive not working
But, if I change "hover" string property to an object property, it works.
Code with Object works
In case you using object, it is not binding but rather change detection.
You need to create @Output property with type EventEmitter and name rowHoverChange, and manually emit new values.
See how binding is implemented plunkr
Using primitives:
import { Directive, HostListener, Input, EventEmitter, Output } from '@angular/core';
@Directive({
selector: '[rowHover]'
})
export class HoverDirective {
@Input('rowHover') hover: any;
@Output() rowHoverChange = new EventEmitter();
@HostListener('mouseenter') onMouseEnter() {
this.hover = "mouse enter";
this.rowHoverChange.emit(this.hover);
}
@HostListener('mouseleave') onMouseLeave() {
this.hover = "mouse leave";
this.rowHoverChange.emit(this.hover);
}
}
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