javascript - 在 TweenLite 中使用 text 方法显示未定义

标签 javascript jquery angular typescript gsap

我正在使用 Green Sock 动画,我目前正在构建加载程序进度并添加百分比计数器示例:- 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 + '%');
      }
    });
  }

关于javascript - 在 TweenLite 中使用 text 方法显示未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55791814/

相关文章:

javascript - 有没有办法在 JavaScript 中反转 Intl.NumberFormat 的格式

jQuery 解析 JSON URL

javascript - 这个函数如何判断一个对象是否为空?

Angular2根据字符串数组过滤对象数组

angular - Ionic 4 - 检查是否可以返回

javascript - TypeError : nodemailer. createTransport 不是一个函数

javascript - 自定义 Chrome 上允许 Flash 气泡

javascript - 使用 JS 在 Google Analytic 中设置目标

javascript - 如何使导航对背景颜色使用react

Angular 5 测试返回错误