2017-10-17 77 views
2

如果某個元素具有(click)處理程序,並且您在此元素中選擇了一些文本,則會調用(click)處理程序。有沒有辦法來防止這種情況?說明問題的Here's a Plunkr。相關代碼:Angular(2/4):選擇文本觸發單擊事件

@Component({ 
    selector: 'my-app', 
    template: ` 
    <div> 
     <h2 (click)="handleClick()">Click or select this text</h2> 
    </div> 
    ` 
}) 
export class App { 
    public handleClick() { 
    alert('you clicked'); 
    } 
} 

回答

2

使用此代碼

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

} 
1

傳遞click事件($event)到​​方法

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

然後使用下面的代碼來獲得選擇類型:

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

或:

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

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