【发布时间】:2017-09-28 11:41:22
【问题描述】:
我正在尝试使用this example 添加“剪贴板”指令。这个例子现在已经过时了,所以我不得不更新它是如何获取 nativeElement 的。
我收到了错误
无法读取未定义的属性“nativeElement”
我在这里用
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。
【问题讨论】:
-
@JuliaPassynkova 看起来不错。但是,将构造函数更改为他的构造函数后,我仍然遇到同样的错误。
-
@JuliaPassynkova 或其他任何人,我可以在上述媒体帖子的 html 中获得使用示例吗?我有 [dbl-click-copy]="foo"。我是否完全删除了
="foo"?
标签: html angular typescript angular2-forms angular2-directives