【问题标题】:Angular: Does Angular support two custom directives on the same DOM element? [closed]Angular:Angular 是否支持同一个 DOM 元素上的两个自定义指令? [关闭]
【发布时间】:2021-12-16 10:38:19
【问题描述】:

我正在关注creating a custom directive from angular.io 上的示例。原始代码托管在stackblitz。但是,当我 modified the code 创建辅助指令并将其应用于同一元素时,我没有看到它被应用,也没有看到任何错误。

所以,我的问题是 -

  1. Angular 不支持同一元素上的两个指令吗?我发现this 说两个结构指令不能在一个元素上,但不确定自定义指令。
  2. 如果它们受支持,那么有人可以找出上述代码不起作用的原因。

谢谢。

highlight.directive.ts:

@Directive({
  selector: '[lineUnderline]',
})
export class lineUnderlineDirective {
  constructor(private el: ElementRef) {}

  @Input() defaultColor = '';

  @Input('lineUnderline') underlineColor = '';

  @HostListener('mouseenter') onMouseEnter() {
    this.underline(this.underlineColor || this.defaultColor || 'red');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.underline('');
  }

  private underline(color: string) {
    this.el.nativeElement.style.textdecoration = 'underline';
    this.el.nativeElement.style.textdecorationcolor = 'blue';
    this.el.nativeElement.style.textdecorationthickness = '3px';
  }
}

app.component.html:

<h1>My First Attribute Directive</h1>

<h2>Pick a highlight color</h2>
<div>
  <input type="radio" name="colors" (click)="color = 'lightgreen'" />Green
  <input type="radio" name="colors" (click)="color = 'yellow'" />Yellow
  <input type="radio" name="colors" (click)="color = 'cyan'" />Cyan
</div>
<p appHighlight lineUnderline>Highlight me!</p>

<p [appHighlight]="color" defaultColor="violet" lineUnderline>
  Highlight me too!
</p>

<hr />
<h2>Mouse over the following lines to see fixed highlights</h2>

<p [appHighlight]="'gray'" lineUnderline>Highlighted in yellow</p>
<p appHighlight="orange" lineUnderline>Highlighted in orange</p>

【问题讨论】:

    标签: angular custom-directive


    【解决方案1】:

    好吧,如果问题是悬停时看不到下划线,那么您访问的样式属性有误:

    textdecoration 应该是 => textDecoration

    textdecorationcolor 应该是 => textDecorationColor

    textdecorationthickness 应该是 => textdecorationthickness

    【讨论】:

    • 好吧...我会被诅咒的。这么愚蠢的错误。是的..在此之后代码起作用了。谢谢@munleashed。
    • 是的,它发生了。但总是尝试调试一切会容易得多的东西。
    • 这是要求关闭标志为“不可复制/错别字”,不回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 2019-03-14
    • 1970-01-01
    • 2019-12-10
    • 2014-01-03
    • 1970-01-01
    相关资源
    最近更新 更多