【发布时间】:2016-09-26 03:56:29
【问题描述】:
我在这里看到了两个问题,如何有条件地添加和删除项目的属性 (Is it possible to conditionally display element attributes using Angular2?) 但我的问题是是否可以添加和删除 attribute directives ?我可以添加和删除属性,但 Angular 不会将属性“编译”为属性指令,但属性只是坐在那里什么都不做。以下是 2 个标签的示例:
第一个是我试图有条件地应用属性指令的那个,第二个一直都有它。
这是我如何应用属性(也许有不同的方式来应用属性指令?)
<h1 [attr.colored]="check ? '': null">Testing something</h1>
这是指令:
import {Directive, ElementRef} from '@angular/core'
@Directive({
selector: '[colored]',
host: {
'(mouseenter)': 'onMouseEnter()',
'(mouseleave)': 'onMouseLeave()'
}
})
export class colorDirective {
constructor(private el: ElementRef) {
}
onMouseEnter() { this.highlight("yellow"); }
onMouseLeave() { this.highlight(null); }
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
编辑:有几个答案,但它们适用于 AngularJS (1)
【问题讨论】:
标签: javascript angular