Angular 将一个字符串进行逐字显示的方法汇总

接上文https://blog.csdn.net/qq_44327851/article/details/136201219, 公司项目是angular,所以实际中使用,我是要考虑到应用Angular框架中,下面是我想到的一些方法汇总,欢迎大家检阅!

  1. 在组件的HTML模板中使用*ngFor指令和setTimeout函数实现逐字显示效果:

    javascript 复制代码
    // app.component.ts
    import { Component, OnInit } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>
          <span *ngFor="let char of text; let i = index">
            <span *ngIf="i < currentIndex">{{ char }}</span>
          </span>
        </div>
      `
    })
    export class AppComponent implements OnInit {
      text = 'Hello World';
      currentIndex = 0;
    
      ngOnInit() {
        const interval = setInterval(() => {
          this.currentIndex++;
          if (this.currentIndex === this.text.length) {
            clearInterval(interval);
          }
        }, 1000);
      }
    }
  2. 使用RxJS的interval操作符和map/pluck/scan/bufferCount操作符:

    javascript 复制代码
    // map操作符
    import { Component } from '@angular/core';
    import { interval } from 'rxjs';
    import { map, take } from 'rxjs/operators';
    
    @Component({
      selector: 'app-root',
      template: `
        <div>{{ text$ | async }}</div>
      `
    })
    export class AppComponent {
      text = 'Hello World';
      text$ = interval(100).pipe(
        take(this.text.length),
        map(i => this.text.slice(0, i + 1))
      );
    }
    
    //scan操作符
    // HTML模板
    <div>{{ text$ | async }}</div>
    
    // 组件代码
    text = "Hello World";
    text$ = interval(100).pipe(
      scan((acc, curr) => this.text.substr(0, curr + 1), '')
    );
    
    
    //pluck操作符
    // HTML模板
    <div>{{ text$ | async }}</div>
    
    // 组件代码
    text = "Hello World";
    text$ = interval(100).pipe(
      pluck('text'),
      map(i => this.text.substr(0, i + 1))
    );
    
    
    //bufferCount操作符
    // HTML模板
    <div>{{ text$ | async }}</div>
    
    // 组件代码
    text = "Hello World";
    text$ = interval(100).pipe(
      bufferCount(1),
      map(arr => this.text.substr(0, arr.length))
    );
  3. **使用rjxs的timer操作符和map/pluck/scan/bufferCount操作符:**这个方法跟第二点几乎一样,只是把interval操作符换成timer操作符就好了,其它的用法一模一样,所以就不过多叙述了。

相关推荐
Carsene几秒前
开源项目文档架构设计:Git Submodule 实现文档与代码的优雅分离
前端·后端
Z思学4 分钟前
promise 有几种状态 async/await 和promise 有什么关系
前端
han_5 分钟前
JavaScript设计模式(四):发布-订阅模式实现与应用
前端·javascript·设计模式
27669582927 分钟前
租车帮(悟空)订单查询算法分析
java·服务器·前端·悟空·悟空app·租车帮·租车帮逆向
用户3266584037418 分钟前
如何初始化 TypeScript + Node.js 项目
javascript
__雨夜星辰__19 分钟前
TypeScript 入门学习笔记(面向对象 + 常用设计模式)
前端·学习·typescript
晚霞的不甘35 分钟前
HarmonyOS ArkTS 进阶实战:深入理解边距、边框与嵌套布局
前端·计算机视觉·华为·智能手机·harmonyos
_野猪佩奇_牛马版35 分钟前
ReACT Agent 开发知识点总结
前端
牛奶1 小时前
你发送的消息,微信到底怎么送到的?
前端·websocket·http
酉鬼女又兒1 小时前
零基础快速入门前端DOM 元素获取方法详解:从代码到实践(可用于备赛蓝桥杯Web应用开发)
前端·javascript·职场和发展·蓝桥杯·js