Guest User

Untitled

a guest
Mar 18th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. /*
  2. @HostBinding and @HostListener are two decorators in Angular that can be really useful in custom directives.
  3. @HostBinding lets you set properties on the element or component that hosts the directive, and
  4. @HostListener lets you listen for events on the host element or component.
  5. */
  6.  
  7. // example directive that listen’s for a keydown event on the host and sets its text and border color
  8. // to a random color from a set of a few available colors:
  9.  
  10. import {Directive,HostBinding,HostListener } from '@angular/core';
  11.  
  12. @Directive({
  13. selector: '[appRainbow]'
  14. })
  15. export class RainbowDirective {
  16. possibleColors = [
  17. 'darksalmon', 'hotpink', 'lightskyblue', 'goldenrod', 'peachpuff',
  18. 'mediumspringgreen', 'cornflowerblue', 'blanchedalmond', 'lightslategrey'
  19. ];
  20.  
  21. @HostBinding('style.color') color: string;
  22. @HostBinding('style.border-color') borderColor: string;
  23.  
  24. @HostListener('keydown') newColor() {
  25. const colorPick = Math.floor(Math.random() * this.possibleColors.length);
  26.  
  27. this.color = this.borderColor = this.possibleColors[colorPick];
  28. }
  29. }
  30.  
  31. // And the directive can be used on elements like this:
  32. // <input type="text" appRainbow>
  33.  
  34.  
  35. // Our Rainbow directive uses two @HostBinding decorators to define two class members,
  36. // one that’s attached to the host’s style.color binding and the other to style.border-color.
  37.  
  38. // The @HostListner with the 'keydown' argument listens for the keydown event on the host.
  39. // We define a function attached to this decorator that changes the value of color and borderColor,
  40. // and our changes get reflected on the host automatically.
Add Comment
Please, Sign In to add comment