7

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>

1 Answer 1

16

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

Sign up to request clarification or add additional context in comments.

6 Comments

but I want to select a particular element from the dom say a button, How can I do that?
HostListener only listens for events on the element the directive is bound to.
i was to late to edit my previous comment so, if you want multiple elements to change on the click of a button you are probably better of using component and a variable controlling the styles of your element (or a variable toggling a class).
can we use @HostListener() from a component or is this only accessible from a directive??
yes, components extend directives, so all posibilities on directives are also possible on components, HostListener on a component will listen for events on the component element (e.g. <app-component></app-component>)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.