Cannot read property 'nativeElement' of un

2020-03-05 02:36发布

问题:

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.

I'm getting the error

Cannot read property 'nativeElement' of undefined

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>

How do I get rid of that error?

Updated to not 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 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.

回答1:

You name ElementRef as eltRef but try to use this.el in ngAfterViewInit. You need to use the same name.

this will work:

constructor(private el:ElementRef) {
}

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