Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
} 
like image 352
ritz078 Avatar asked Aug 08 '16 19:08

ritz078


People also ask

How do you pass a value to a directive?

If you want to send data to directive then you should try like this: This is my custom directive, and I am going to share two value from component or HTML to the directive. You will have to use your directive in your html and send data to the directive like in below code. I am sending name and value to the test.

What is ElementRef in Angular?

Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.

How do you use directive components?

To create a custom directive we have to replace @Component decorator with @Directive decorator. So, let's get started with creating our first Custom Attribute directive. In this directive, we are going to highlight the selected DOM element by setting an element's background color. Create an app-highlight.

How do you use directive in child components?

You can use exportAs property of the @Directive annotation. It exports the directive to be used in the parent view. From the parent view, you can bind it to a view variable and access it from the parent class using @ViewChild() .


1 Answers

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>
like image 125
Günter Zöchbauer Avatar answered Oct 01 '22 23:10

Günter Zöchbauer