文章意在記錄自己在學(xué)習(xí)angular2中的一些收獲汇荐,請帶著質(zhì)疑的眼光去看文章掏击。由于本人也是學(xué)習(xí)階段,語言難免會不嚴(yán)謹(jǐn)悼粮,若有說的不對的地方闲勺,歡迎指出~~~
目的
想修改".html"文件(一個component最基本的文件.ts+.html+.css)中的button標(biāo)簽的背景顏色。
實(shí)現(xiàn)
".html"中的<button #greet>測試</button>
修改button的樣式扣猫,比如修改background-color
為blue
菜循。
上述button標(biāo)簽中的#greet
是為了給后面用的,代碼如下:
import {ElementRef,AfterViewInit,ViewChild,Renderer} from '@angular/core';
...
@ViewChild('greet')//ViewChild是Angular 2 內(nèi)置的屬性裝飾器
greetDiv:ElementRef;
constructor(private elementRef:ElementRef,private renderer:Renderer) { }
ngAfterViewInit() {//元素創(chuàng)建完成以后執(zhí)行下面代碼申尤,更多請看angular2的生命周期鉤子
// this.greetDiv.nativeElement.style.background = 'green';
this.renderer.setElementStyle(this.greetDiv.nativeElement,'background-color','blue');
}
ngOnInit() {
}
這個是renderer.setElementStyle的用法癌幕,第二個參數(shù)是background-color
就是添加style的背景顏色。
還可以給模板添加class昧穿,比如:
this.renderer.setElementClass(this.greetDiv.nativeElement,'aaa',true);
這就添加完class了序芦。相當(dāng)于在<button #greet>測試</button>
中添加class='aaa',這樣就可以在.css中使用.aaa{}
添加各種樣式了粤咪;
更多renderer 的API谚中,看這里。
注意:
上述方法我試了一下,貌似只在純html標(biāo)簽中有效宪塔,如果是angular2的自定義標(biāo)簽組件磁奖,貌似不起作用,像這樣:
<div >
<app-back-home #greet></app-back-home>
</div>
是沒有效果的某筐,需要修改此處組件的樣式比搭,應(yīng)該是通過傳參的方式,這里就先不說了南誊。