两种方式绑定不适用于 angular 2 的原始对象

Two way binding not working on primitive object with angular 2

在 angular 2 中,我尝试将字符串组件 属性 绑定到输入指令参数。 尽管我使用 "banana in a box".

,但看起来双向绑定不适用于原始 属性

组件:

@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({
  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

但是,如果我将 "hover" 字符串 属性 更改为对象 属性,它就可以工作。

Code with Object works

如果您使用对象,它不是绑定而是更改检测。

您需要使用类型 EventEmitter 和名称 rowHoverChange 创建 @Output 属性,并手动发出新值。

查看绑定是如何实现的plunkr

使用原语:

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);
  }
}