-1

I am working on a project in Angular and need to make an input accept me copying and pasting an image into it, similar to whatsapp web. What is the easiest way to do this? I have no idea how to start LOL.

Iago Alexandre
  • 307
  • 1
  • 1
  • 8
  • 1
    Usually a good start is googling. For instance "site:stackoverflow paste image javascript" will give you https://stackoverflow.com/questions/490908/paste-an-image-from-clipboard-using-javascript and https://stackoverflow.com/questions/6333814/how-does-the-paste-image-from-clipboard-functionality-work-in-gmail-and-google-c. And I guess there are also many non-stackoverflow tutorials on it – A_A Jan 11 '23 at 18:06
  • Thanks for the links, they will help a lot. – Iago Alexandre Jan 11 '23 at 18:42

1 Answers1

1

You need to build your one input for this. Here is a Stackblitz to play.

Here is a simple editor component. The Code Behind

import {
  Component,
  Input,
  OnInit,
  Output,
  EventEmitter,
  OnChanges,
  ViewChild,
  ElementRef
} from '@angular/core';


@Component({
  selector: 'editor',
  templateUrl: './editor.html',
  styleUrls: ['./editor.scss']
})
export class Editor implements OnInit, OnChanges {
  @Input() value: any;
  @ViewChild('editor') editor: ElementRef;
  @Output() valueChange = new EventEmitter();


  ngOnInit() {
    document.execCommand("styleWithCSS", false, null);
    this.editor.nativeElement.innerHTML = this.value;
  }
  ngOnChanges(changes: any) {
    try {
      if (this.editor.nativeElement.innerHTML != this.value) {
        this.editor.nativeElement.innerHTML = this.value;
      }
    } catch (err) {

    }
  }

  exec(a, b = null) {
    document.execCommand(a, false, b);
  };

  onInput(newValue) {
    this.valueChange.emit(newValue);
  }
}

The HTML part

<button (click)="exec('bold')">B</button>
<div contenteditable (input)="onInput($event.target.innerHTML)" class="editor" #editor></div>

It's very small. But the contenteditable attribute is important. It has nothing to do with Angular. It's a standard HTML attribute, which makes elements editable.

With this simple thing you can insert Images, too with CTRL + V or mouse right click. But this will only insert a img element into the control. So if you copy a image from your pc it will not working. So you need to do other things. First add this to your HTML Element:

(paste)="onPaste($event)"

And here the code part of this

  onPaste(e) {
    const items = (e.clipboardData || e.originalEvent.clipboardData).items;
    let blob = null;
    for (const item of items) {
      if (item.type.indexOf('image') === 0) {
        blob = item.getAsFile();
        console.log(blob);
      }
    }
  }

With this blob data you can do what you want. Use a FileReader or do what you want.

Flo
  • 2,232
  • 2
  • 11
  • 18