Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 502
Hussain Wali Avatar asked Dec 08 '22 16:12

Hussain Wali


1 Answers

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

like image 184
Laurence Mommers Avatar answered Dec 10 '22 06:12

Laurence Mommers