Skip to content

Instantly share code, notes, and snippets.

@WodenWang820118
Last active January 28, 2023 08:30
Show Gist options
  • Save WodenWang820118/e83ff25eef8627333161875a10ffa557 to your computer and use it in GitHub Desktop.
Save WodenWang820118/e83ff25eef8627333161875a10ffa557 to your computer and use it in GitHub Desktop.
// 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment