我正在尝试使用 this example 添加“剪贴板”指令.该示例现在已过时,因此我不得不更新它获取 nativeElement 的方式。
我遇到了错误
Cannot read property 'nativeElement' of undefined
我在代码中用 <===== 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,因为它不是 View ...同样的错误:
@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
。
最佳答案
您将 ElementRef
命名为 eltRef,但尝试在 ngAfterViewInit
中使用 this.el
。您需要使用相同的名称。
这会起作用:
constructor(private el:ElementRef) {
}
ngAfterViewInit() {
this.clipboard = new Clipboard(this.el.nativeElement, {
target: () => {
return this.elt;
}
}
关于html - 无法读取未定义的属性 'nativeElement' - ngAfterViewInit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43712642/