无法读取未定义的 属性 'nativeElement' - ngAfterViewInit

Cannot read property 'nativeElement' of undefined - ngAfterViewInit

我正在尝试使用 添加 "clipboard" 指令。该示例现在已过时,因此我不得不更新它获取 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,因为它不是视图...同样的错误:

@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,因为它不是一个组件,但我不确定如何填充eleltRefel 只能用来替换 eltRef 因为我无法填充 eltRef.

您将 ElementRef 命名为 eltRef,但尝试在 ngAfterViewInit 中使用 this.el。您需要使用相同的名称。

这会起作用:

constructor(private el:ElementRef) {
}

ngAfterViewInit() {
  this.clipboard = new Clipboard(this.el.nativeElement, { 
  target: () => {
    return this.elt;
  }
}