简体   繁体   中英

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

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') 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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM