如何在Angular 2中的元素上设置属性?
问题描述:
我有一个简单的Directive
,如下所示:
I have a simple Directive
as follows:
import { Directive, OnInit, OnDestroy, ElementRef } from "@angular/core";
@Directive({
selector: "[Checker]"
})
export class Checker {
constructor(private e: ElementRef) {
}
OnInit() {
this.e.nativeElement.setAttribute("spellcheck", "true");
}
keyFunc(event: KeyboardEvent) {
if (event.keyCode == 74) {
//more functionality
}
}
}
因此,每当我将此指令选择器添加到任何标签时,我都会将spellcheck
属性设置为true
.
So, whenever I add this directive selector to any tag, I set the spellcheck
attribute to true
.
如何以Angular2方式设置此属性,即替代Angular的方法是什么?
How can I set this attribute in an Angular2 way, i.e. what is the alternative Angular way to do this?
答
您可以简单地在@Directive
中声明host
属性,如下所示:
You can simply declare the host
property in the @Directive
as follows:
@Directive({
selector: "[Checker]",
host: { "spellcheck":"true" }
})
显然,您可以删除在ngOnInit()
中使用的setAttribute()
.
And obviously you can remove the setAttribute()
which you are using in the ngOnInit()
.