user1188867
user1188867

Reputation: 3978

How to add attribute to button and access it at the global level in angular 2

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

Answers (2)

ranjeet8082
ranjeet8082

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

Trash Can
Trash Can

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

Related Questions