I'm trying to add a "clipboard" directive using this example. The example is now outdated so I have had to update how it is getting the nativeElement.
I'm getting the error
Cannot read property 'nativeElement' of undefined
I have marked the error in the code with <===== error here:
clipboard.directive.js
import {Directive,ElementRef,Input,Output,EventEmitter, ViewChild, AfterViewInit} from "@angular/core";
import Clipboard from "clipboard";
@Directive({
selector: "[clipboard]"
})
export class ClipboardDirective implements AfterViewInit {
clipboard: Clipboard;
@Input("clipboard")
elt:ElementRef;
@ViewChild("bar") el;
@Output()
clipboardSuccess:EventEmitter<any> = new EventEmitter();
@Output()
clipboardError:EventEmitter<any> = new EventEmitter();
constructor(private eltRef:ElementRef) {
}
ngAfterViewInit() {
this.clipboard = new Clipboard(this.el.nativeElement, { <======error here
target: () => {
return this.elt;
}
} as any);
this.clipboard.on("success", (e) => {
this.clipboardSuccess.emit();
});
this.clipboard.on("error", (e) => {
this.clipboardError.emit();
});
}
ngOnDestroy() {
if (this.clipboard) {
this.clipboard.destroy();
}
}
}
html
<div class="website" *ngIf="xxx.website !== undefined"><a #foo href="{{formatUrl(xxx.website)}}" target="_blank" (click)="someclickmethod()">{{xxx.website}}</a></div>
<button #bar [clipboard]="foo" (clipboardSuccess)="onSuccess()">Copy</button>
How do I get rid of that error?
Updated to not use AfterViewInit because it is not a view...same error:
@Directive({
selector: "[clipboard]"
})
export class ClipboardDirective implements OnInit {
clipboard: Clipboard;
@Input("clipboard")
elt:ElementRef;
@ViewChild("bar") el;
@Output()
clipboardSuccess:EventEmitter<any> = new EventEmitter();
@Output()
clipboardError:EventEmitter<any> = new EventEmitter();
constructor(private eltRef:ElementRef) {
}
ngOnInit() {
this.clipboard = new Clipboard(this.el.nativeElement, {
target: () => {
return this.elt;
}
} as any);
I think I need to not use @viewChild because it is not a component but am unsure how to populate el
or eltRef
. el
is only there to replace eltRef
because I couldn't populate eltRef
.