Ctrl + c button in typescript, Ionic

Asked

Viewed 459 times

0

Good afternoon, I’m trying to create a button to copy the text of an input, but without success, I’m trying with Clipboard and it doesn’t work, gives an error saying that 'copy()' is not a function. follows the code:

Typescript:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormGroup, FormBuilder, Validators, AbstractControl, FormControl} from '@angular/forms'
import { Clipboard } from '@ionic-native/clipboard/ngx';


/**
 * Generated class for the TestePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-teste',
  templateUrl: 'teste.html',
})
export class TestePage {
private orderForm: FormGroup
  constructor(public navCtrl: NavController,
     public navParams: NavParams, 
     public formBuilder: FormBuilder,
     private clipboard: Clipboard

  ) { let texto = navParams.get('texto');

  this.orderForm = this.formBuilder.group({
    resultado: texto
  })
  }



  copy(){
    // copy function
    this.clipboard.copy('Hello world').then(rs => {
     alert(rs);
   }).catch(error => {
     alert(error);
   })
  }



  ionViewDidLoad() {
    console.log('ionViewDidLoad TestePage');
  }

}

html:

<ion-header>

  <ion-navbar>
    <ion-title></ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
  <ion-card>
    <ion-card-header>

    </ion-card-header>

    <ion-card-content>
    <form [formGroup]="orderForm" novalidate>
      <ion-item>
        <ion-label></ion-label>
        <ion-input type="text" formControlName="resultado" readonly></ion-input>
      </ion-item>

      <button ion-button (click)="copy()" >  <ion-icon ios="ios-copy" md="md-copy"></ion-icon>
      </button>





</form> 

</ion-card-content>
</ion-card>
</ion-content>
  • Are you testing on an emulator or right in the browser ? Because this plugin, by what I researched, has no implementation in the Browser, so calling any function of it would give error.

  • Really, by what I researched it would be that same, you know some other solution for desktop ?

1 answer

0


A desktop solution would be like this:

import { Directive, Input, Output, EventEmitter, HostListener } from "@angular/core";

@Directive({ selector: '[copy-clipboard]' })
export class CopyClipboardDirective {

  @Input("copy-clipboard")
  public payload: string;

  @Output("copied")
  public copied: EventEmitter<string> = new EventEmitter<string>();

  @HostListener("click", ["$event"])
  public onClick(event: MouseEvent): void {

    event.preventDefault();
    if (!this.payload)
      return;

    let listener = (e: ClipboardEvent) => {
      let clipboard = e.clipboardData || window["clipboardData"];
      clipboard.setData("text", this.payload.toString());
      e.preventDefault();

      this.copied.emit(this.payload);
    };

    document.addEventListener("copy", listener, false)
    document.execCommand("copy");
    document.removeEventListener("copy", listener, false);
  }
}

And add to your app.module.ts the directive, thus:

@NgModule({
  declarations: [
    ...
    CopyClipboardDirective //added here
  ],
  ...
})
export class AppModule { }

The original answer link you can find here.

This is a directive that you can place directly on the button you want to be clicked on to activate the copy. For your case, the implementation would look like this:

In the HTML file.

<button ion-button [copy-clipboard]="dataParaACopia">  
    <ion-icon ios="ios-copy" md="md-copy"></ion-icon>
</button>

In the file ts:

public dataParaACopia: string = "O texto que será copiado para o seu clipboard";

A solution without a directive would be like this:

In the .html:

<button ion-button (click)="copyForClipboard($event)">  
    <ion-icon ios="ios-copy" md="md-copy"></ion-icon>
</button>

In the archive .ts:

public copyForClipboard(event: MouseEvent): void {
    event.preventDefault();
    const payload: string = "A informação que será copiada.";

    let listener = (e: ClipboardEvent) => {
      let clipboard = e.clipboardData || window["clipboardData"];
      clipboard.setData("text", payload.toString());
      e.preventDefault();
    };

    document.addEventListener("copy", listener, false)
    document.execCommand("copy");
    document.removeEventListener("copy", listener, false);
}

In parallel, you can use both solutions for what you want to do, use the class Platform and its method called is to identify on which platform the user is, and thus use the appropriate solution for each platform ( the directive on the browser and the plugin on the device ).

  • That first part, I create a new ts file and put it? or inside the page ts file itself ?

  • @Israel you create a new file, I recommend creating a folder called directives and add there the copy-clipboard.directive.ts and put that code there.

  • Sorry the feedback delay, I ended up trying another project on the front. I did what you went through, but is giving the following error: Can’t bind to 'copy-Clipboard' Since it isn’t a known Property of 'button'

  • This is a problem for when it does not find the directive. You added the directive class in the app.module.ts ? If yes, try restarting the ionic serve after doing so.

  • Yes, I added in the declarations part, I created a Directive folder and created the ts file and put what you sent, already restarted Ionic serves tb, but the error continues, only reinforcing that I am using Ionic 3.9.2

  • I updated the answer to a form without the directive, but post here the complete error that is occurring so that we can try to solve too.

  • Thanks Lawrence, now it was!. It is difficult to post the error because it happens at work and I can only access the stack at home, but thanks man! Hug.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.