user5113188
user5113188

Reputation:

inserting text in current (or last) caret position inside of TextArea, in Angular; Element is not interpreted as TextArea

I was checking this documentation...

https://material.angular.io/cdk/clipboard/examples

Is there some example explaining how to paste inside some text of the last current (maybe starting, or middle) position inside of TextArea (after of lost focus event).

I was trying with this simple response: https://stackoverflow.com/a/58356806/5113188

function insertAtCaret(text) {
  const textarea = document.querySelector('textarea')
  textarea.setRangeText(
    text,
    textarea.selectionStart,
    textarea.selectionEnd,
    'end'
  )
}

setInterval(() => insertAtCaret('Hello'), 3000)

Adapting to my code:

In .html file:

    <button mat-icon-button type="button" (click)="onInsertSomethingText(entry)" >
      <mat-icon>play_for_work</mat-icon>
    </button>

  <div>
    <mat-form-field>
      <textarea
        [id]="BODY_TEXTAREA"
        matInput
        rows="5"
        formControlName="body"
      ></textarea>
    </mat-form-field>
  </div>

In my .ts file

  public readonly BODY_TEXTAREA = 'BODY_TEXTAREA';
  
  private buildMyFormGroup() {
    return internalFormGroup = this.formBuilder.group({
      body: ['', [Validators.required, Validators.minLength(1)]],
    });
  }
   
  //Event in ordfer to insert the text in the position!!!!
  public onInsertSomethingText(myText: string) {
    console.log(myText);
    const myTA = document.querySelector(this.BODY_TEXTAREA);
    myTA.setRangeText(myText, myTA.selectionStart, myTA.selectionEnd, 'end');
  }
 

In this line myTA.setRangeText(myText, myTA.selectionStart, myTA.selectionEnd, 'end'); I'm obtaining these:

I know that possibly, the myTA is not interpreted as a real TextArea

How to do it correctly?

Thanks in Advance

Upvotes: 0

Views: 1067

Answers (1)

yurzui
yurzui

Reputation: 214017

When you're dealing with Angular you're in TypeScript world.

document.querySelector method is a generic method where by default it returns Element:

querySelector<E extends Element = Element>(selectors: string): E | null;

Simply choose the proper type and you're done:

const myTA = document.querySelector<HTMLTextAreaElement>(`#${this.BODY_TEXTAREA}`);
                                    ^^^^^^^^^^^^^^^^^^^          

Upvotes: 2

Related Questions