Brain
Brain

Reputation: 440

How to enable marking or selecting of text in an Angular routerlink element without to initate a navigation?

I try to mark a text inside a Angular 8 table, but the application initiate a navigation as soon as the mouse click gets up.

    <tr *ngFor="let item of items$ | async" routerLink="{{item.id}}">
      <td>{{item.file.id}}</td>
      <td>{{item.file.name}}</td>
    </tr>

Is it possible to tell Angular, that I want also a possibility to mark and copy the text of an table row? With other words, to stop the navigation event if I have marked a text?

Upvotes: 2

Views: 635

Answers (2)

Ivan F
Ivan F

Reputation: 1

You can use a <span> with (click)="$event.stopPropagation()"

<tr *ngFor="let item of items$ | async" routerLink="{{item.id}}">
    <td>
        <span (click)="$event.stopPropagation()">{{item.file.id}}</span>
    </td>
    <td>
        <span (click)="$event.stopPropagation()">{{item.file.name}}</span>
    </td>
</tr>

Upvotes: -1

Reactgular
Reactgular

Reputation: 54791

There is no text selection event in JavaScript. Selecting text is still a click event since it has a mouse down and up event.

You basically have to do the route manually, but ignore clicks if text is selected.

@Component({
    template: `
      <tr *ngFor="let item of items$ | async" (click)="onClick([item.id])">
         <td>{{item.file.id}}</td>
         <td>{{item.file.name}}</td>
      </tr>
    `
})
export class MyComponent {
   constructor(private router: Router,
               @Inject(DOCUMENT) private doc: Document) {}

   public onClick(url: any) {
       // ignore click if text is selected
       if(!this.doc.getSelection().toString()) {
           this.router.navigateByUrl(url);
       }
   }
}

Upvotes: 5

Related Questions