如何使 Angular 属性指令一次仅应用于一个 DOM 元素

How to make Angular attribute Directive applied to only one DOM element at a time

I do have the following Angular attribute directive which toggles the css class .highlighted to its host upon click event.

import { Directive, HostBinding, Input, HostListener } from '@angular/core';

@Directive({
  selector: '[highlighted]'
})
export class HighlightedDirective {

  @Input('highlighted') isHighlighted = false;

  constructor() {
  }

  @HostBinding('class.highlighted')
  get cssClasses() {
    return this.isHighlighted;
  }

  @HostListener('click')
  toggle() {
    this.isHighlighted = !this.isHighlighted;
  }

}

And applied to every div within *ngFor:

 <div *ngFor="let row of rows" highlighted>
    row
 </div>

The css class is attached and removed correctly, but multiple divs can be highlighted at a time.

Given one existing div with .highlighted class already attached to it, upon clicking inside another div, the highlighted directive should be removed from the first div and attached to last clicked one ONLY. Any suggestions?

您可以根据事件目标切换或清除。请检查以下代码:

 import { Directive, HostBinding, Input,ElementRef,  HostListener } from '@angular/core';

@Directive({
  selector: '[highlighted]'
})
export class HighlightedDirective {

constructor(private _elementRef : ElementRef) { }
  @Input('highlighted') isHighlighted = false;


  @HostBinding('class.highlighted')
  get cssClasses() {
    return this.isHighlighted;
  }

  @HostListener('document:click', ['$event.target'])
  public onClick(targetElement) {
    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
      if (clickedInside) {
          this.isHighlighted = !this.isHighlighted 
       }
      else{
        this.isHighlighted =false;
      }
  }

}