如何在Angular 2中的元素上设置属性? [英] How to set attributes on an element in Angular 2?
本文介绍了如何在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()
.
这篇关于如何在Angular 2中的元素上设置属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文