Home > Net >  Angular: Does Angular support two custom directives on the same DOM element?
Angular: Does Angular support two custom directives on the same DOM element?

Time:11-02

I was following the example on creating a custom directive from angular.io. The original code is hosted on stackblitz. However, when I modified the code to create a secondary directive and applied it to the same element, I do not see it getting applied nor do I see any errors thrown.

So, my questions are -

  1. Does angular not support two directives on the same element ? I have found this which says that two structural directives cannot be on one element but not sure about custom directives.
  2. If they are supported then can someone identify why the above code is not working.

Thanks.

highlight.directive.ts:

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

  @Input() defaultColor = '';

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

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

  @HostListener('mouseleave') onm ouseLeave() {
    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>

CodePudding user response:

Well, if the problem is that you dont see underline when you hover it then you are accessing wrong style properties:

textdecoration should be => textDecoration

textdecorationcolor should be => textDecorationColor

textdecorationthickness should be => textdecorationthickness

  • Related