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
}
}
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.
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.
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.
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() .
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With