【问题标题】:Two way binding not working on primitive object with angular 2两种方式绑定不适用于角度为 2 的原始对象
【发布时间】:2017-06-13 01:29:06
【问题描述】:

在 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

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

Code with Object works

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

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

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

    看看绑定是如何实现的plunkr

    【讨论】:

    • 实际上,在我的项目中,我使用 EventEmitter,但我忘记在我的 rowHover eventEmitter 属性后添加“更改”字样。现在它正在工作。
    【解决方案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);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      相关资源
      最近更新 更多