Creé una directiva custom en angular, y quiero compartir un valor entre mi directiva y mi archivo typescript, este es un ejemplo de mis 2 archivos:
<!-- 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;
}
}
Al cambiar el valor booleano a true
o false
, mi *ngIf
lo evalúa y me muestra el <p *ngIf="color">True</p>
debidamente.
Pero al cambiar el valor en mi directiva *ngIf
no lo evalúa, cómo puedo comunicar el valor de mi directiva con mi .ts
?