[英]Angular TimelineLite time function doesn't work with OnInit
我嘗試使用 TimelineLite 實現進度條和計時器:
HTML:
<div id="progress"></div>
{{timeline.time()}}
CSS:
#progress {
width: 100%;
height: 30px;
background-color: red;
}
這是我想要的:
當頁面加載時,進度條開始從 100% 到 0% 寬度(10 秒持續時間)進行動畫處理。 另外,我想顯示time
函數的結果。
這是我所做的:
public timeline = new TimelineLite();
ngOnInit() {
this.start();
}
start() {
const progress = document.getElementById('progress');
this.timeline.fromTo(progress, 10, {width: '100%'}, {width: 0, ease: Linear.easeNone});
}
因此,當頁面加載時,進度條會工作,但計時器不會。 我不知道為什么。 如果我嘗試在ngOnInit
設置超時 3 秒,它會起作用:
ngOnInit() {
setTimeout(() => this.start(), 3000);
}
此外,如果我創建一個按鈕而不是在單擊時調用start
函數,它會起作用:
<button (click)="start()">Start</button>
所以問題是,如果我嘗試從ngOnInit
調用fromTo
函數,則計時器不起作用。
嗨,您應該使用@ViewChild
來定位您的元素,並在您想要操作時使用AfterViewInit
lifeCycleHook | 訪問您的 DOMElement(當前組件或子組件)。
export class AppComponent implements AfterViewInit {
@ViewChild('progress') progressElement: ElementRef;
constructor(private changeRef: ChangeDetectorRef) { }
public timeline = new TimelineLite();
ngAfterViewInit() {
this.start();
}
start() {
this.timeline.eventCallback('onUpdate', () => {
this.time = this.timeline.time();
this.changeRef.detectChanges();
}, [] );
// Here i use the ViewChild Binding instead of pure javascript fetching.
this.timeline.fromTo(this.progressElement.nativeElement, 10, {width: '100%'}, {width: 0, ease: Linear.easeNone});
}
}
為了方便您的測試,我做了Github 拉取請求。 任何閱讀您原始問題的人都可以輕松看出其中的區別。
更新 1:在您看來,您調用了一個函數,該函數從 TimelineLite 返回當前計時器。 因為只是函數調用,所以不會在每次內部 TimelineLite 更新時一次又一次地調用。
為此,您必須使用TimelineLite 事件綁定。
現在,默認情況下,每次從以下代碼更新屬性時,您的視圖都不會“更新”:
this.timeline.eventCallback('onUpdate', () => {
// angular is not inform by default than something happen here.
}, [] );
這就是為什么,您應該使用ChangeDetectorRef
來強制 angular 檢測最新更新的組件屬性。
拉請求已更新
這顯然是調用angular生命周期方法的timeline的一個案例。 問題很可能出在 onInit 中,您無法立即獲得 DOM 元素progress
。 您已經通過應用settimeout
使其工作,另一種方式是保持setinterval
直到您找到progress
。
貌似最好的方法是在this.start()
中寫ngAfterViewInit()
而不是ngOnInit()
可能是因為超時在模板初始化之后開始,然后代碼在 OnInit 之外運行。 我不確定。
您可能想在這里使用 zone.run()。
這是一個鏈接,它可能對您有所幫助: https : //medium.com/@MertzAlertz/what-the-hell-is-zone-js-and-why-is-it-in-my- angular-2-6ff28bcf943e
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.