将段落内的字符串更改为大写的指令不起作用

问题描述

我正在尝试编写一个指令,当您将鼠标悬停在段落上时,该指令将段落的内容变为大写。我没有收到任何错误 - 它只是不起作用。我之前写了一个类似的代码,将文本突出显示为某种颜色,这很有效。为什么将文本更改为大写时它也不起作用?

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,但它仍然不起作用。

解决方法

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

,

您的指令结构看起来不错。我猜您忘记将它包含在模块的声明列表中,因此该指令可用于模板。此外,“p”元素没有“value”属性,您需要按照之前的建议使用innerHTML。

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