Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two way binding not working on primitive object with angular 2

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

like image 398
Nicolas Law-Dune Avatar asked May 07 '26 14:05

Nicolas Law-Dune


2 Answers

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

like image 80
kemsky Avatar answered May 09 '26 04:05

kemsky


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);
  }
}
like image 22
Fabrizio Caldarelli Avatar answered May 09 '26 05:05

Fabrizio Caldarelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!