I created a custom directive in angular , and I want to share a value between my directive and my typescript file, this is an example of my 2 files:
<!-- Mi html -->
<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">Highlight me!</p>
<p *ngIf="color">True</p>
<p [appHighlight]="color" defaultColor="violet">
Highlight me too!
</p>
<!-- mi typescript -->
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
color: boolean;
}
<!-- mi directiva custom -->
/* tslint:disable:member-ordering */
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {}
@Input() color: boolean;
@Input() defaultColor: boolean;
@Input('appHighlight') highlightColor: string;
@HostListener('mouseenter')
onMouseEnter() {
console.log(this.color);
}
@HostListener('mouseleave')
onMouseLeave() {
this.highlight(null);
}
private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
By changing the Boolean value to true
or false
, my% ngIf
evaluates it and shows me the <p *ngIf="color">True</p>
properly.
But when changing the value in my directive *ngIf
does not evaluate it, how can I communicate the value of my directive with my .ts
?