0
如何在自定义属性指令中使用NgClass来更改主要元素CSS类?Angular 2.4.0目标NgClass属性指令的内部
如果我有这样的事情:
@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');
}
难道我没有访问范围中,蓝色和红色居住在?如果我创建一个切换,我可以用一个按钮来更新这些值,但似乎并不能从指令本身中完成。这是一个准确的观察,我应该这样做,还是有一种替代方案,我没有在文档中看到?
感谢您的初始,然后更新的答案!您的初始响应实际上让我回到了我认识到我的错误的文档,并且比上面的文章稍微深入一点,使用.emit()将它们彼此解耦。 – katyusha
很高兴帮助您,您可以接受答案,干杯! –