// ng g directive directives/highlighted
// the directive separates CSS implementation out of component and
// allow complex CSS as an independent concern
// [highlighted.directive.ts]
import {
Directive,
EventEmitter,
HostBinding,
HostListener,
Input,
} from "@angular/core";
@Directive({
selector: "[highlighted]",
exportAs: "hl",
})
export class HighlightedDirective {
@Input("highlighted") isHighlighted: boolean = false;
toggleHighlight = new EventEmitter<boolean>(); // custom event
constructor() {}
// angular directives
// the HostBinding can bind any DOM property to the host element
@HostBinding("class.highlighted")
get cssClasses() {
// if @HostBinding('style.border')
// then can return '1px solid red'
return this.isHighlighted;
}
// the HostListener can listen to any DOM events or custom events
@HostListener("mouseover", ["$event"])
mouseOver($event) {
console.log($event);
this.isHighlighted = true;
this.toggleHighlight.emit(this.isHighlighted);
}
@HostListener("mouseleave")
mouseLeave() {
this.isHighlighted = false;
this.toggleHighlight.emit(this.isHighlighted);
}
// publid method to toggle the highlighted state
toggle() {
this.isHighlighted = !this.isHighlighted;
this.toggleHighlight.emit(this.isHighlighted);
}
}
// [app.component.html]
<div class="courses" *ngIf="courses[0] as course">
<!-- can refer exporeted directive that the public methods can be called -->
<course-card
highlighted
#highlighter="hl"
(toggleHighlight)="onToggleHighlight($event)"
(courseSelected)="onCourseSelected($event)"
[course]="course"
>
<course-image [src]="course.iconUrl"></course-image>
<!-- can use the highlighter directive here or in the component.ts -->
<div class="course-description" (click)="highlighter.toggle()">
{{ course.longDescription }}
</div>
</course-card>
</div>