简体   繁体   English

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

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

I have a simple button and a directive I want to access the button's style, add MarginLeft with an onclick() function in the directive it is not working but setting the css from constructor works how can I use this with on click? 我有一个简单的按钮和一个指令,我想访问该按钮的样式,在指令中使用onclick()函数添加MarginLeft,该指令不起作用,但是从构造函数设置css时,如何在单击时使用它呢? please help: 请帮忙:

the directive: 指令:

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

this is the template: 这是模板:

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

You could use a HostListener in your directive: 您可以在指令中使用HostListener:

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

this way you can remote (click)="clicked()" from the button aswell 这样,您还可以从按钮上远程(click)="clicked()"

I named mine onClick, but you could name it clicked aswell 我将其命名为我的onClick,但您也可以将其命名为clicked

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM