指令将段落内的字符串改为大写是不工作的



我正试图编写一个指令,当您将鼠标悬停在上面时,将段落的内容变为大写。我没有得到任何错误-它只是不工作。我之前写过一个类似的代码,将文本突出显示为特定的颜色,这是有效的。为什么在将文本更改为大写时也不能工作?

filter.component.html

<p appToUpperCase>String to uppercase</p>

to-upper-case.directive.ts

import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
selector: '[appToUpperCase]'
})
export class ToUpperCaseDirective {
constructor(public el: ElementRef) {
}
@HostListener('mouseenter2') onMouseEnter() {
this.el.nativeElement.value = this.el.nativeElement.value.toUpperCase();
}
}

编辑:正如@Ilya Rachinsky建议的那样,我已经将事件名称从mouseenter2更改为mouseenter,但它仍然不起作用。

你的指令结构看起来很好。我猜你忘记把它包含在模块的声明列表中了,所以这个指令对模板是可用的。此外,在'p'元素上没有'value'属性,您需要使用innerHTML,如前所述。

查看示例:https://stackblitz.com/edit/angular-ivy-uppercase-directive?file=src%2Fapp%2Fto-upper-case.directive.ts

您必须使用正确的事件名称- mouseenter而不是mouseenter2

最新更新