Browse Source

@HostBinding 裝飾器

可以設定class屬性,去影響宿主元素
master
HarveyMac 2 years ago
parent
commit
5bd08dfd5c
  1. 4
      src/app/app.component.css
  2. 3
      src/app/app.component.html
  3. 14
      src/app/over-highlight.directive.ts

4
src/app/app.component.css

@ -1,3 +1,7 @@
p {
font-family: Lato;
}
p.overing {
color: green;
}

3
src/app/app.component.html

@ -1,3 +1,2 @@
<p appOverHighlight>當游標移到這裡,會改變文字顏色</p>
<!-- 將此段套用directive OverHighlight-->
<p class="overing">這裡套上了就不會改變顏色</p>

14
src/app/over-highlight.directive.ts

@ -1,21 +1,19 @@
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';
import { Directive, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: '[appOverHighlight]'
selector: '[appOverHighlight]',
})
export class OverHighlightDirective {
@HostBinding('class.overing')
isOvering = false;
constructor(private elRef: ElementRef, private renderer: Renderer2) {
}
@HostListener('mouseover')
onMouseOver() {
this.renderer.setStyle(this.elRef.nativeElement, 'color', 'red');
this.isOvering = true;
}
@HostListener('mouseout')
onMouseOut() {
this.renderer.removeStyle(this.elRef.nativeElement, 'color');
this.isOvering = false;
}
}
Loading…
Cancel
Save