No se puede leer la propiedad 'nativeElement' de undefined - ngAfterViewInit
Estoy tratando de agregar una directiva "portapapeles" usandoeste ejemplo. El ejemplo ahora está desactualizado, así que tuve que actualizar cómo se está obteniendo el elemento nativo.
Me sale el error
No se puede leer la propiedad 'nativeElement' de undefined
He marcado el error en el código con <===== error aquí:
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>
¿Cómo me deshago de ese error?
Actualizado para no usar AfterViewInit porque no es una vista ... mismo 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);
Creo que no necesito usar @viewChild porque no es un componente pero no estoy seguro de cómo llenarel
oeltRef
. el
solo está ahí para reemplazareltRef
porque no pude poblareltRef
.