如何在 Angular2 中使用没有 ngModel 的双向绑定编写自定义指令

how to write custom directive with two way binding without ngModel in Angular2

在 angular2 中,如何使用双向绑定编写自定义指令,我不想使用 naModel 进行数据绑定。

目前,我想实现一个功能,当鼠标进入或离开div时,指令也会修改绑定对象。以下是我的代码:

指令:

import { Directive, HostListener, Input } from '@angular/core';
@Directive({
  selector: '[rowHover]'
})
export class HoverDirective {

  @Input('rowHover') hover: boolean;
  @HostListener('mouseenter') onMouseEnter() {
    this.hover = true;
  }
  @HostListener('mouseleave') onMouseLeave() {
    this.hover = false;
  }
}

组件:

import {Component} from "@angular/core";
import {PairRowComponent} from './pair-row.component';
import {HoverDirective} from '../directives/pair-hover.directive';

@Component({
  selector: "pairs-result",
  templateUrl: "./app/pairs/components/pairs.html",
  directives: [PairRowComponent, HoverDirective]
})
export class PairsComponent {
  public showDetail: boolean = false;
}

HTML

<ul class="search-list">
    <li [(rowHover)]="showDetail">{{showDetail}}<pair-row></pair-row></li>
  </ul>

并且我想在鼠标进入或离开 li 标签时更改 showDetail 的值。

非常感谢!

您可以将 showDetail 设为对象而不是 boolean,然后更改该对象的 属性。请注意,您甚至不需要将属性标记为输出(()s):

@Component({
  selector: "pairs-result",
  template: `
  <ul class="search-list">
    <li [rowHover]="showDetail">{{showDetail.value}}<pair-row></pair-row></li>
  </ul>
  `,  // ^^^^^^^^-- no need of (rowHover)   ^^^^^^^^--- .value added here as well
  directives: [HoverDirective]
})
export class PairsComponent {
  public showDetail: any = {value: false};   // property is now an object instead of a bool
}

指令:

@Directive({
  selector: '[rowHover]'
})
export class HoverDirective {
  @Input('rowHover') hover: any;
  @HostListener('mouseenter') onMouseEnter() {
    this.hover.value = true;                       // <-- notice the .value here
  }
  @HostListener('mouseleave') onMouseLeave() {
    this.hover.value = false;                       // <-- notice the .value here
  }
}

检查demo plunker here