繁体   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