Cannot read property "nativeElement" from undefined - ngAfterViewInit
I am trying to add a clipboard directive using this example . The example is now deprecated, so I had to update how it gets the nativeElement.
I am getting the error
Cannot read property "nativeElement" from undefined
I noted the error in the code with the 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 this error?
Updated not to 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 guess I don't need to use @viewChild because it's not a component, but I'm not sure how to fill el
or eltRef
. el
only exists there to be replaced eltRef
because I could not fill eltRef
.
source to share