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?
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();
}
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.
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 {}()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With