ritz078
ritz078

Reputation: 2337

pass element reference to a directive

I want to pass an element reference to a directive. I know that the reference of the element on which the directive has been applied can be obtained by

private _elemRef: ElementRef

but I want to pass the reference to other element to the directive. Any help is appreciated.

Here's the demo code. I m using a ripple directive.

<ul #other>
  <li ripple>Hello</li>
</ul>

directive.js

@Directive({
  selector: '[ripple]'
})
export class RippleDirective {
  constructor(private _elemRef: ElementRef) {
  }

  @HostListener('click', ['$event'])
  public onClick(event: MouseEvent) {
    // I wan't to refer the '#other' node here
}
} 

Upvotes: 8

Views: 9132

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658263

You can pass the template variable #other to an @Input():

@Directive({
  selector: '[ripple]'
})
export class RippleDirective {
  @Input() ripple;

  @HostListener('click', ['$event'])
  public onClick(event: MouseEvent) {
    this.ripple...
  }
} 
<ul #other>
  <li [ripple]="other">Hello</li>
</ul>

Upvotes: 16

Related Questions