在角度为4的自定义指令中实现onclick()

use*_*703 2 javascript css typescript angularjs-directive angular

我有一个简单的按钮和一个指令,我想访问该按钮的样式,在指令中使用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);
}
}
Run Code Online (Sandbox Code Playgroud)

这是模板:

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

Lau*_*ers 5

您可以在指令中使用HostListener:

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

这样你也可以远离(click)="clicked()"按钮

我将其命名为我的onClick,但您也可以将其命名为clicked