如何有条件地添加元素属性,例如checked复选框?
以前版本的Angular已经NgAttr和我认为NgChecked哪些似乎都提供了我所追求的功能.但是,Angular 2中似乎不存在这些属性,我看不到提供此功能的其他方法.
我在这里看到两个问题如何有条件地添加和删除项目上的属性(是否可以使用Angular2有条件地显示元素属性?)但我的问题是,是否可以添加和删除属性指令?我能够添加和删除属性,但Angular不会将该属性"编译"为属性指令,但该属性只是在那里无所事事.以下是2个标签的示例:
第一个是我试图有条件地应用属性指令而第二个有所有时间.
以下是我应用属性的方法(可能有不同的方法来应用属性指令?)
<h1 [attr.colored]="check ? '': null">Testing something</h1>
Run Code Online (Sandbox Code Playgroud)
这是指令:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:有几个答案,但它们适用于AngularJS(1)