【问题标题】:Directive to change the string inside of a paragraph to uppercase is not working将段落内的字符串更改为大写的指令不起作用
【发布时间】:2021-04-28 16:49:10
【问题描述】:

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

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 元素上。 p 元素是否具有 value 属性。它不应该是innerText。您可以为 ElementRef 指定一个类型,以帮助查看元素上有哪些属性。您可以登录到控制台以查看您的事件是否被触发。您还需要存储原始的 innerText 并在 mouseleave 时将其重置。

标签: html angular angular2-directives


【解决方案1】:

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

【讨论】:

  • 感谢您的回答!我最初将其更改为 mouseenter2 是因为我认为,如果有另一个同名事件,它可能不起作用。所以,是的,它不适用于 mouseenter。
  • 我刚刚查到有解决方案stackblitz.com/edit/…需要更新innerHTML属性
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 1970-01-01
    • 2014-02-04
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多