Hussain Wali
Hussain Wali

Reputation: 203

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>

Upvotes: 7

Views: 12333

Answers (1)

Laurence Mommers
Laurence Mommers

Reputation: 705

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

Upvotes: 16

Related Questions