简体   繁体   中英

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? 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('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

I named mine onClick, but you could name it clicked aswell

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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