将字符串从 html 传递给指令

Pass string to directive from html

我正在尝试使用 添加 "clipboard" 指令。

但是我想计算要复制到剪贴板的字符串。

我想将 returns 字符串的函数结果传递给我的指令。

目前,它将 "getCopyDetails(supplier)" 字符串传递给指令。

因为我试图将计算的字符串传递给 html 中的按钮(包含指令):

<button [clipboard]="foo, getCopyDetails(supplier)" (clipboardSuccess)="onSuccess()">Copy</button>

导致错误的原因。

代码:

clipboard.directive.ts:

import {Directive,ElementRef,Input,Output,EventEmitter, ViewChild, AfterViewInit} from "@angular/core";
import Clipboard from "clipboard";
import { SupplierSearchComponent } from "../components/suppliersearch.component"

declare var jQuery:any;

@Directive({
  selector: "[clipboard]"
})
export class ClipboardDirective implements AfterViewInit {
  clipboard: Clipboard;

   @Input("clipboard")
   elt:ElementRef;

   text: string;

  @Output()
  clipboardSuccess:EventEmitter<any> = new EventEmitter();

  @Output()
  clipboardError:EventEmitter<any> = new EventEmitter();

  constructor(private eltRef:ElementRef, text) {
    this.text = text
  }

  ngAfterViewInit() {
    this.clipboard = new Clipboard(this.eltRef.nativeElement, {
      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();
    }
  }
}

search.component.html:

<div  class="website" *ngIf="xxx.website !== undefined"><a #foo href="{{formatUrl(xxx.website)}}" target="_blank" (click)="someclickmethod()">{{xxx.website}}</a></div>
<button [clipboard]="foo, getCopyDetails(supplier)" (clipboardSuccess)="onSuccess()">Copy</button>

来自 search.component.ts 的片段(与上面相同的组件):

getCopyDetails(supplier: Supplier): string {
    var details: string = "";

    details += xxx.yyy + "\n\n";
    details += xxx.yyy + "\n";
    details += xxx.yyy + "\n";
    details += xxx.yyy + "\n";
    details += xxx.yyy + "\n";

    return details;
}

另一位程序员的旧 html 代码(他使用 "ngx-clipboard": "^5.0.8" plugin which is a wrapper around clipboard.js,我将其用于剪贴板)已被注释掉,我基本上已尝试将其应用于我在 [=60] 中的指令=] 以上:

<!--<button class="btn anchor" (click)="supplierCopyDetailsClick()" ngxClipboard [cbContent]="getCopyDetails(supplier)">Copy details</button>-->

如何将从getCopyDetails()获取的字符串传递给我的指令?

判断,我可以在 HTML 中执行 my-object='{"Code":"test"}',然后在我的指令中使用它来复制它。不过,我有点不确定我在指令中放置了什么代码来保存该对象。

您只能使用 Angular DI 进行注入:@Injectable() 服务、父组件或 InjectionToken。

所以文字不正确。

constructor(private eltRef:ElementRef, text) {
  this.text = text
}