2017-10-19 59 views
0

我有一個簡單的按鈕和一個指令我想要訪問按鈕的樣式,在指令中添加一個onclick()函數的MarginLeft它不工作,但從構造函數設置css如何通過點擊來使用它?請幫助:在自定義指令中實現onclick()angular 4

指令:

import { Directive, ElementRef } from '@angular/core'; 

@Directive({ 
    selector: '[Bluecolored]' 
}) 
export class BluecoloredDirective { 

    constructor(private element:ElementRef) { 
    console.log(element); 
    element.nativeElement.style.color="blue"; 
    } 
clicked(){ 
    this.element.nativeElement.style.marginLeft=20; 
    console.log("marzi"+this.element.nativeElement.style.marginLeft); 
} 
} 

這是模板:

@HostListener('onClick') onClick(){ 
    this.element.nativeElement.style.marginLeft=20; 
    console.log("marzi"+this.element.nativeElement.style.marginLeft); 
} 

這樣你就可以遠程:

<p Bluecolored> 
    new-fom works! 
</p> 
<h1 Bluecolored>Blue Colored</h1> 
<button (click)="clicked()" Bluecolored>Click</button> 

回答

0

你可以在你的指令使用HostListener (click)="clicked()" from the button aswell

我命名我的onClick,但你可以命名它點擊以及

+0

但我想從DOM中選擇一個特定的元素說一個按鈕,我該怎麼做? – user3368703

+0

HostListener只偵聽指令綁定到的元素上的事件。 –

+0

我遲到編輯我以前的評論,所以, 如果你想多個元素改變點擊一個按鈕,你可能更好地使用組件和一個變量控制你的元素的風格(或變量切換一個類) 。 –

相關問題