[英]Angular2 component styles/css not applied by browser in ngAfterViewInit
我在angular 2.0組件中使用一些JQuery庫時遇到問題。 問題是這個庫OwlCarousel正在內部使用一些測量$('element).width()
來正確應用。
在我的ngAfterViewinit
里面,我用$(this.carousel.nativeElement).owlCarousel(options);
創建輪播$(this.carousel.nativeElement).owlCarousel(options);
該方法的問題在於,無法保證在此生命周期樣式中,添加到標頭標記的角度已經被borwser重新計算並應用。
它導致非確定性行為。 有時輪播正在獲得大小合適的元素 - 有時候它的速度太快而且大小為0,因為盡管樣式元素已經在HTML的標題中,但它並沒有被瀏覽器應用。 有什么建議?
@Component({
selector: 'tc-slider',
styles: [`
.slide{
width:100px;
}
`],
template: `
<div class="wrapper">
<div #carousel>
<div class="slide">1</div>
<div class="slide">2</div>
<div class="slide">3</div>
<div class="slide">4</div>
</div>
</div>`,
encapsulation: ViewEncapsulation.None,
})
export class SliderComponent {
@ViewChild('carousel') carousel:ElementRef;
ngAfterViewInit() {
var options:any = {
mouseDrag: false,
autoWidth: true
};
$(this.carousel.nativeElement).owlCarousel(options);
}
}
$('。slide')。width()在ngAfterViewInit中為0。 大部分時間都是正確測量的,但一次測量10次就有0次。
問題解決了。 它是由@import url引起的(' http://fonts.googleapis.com/css?family=Noto+Sans:400,700 '); 在我的一個css樣式里面,由angular comonent添加。 這是阻止css解釋直到從谷歌下載。 當javascript更快時,谷歌會以不良大小的元素回應結果,因為此聲明下面的所有CSS樣式:@import url(' http://fonts.googleapis.com/css?family=Noto+Sans:400,700 '); 尚未受到瀏覽器影響和應用的地方。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.