2017-02-15 98 views
3

我有一個簡單的指令,如下所示:如何設置屬性的元素Angular2

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 
     } 
    } 

} 

所以,每當我這個指令選擇添加到任何標記,我設置了「拼寫檢查」屬性設置爲true。

如何以Angular2方式設置此屬性?即,做這件事的另一種角度方式是什麼。

謝謝。

回答

2

你可以簡單地在@Directive聲明主機屬性如下:

@Directive({ 
    selector: "[Checker]", 
    host: { "spellcheck":"true" } 
}) 

而且很明顯,你可以刪除它使用的是在OnInit(中的setAttribute())

希望它有幫助。

+2

它實際上需要是「」attr.spellcheck「:」true「',它只是'@HostBinding()'的替代語法。你可以用Angular裝飾器做的所有事情都可以用'host:'完成,'@Input()','@Output()','@ViewChild()','@HostListener()',... 。 –

+0

@GünterZöchbauer我實際上沒有使用attr,而且它也在工作。我不確定哪個是正確的。雖然我沒有用attr.spellcheck試試。 – ShellZero

+0

如果綁定到組件輸入或DOM元素屬性,則不需要'attr.',否則需要'attr.'。 –

2

'Angular 2'的方法是使用Renderer

this.renderer.setElementAttribute(e.nativeElement, "spellcheck", "true");

編輯:

正如彼得斯在下面的評論指出,renderer已被棄用,取而代之的renderer2,因此新的命令是:

this.renderer2.setAttribute(e.nativeElement, "spellcheck","true")

+0

我可以使用@HostBinding()嗎? – zelda

+0

尚未嘗試此操作,但鏈接被破壞如此:https://angular.io/api/core/Renderer#setElementProperty – theSiberman

+0

謝謝,@theSiberman。我更新了答案以使用您的新鏈接。 – Adam

3

您可以使用@HostBinding lik Ë

export class Checker { 

    @HostBinding('attr.spellcheck') 
    spellcheck:boolean = true;