使用directives來更改html物件的css樣式

1
<p newStyle>Style me with directive</p>

新增typescript檔案來定義directives

  1. 直接更改DOM(不建議):
1
2
3
4
5
6
7
export NewStyleDirective implements OnInit {
constructor(private elementRef: ElementRef) {}

ngOnInit() {
this.elementRef.nativeElement.style.backgroundColor = 'yellow';
}
}
  1. 不直接更改DOM(建議做法):
1
2
3
4
5
6
7
export NewStyleDirective implements OnInit {
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}

ngOnInit() {
this.renderer.setStyle(this.elementRef.nativeElement, 'background-color', 'yellow');
}
}