Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular No provider for Clipboard

I am using Angular 9 and trying to use the Clipboard Module programmatically.

  constructor(
    private clipboard: Clipboard
  ) {}

It just wouldn't compile

it gives in the console the following.

NullInjectorError: No provider for Clipboard!

I added 'Clipboard' in the app.module.ts providers array. It is also not working

It is giving

zone-evergreen.js:659 Unhandled Promise rejection: Illegal constructor ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Illegal constructor
    at Object.factory (core.js:17177)
    at R3Injector.hydrate (core.js:17053)
    at R3Injector.get (core.js:16803)
    at NgModuleRef$1.get (core.js:36454)
    at Object.get (core.js:34091)
    at getOrCreateInjectable (core.js:5830)

What am I missing?

like image 410
Missak Boyajian Avatar asked May 12 '20 13:05

Missak Boyajian


3 Answers

Make sure that you import the correct 'Clipboard'

import { Clipboard } from '@angular/cdk/clipboard';

constructor(private clipboard: Clipboard) {

}

then use this function

 private copyToClipboard(str:string) {
    const pending = this.clipboard.beginCopy(str);

      let remainingAttempts = 3;
      const attempt = () => {
        const result = pending.copy();
        if (!result && --remainingAttempts) {
          setTimeout(attempt);
        } else {
          // Remember to destroy when you're done!
          pending.destroy();
        }
      };
      attempt();
  }
like image 50
Maayan Hope Avatar answered Oct 17 '22 16:10

Maayan Hope


I think you forgot to include the import for ClipBoard (in the file where you injected ClipBoard in the constructor):

import {Clipboard} from "@angular/cdk/clipboard"

Because ClipBoard exists also on windows, but it's not the same API:

interface Clipboard extends EventTarget {
    readText(): Promise<string>;
    writeText(data: string): Promise<void>;
}

So you won't have any errors if you forgot the import. But when Angular will try to inject it, it won't find one provider for that.

like image 6
zacheus Avatar answered Oct 17 '22 16:10

zacheus


You need to import the ClipboardModule which registers the Clipboard as a provider.

See the stripped example below. I left out everything else you would put in your module to just focus on the ClipboardModule.

import {NgModule} from '@angular/core';
import {ClipboardModule} from '@angular/cdk/clipboard';

@NgModule({
  imports: [ClipboardModule]
})
export class AppModule {}()
like image 3
Igor Avatar answered Oct 17 '22 14:10

Igor