我想使用 Angular Directive 禁用文本选择。到目前为止,我发现像下面这样的角度解决方案对我不起作用(处理程序
onSelectStart
从未被调用)。
从 '@angular/core' 导入 { Directive, ElementRef, HostListener };
@Directive({
selector: '[appDateInput]' ,
host: {
'[style.-webkit-touch-callout]': '"none"',
'[style.-webkit-user-select]': '"none"',
'[style.-khtml-user-select]': '"none"',
'[style.-moz-user-select]': '"none"',
'[style.-ms-user-select]': '"none"',
'[style.user-select]': '"none"',
}
})
export class CopyProtectionDirective {
@HostListener('selectstart') onSelectStart() {
return false;
}
constructor(private elementRef: ElementRef) { }
}
然后在我的材料日期选择器中我这样做了:
<mat-card class="mb-3" appearance="outlined">
<mat-card-content>
<div class="row">
<div class="col-12">
<mat-form-field appearance="outline" hideRequiredMarker >
<mat-label>DOB</mat-label>
<input formControlName="dob" #ref matInput [matDatepicker]="picker" appDateInput>
<mat-hint>{{DATE_FORMAT}}</mat-hint>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
</div>
</mat-card-content>
</mat-card>
这应该有效吗?我是不是做错了什么?
您发布的代码应该可以使用
CopyProtectionDirective
禁用输入字段中的文本选择。但是,您的指令代码中有一个小问题。 selectstart
事件是 DOM 事件,而不是主机事件,因此您应该将其直接附加到 ElementRef.nativeElement
。这是更新后的代码:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appDateInput]'
})
export class CopyProtectionDirective {
constructor(private elementRef: ElementRef) { }
@HostListener('selectstart', ['$event'])
onSelectStart(event: Event) {
event.preventDefault();
}
}
我已经删除了用户选择样式的主机绑定,因为您可以通过阻止
selectstart
事件的默认行为来实现相同的结果。
添加了
@HostListener
装饰器以直接在 selectstart
上监听 ElementRef.nativeElement
事件。
在
onSelectStart
方法中,我们通过调用 selectstart
来防止 event.preventDefault()
事件的默认行为,这实际上会禁用文本选择。
通过这些更改,您的指令应该按预期工作以禁用输入字段中的文本选择。