簡體   English   中英

在角度為4的自定義指令中實現onclick()

[英]implement onclick() in custom directive angular 4

我有一個簡單的按鈕和一個指令,我想訪問該按鈕的樣式,在指令中使用onclick()函數添加MarginLeft,該指令不起作用,但是從構造函數設置css時,如何在單擊時使用它呢? 請幫忙:

指令:

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

這是模板:

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

您可以在指令中使用HostListener:

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

這樣,您還可以從按鈕上遠程(click)="clicked()"

我將其命名為我的onClick,但您也可以將其命名為clicked

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM