在angular2中,如何用双向绑定编写自定义指令,我不想使用naModel进行数据绑定。
目前,我想实现一个函数,当鼠标进入或离开div时,该指令也会修改绑定对象。以下是我的代码:
指令:
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;
}
组件:
<ul class="search-list">
<li [(rowHover)]="showDetail">{{showDetail}}<pair-row></pair-row></li>
</ul>
HTML
#div1, #div2, #div3, #div4, #div5 {
width: 300px;
height: 300px
}
#div1 {
background: yellow;
}
#div2 {
background: orange;
padding: 50px;
}
#div3 {
background: red;
padding: 100px;
}
#div4 {
background: purple;
padding: 150px;
}
我想在鼠标进入或离开li标签时更改showDetail的值。
非常感谢!
答案 0 :(得分:0)
您可以将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
}
}