简体   繁体   English

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

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

In angular2, how to write custom directive with two way binding, and I don't want to use naModel for data binding. 在angular2中,如何通过两种方式编写自定义指令,并且我不想将naModel用于数据绑定。

Currently, I want to implement a function that when mouse enter or leave a div, the directive will also modify the binding object. 当前,我想实现一个函数,当鼠标进入或离开div时,该指令还将修改绑定对象。 And the following is my code: 以下是我的代码:

Directive: 指示:

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

Component: 零件:

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 的HTML

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

And I want to change the value of showDetail when mouse enter or leave the li tag. 我想在鼠标进入或离开li标签时更改showDetail的值。

Many thanks! 非常感谢!

You can make the showDetail an object instead of a boolean , and then change that object's property. 您可以将showDetail为对象而不是boolean ,然后更改该对象的属性。 Notice you don't even need to mark the attribute as output (the () 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: 指示:

@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
  }
}

Check demo plunker here . 在此处检查演示插件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM