问题描述
我正在尝试使用此示例添加剪贴板"指令.该示例现已过时,因此我不得不更新它获取 nativeElement 的方式.
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.
我收到错误
无法读取未定义的属性nativeElement"
我在代码中用 <====== error 标记了错误:
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>
我如何摆脱那个错误?
更新为不使用 AfterViewInit,因为它不是视图...同样的错误:
@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);
我想我不需要使用@viewChild,因为它不是一个组件,但我不确定如何填充el
或eltRef
.el
仅用于替换 eltRef
,因为我无法填充 eltRef
.
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
.
推荐答案
你将 ElementRef
命名为 eltRef 但尝试在 ngAfterViewInit
中使用 this.el
代码>.您需要使用相同的名称.
You name ElementRef
as eltRef but try to use this.el
in ngAfterViewInit
. You need to use the same name.
这会起作用:
constructor(private el:ElementRef) {
}
ngAfterViewInit() {
this.clipboard = new Clipboard(this.el.nativeElement, {
target: () => {
return this.elt;
}
}
这篇关于无法读取未定义的属性“nativeElement" - ngAfterViewInit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!