By using window.getSelection(), we can get the selected text. Here I am just adding little Angular touch to that.
Source Code      DEMO

Markup 

Here on mouseup event, we will show Selected text of the div
<div (mouseup)="showSelectedText()">
  ....
</div>

Script - app.component.ts

Here showSelectedText function code. selectedText variable displays its value
import { Component } from '@angular/core';
@Component({
  selector: 'my-app',
  template: `
  <h3>Select some text </h3>
  <div (mouseup)="showSelectedText()">
  Do you think that facebook, twitter, linkedin are designed to make people addict ?, Then you have to read this article. The most popular social networking sites are following people's habit. It is not concept, it is people's habit
  </div>
  <br/>
  <h3>Selected Text</h3>
  <div>{{selectedText}}</div>
  `
})
export class AppComponent {
  selectedText: string = '';

  showSelectedText(oField) {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    this.selectedText = text;
  }
}

2 comments:

  1. have being looking for a simple way of doing this for a couple of hours. Thanks for the simple example.

    ReplyDelete
  2. I am doing same things on button click, but its not working. Selection goes out on button click. I don't want to do this process on mouseup key event. please give me any suggestion.

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts