Pass input values into the directive using the @Input data binding
Create an @Input property in the directive to get the input.
highlight.directive.ts
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export class HighlightDirective { constructor(private eleRef: ElementRef) { } @Input('appHighlight') HighlightColor : string; @HostListener('mouseenter') onMouseEnter() { this.highlight(this.HighlightColor ) } @HostListener('mouseleave') onMouseLeave() { this.highlight('' ) } private highlight(color: string) { this.eleRef.nativeElement.style.backgroundColor = color } }
app.component.ts
import { Component, ViewChild, AfterViewInit } from '@angular/core'; @Component({ selector: 'app-root', template: ` <h4>Pick a color to highlight</h4> <div> <input type="radio" name="colors" (click)="color='lightgreen'">Green <input type="radio" name="colors" (click)="color='yellow'">Yellow <input type="radio" name="colors" (click)="color='cyan'">Cyan </div> <p [appHighlight] = "color" > Change my color </p> ` , styleUrls: ['./app.component.css'] }) export class AppComponent { color: string }
0 Comments