【发布时间】:2017-07-26 12:41:50
【问题描述】:
如何在自定义属性指令中使用 NgClass 来更改主要元素 CSS 类?
如果我有这样的事情:
@Component({
selector: 'my-app',
template: `
<div>
<div class="box" myDir [ngClass]="{'blue': blue, 'red': red}"> </div>
</div>
`,
});
然后,在 myDir 指令中,类似这样的内容:
import { Directive, HostListener, OnInit } from '@angular/core';
@Directive({
selector: '[myDir]'
})
export class MyDirDirective {
blue: boolean;
red: boolean;
constructor() {
}
ngOnInit() {
}
@HostListener('mouseenter', ['$event'])
onMouseEnter(event) {
event.preventDefault();
event.stopPropagation();
this.blue = true;
this.red = false;
console.log('mouseenter');
}
@HostListener('mouseleave', ['$event'])
onMouseLeave(event) {
event.preventDefault();
event.stopPropagation();
this.blue = true;
this.red = false;
console.log('mouseleave');
}
我无法访问蓝色和红色所在的范围吗?如果我创建一个切换,我可以用一个按钮更新这些值,但似乎我不能从指令本身中做到这一点。这是一个准确的观察结果吗?我应该这样做吗?还是有我在文档中没有看到的替代方法?
【问题讨论】:
标签: angular typescript scope angular-directive