我正在使用Green Sock Animation我正在构建加载程序进度并添加百分比计数器示例: - https://codepen.io/linxlatham/pen/aWJaXp
我使用此链接作为参考来显示百分比计数器,但使用文本方法显示未定义
HTML:
<div class="loader">
<div class="loader-border">
<div class="progress" [ngStyle]="{'width': '0%'}">
<div class="progress-text">
<p id="count"><p>
</div>
</div>
</div>
</div>
码:
progres: any;
width: string;
count: any;
tween: any;
newPercent: any;
constructor() {}
ngOnInit() {
this.progres = document.getElementsByClassName('progress')[0];
this.count = document.getElementById('count');
this.tween = new TweenLite(this.progres, 10, {
width: '100%',
ease: Linear.easeNone,
onUpdate: () => {
this.newPercent = (this.tween.progress() * 100).toFixed();
console.log(this.count.innerHTML = this.newPercent + '%');
console.log('-----' + this.count.text()); //show undefined
}
});
}
但它使用innerHTML工作正常请告诉我是否做错了。
不建议在Angular中查询DOM。您需要以Angular方式执行此操作:
首先,您需要用户模板引用变量,以便您可以在组件中引用它们。模板引用变量以#为前缀。
<div class="loader">
<div class="loader-border">
<div class="progress" [ngStyle]="{'width': '0%'}" #progress>
<div class="progress-text">
<p id="count" #count><p>
</div>
</div>
</div>
</div>
现在在您的组件中,您需要导入ViewChild和ElementRef并使用它们,如下所示:
progres: any;
width: string;
count: any;
tween: any;
newPercent: any;
@ViewChild('count') count: ElementRef;
@ViewChild('progress') count: ElementRef;
constructor() {}
ngOnInit() {
this.progres = this.progress.nativeElement;
this.count = this.count.nativeElement;
this.tween = new TweenLite(this.progres, 10, {
width: '100%',
ease: Linear.easeNone,
onUpdate: () => {
this.newPercent = (this.tween.progress() * 100).toFixed();
this.count.nativeElement.innerHTML = this.newPercent + '%');
}
});
}