Angular变化检测 2.0版本学习

        在学习如何在Angular中实现文字逐字显示的过程中,我发现要保证用户的体验感的关键点在于:如何确保实时更新.html页面的内容显示,保证及时在UI界面反应出后端返回的数据?  那如何解决这个问题呢?其实我在博客中有提到过这个问题的解决办法,大家有兴趣可以去帮忙简单的检阅一下:https://blog.csdn.net/qq_44327851/article/details/135152188

        下面是上面博客的进阶版学习---->这篇博客主要是文字逐字显示过程页面实时更新的解决办法,话不多说,直接上代码。

  1. 使用setTimeout函数创建定时器,更新文字显示,并手动触发变更检测:
    import { Component, ChangeDetectorRef } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>{{ displayedText }}</div>
      `
    })
    export class AppComponent {
      text = 'Hello World';
      displayedText = '';
      currentIndex = 0;
    
      constructor(private cdr: ChangeDetectorRef) {}
    
      ngOnInit() {
        const updateText = () => {
          this.displayedText = this.text.slice(0, this.currentIndex + 1);
          this.currentIndex++;
          this.cdr.detectChanges();
          if (this.currentIndex < this.text.length) {
            setTimeout(updateText, 1000);
          }
        };
    
        updateText();
      }
    }
    
  2. 使用NgZone服务在NgZone之外运行文字更新逻辑:
    import { Component, NgZone } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>{{ displayedText }}</div>
      `
    })
    export class AppComponent {
      text = 'Hello World';
      displayedText = '';
      currentIndex = 0;
    
      constructor(private zone: NgZone) {}
    
      ngOnInit() {
        this.zone.runOutsideAngular(() => {
          const interval = setInterval(() => {
            this.zone.run(() => {
              this.displayedText = this.text.slice(0, this.currentIndex + 1);
              this.currentIndex++;
            });
            if (this.currentIndex === this.text.length) {
              clearInterval(interval);
            }
          }, 1000);
        });
      }
    }
    
  3. 使用OnPush变更检测策略和markForCheck方法:
    import { Component, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>{{ displayedText }}</div>
      `,
      changeDetection: ChangeDetectionStrategy.OnPush
    })
    export class AppComponent {
      text = 'Hello World';
      displayedText = '';
      currentIndex = 0;
    
      constructor(private cdr: ChangeDetectorRef) {}
    
      ngOnInit() {
        const interval = setInterval(() => {
          this.displayedText = this.text.slice(0, this.currentIndex + 1);
          this.currentIndex++;
          this.cdr.markForCheck();
          if (this.currentIndex === this.text.length) {
            clearInterval(interval);
          }
        }, 1000);
      }
    }
    
  4. 使用AsyncPipe结合Observable实现文字逐字显示:
    import { Component } from '@angular/core';
    import { timer } from 'rxjs';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>{{ (text$ | async) }}</div>
      `
    })
    export class AppComponent {
      text = 'Hello World';
      text$ = timer(0, 1000).pipe(
        map(index => this.text.slice(0, index + 1)),
        take(this.text.length)
      );
    }
    
  5. 使用Renderer2服务手动更新DOM元素的innerText属性:
    import { Component, Renderer2, ElementRef } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div #textElement></div>
      `
    })
    export class AppComponent {
      text = 'Hello World';
      currentIndex = 0;
    
      constructor(private renderer: Renderer2, private el: ElementRef) {}
    
      ngOnInit() {
        const interval = setInterval(() => {
          this.renderer.setProperty(this.el.nativeElement, 'innerText', this.text.slice(0, this.currentIndex + 1));
          this.currentIndex++;
          if (this.currentIndex === this.text.length) {
            clearInterval(interval);
          }
        }, 1000);
      }
    }
    
  6. 使用ViewChild装饰器获取DOM元素的引用,直接操作DOM元素实现文字逐字显示:
    import { Component, ViewChild, ElementRef } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div #textElement></div>
      `
    })
    export class AppComponent {
      @ViewChild('textElement', { static: true }) textElement: ElementRef;
      text = 'Hello World';
      currentIndex = 0;
    
      ngOnInit() {
        const interval = setInterval(() => {
          this.textElement.nativeElement.innerText = this.text.slice(0, this.currentIndex + 1);
          this.currentIndex++;
          if (this.currentIndex === this.text.length) {
            clearInterval(interval);
          }
        }, 1000);
      }
    }
    
  7. 使用NgZone服务结合setTimeout函数实现文字逐字显示:
    import { Component, NgZone } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>{{ displayedText }}</div>
      `
    })
    export class AppComponent {
      text = 'Hello World';
      displayedText = '';
      currentIndex = 0;
    
      constructor(private zone: NgZone) {}
    
      ngOnInit() {
        this.zone.runOutsideAngular(() => {
          const updateText = () => {
            this.displayedText = this.text.slice(0, this.currentIndex + 1);
            this.currentIndex++;
            if (this.currentIndex < this.text.length) {
              setTimeout(updateText, 1000);
            }
          };
    
          updateText();
        });
      }
    }
    
  8. 使用ElementRef服务直接操作DOM元素实现文字逐字显示:
    import { Component, ElementRef } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div #textElement></div>
      `
    })
    export class AppComponent {
      constructor(private el: ElementRef) {}
    
      ngOnInit() {
        const textElement = this.el.nativeElement.querySelector('#textElement');
        const text = 'Hello World';
        let currentIndex = 0;
    
        const interval = setInterval(() => {
          textElement.innerText = text.slice(0, currentIndex + 1);
          currentIndex++;
          if (currentIndex === text.length) {
            clearInterval(interval);
          }
        }, 1000);
      }
    }
    
  9. 使用Renderer2服务创建文本节点,逐步添加到DOM元素中实现文字逐字显示:
    import { Component, Renderer2, ElementRef } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `java
        <div #textElement></div>
      `
    })
    export class AppComponent {
      text = 'Hello World';
      currentIndex = 0;
    
      constructor(private renderer: Renderer2, private el: ElementRef) {}
    
      ngOnInit() {
        const textElement = this.el.nativeElement.querySelector('#textElement');
        const text = 'Hello World';
    
        const interval = setInterval(() => {
          const textNode = this.renderer.createText(text.slice(0, this.currentIndex + 1));
          this.renderer.appendChild(textElement, textNode);
          this.currentIndex++;
          if (this.currentIndex === text.length) {
            clearInterval(interval);
          }
        }, 1000);
      }
    }
    
  10. 使用@Input装饰器监听输入属性的变化,更新文字显示:
    import { Component, Input } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>{{ displayedText }}</div>
      `
    })
    export class AppComponent {
      @Input() text: string;
      displayedText = '';
      currentIndex = 0;
    
      ngOnInit() {
        const interval = setInterval(() => {
          this.displayedText = this.text.slice(0, this.currentIndex + 1);
          this.currentIndex++;
          if (this.currentIndex === this.text.length) {
            clearInterval(interval);
          }
        }, 1000);
      }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值