Reputation: 3978
I want to add an attribute to a button like below
<button type="button" eventlistener (click)="toggleButton()">Toggle</button>
I want to add some more logic at the global level for click event, is there anyway that whenever I add a button or any element by adding simple attribute I should be able to listen to them. I got this doubt after watching the code in angular 2 material as below:
<button md-button>Click me!</button>
Using md-button attribute they have added few styles to the button. In the same way I want to add my custom functionality for my custom attribute. Please suggest.
Upvotes: 0
Views: 1806
Reputation: 2359
Create a directive for this. Check directive to change background color on hover of mouse.
Directive class
import { Directive,ElementRef, Renderer2, OnInit, HostListener, HostBinding,
Input } from '@angular/core';
@Directive({
selector: '[appBetterHighlight]'
})
export class BetterHighlightDirective implements OnInit {
@Input() defaultColor: string = 'transparent';
@Input() highlightColor: string = 'yellow';
@HostBinding('style.backgroundColor') backgroudColor: string;
constructor(private elmentRef: ElementRef, private renderer: Renderer2) { }
ngOnInit() {
this.backgroudColor = this.defaultColor;
}
@HostListener('mouseenter') onmouseover(eventData: Event) {
//this.renderer.setStyle(this.elmentRef.nativeElement, 'background-color', 'red');
this.backgroudColor = this.highlightColor;
}
@HostListener('mouseleave') onmouseleave(eventData: Event) {
//this.renderer.setStyle(this.elmentRef.nativeElement, 'background-color', 'transparent');
this.backgroudColor = this.defaultColor;
}
}
Template
<p appBetterHighlight [defaultColor] = "'green'" [highlightColor] = "'yellow'" >Highlight better paragraph</p>
Upvotes: 1
Reputation: 6824
@Directive({
selector: '[eventlistener]'
})
export class EventListener {
@HostListener('click')
onClick() {
alert('You clicked me');
}
}
Then just add eventlistener
to anything, and click on it, you will see the alert.
Also, add this directive's class to the declarations
array in your root module
Note everything is imported from @angular/core
Upvotes: 1