双向绑定不使用角度为2的原始对象

时间:2017-01-27 11:16:57

标签: angular angular2-directives

在angular 2中,我尝试将字符串组件属性绑定到输入指令参数。 看起来双向绑定对于原始属性不起作用,即使我使用“盒子里的香蕉”。

组件:

@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

2 个答案:

答案 0 :(得分:4)

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

您需要创建类型为@Output且名称为EventEmitter的{​​{1}}属性,并手动发出新值。

了解如何实施绑定June 2013

答案 1 :(得分:2)

使用原语:

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