8

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
}
} 
3
  • 1
    Please add more code that demonstrates what you try to accomplish. What is "other element" and "the directive"? Commented Aug 8, 2016 at 19:48
  • It's possible this is possible. But, I'd be worried about the code design effects of this. If you want information from that element, you can write a function that reads it in the current component, and pass that information in a [bracket]="func()" attribute. If you want to change that element, you could watch an event on your subcomponent. For other uses, specialized tags work well. Commented Aug 8, 2016 at 20:00
  • angular.io/docs/ts/latest/api/core/index/ViewChild-var.html Commented Aug 8, 2016 at 21:46

1 Answer 1

16

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>
Sign up to request clarification or add additional context in comments.

2 Comments

How to reset this element if it is input #other?
What do you mean with "reset"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.