Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular (2/4): selecting text fires click event

Tags:

angular

If an element has a (click) handler and you select some text within this element, the (click) handler gets called. Is there a way to prevent this? Here's a Plunkr illustrating the problem. Relevant code:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (click)="handleClick()">Click or select this text</h2>
    </div>
  `
})
export class App {
  public handleClick() {
    alert('you clicked');
  }
}
like image 772
fikkatra Avatar asked Oct 17 '17 08:10

fikkatra


2 Answers

Pass the click event ($event) to the handleClick method

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2 (click)="handleClick($event)">Click or select this text</h2>
    </div>
  `
})

Then use the following code to get the selection type:

export class App {
  public handleClick(event) {
    if (event.view.getSelection().type !== 'Range') {
      alert('you clicked');
    }
  }
}

or:

export class App {
  public handleClick(event) {
    if (event.view.getSelection().toString().length === 0) {
      alert('you clicked');
    }
  }
}

Plunker demo: https://plnkr.co/edit/PEPyPzDkFjweyAHK8Tj6?p=preview

like image 192
Tim Hovius Avatar answered Nov 07 '22 13:11

Tim Hovius


use this code

public handleClick() {
  var selection = window.getSelection();
  if(selection.toString().length === 0) {
      alert('you clicked');
  }

}
like image 29
Raja Mohamed Avatar answered Nov 07 '22 15:11

Raja Mohamed