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操作符就好了,其它的用法一模一样,所以就不过多叙述了。

相关推荐
前端若水12 分钟前
在 Vue 2 与 Vue 3 中使用 markdown-it-vue 渲染 Markdown 和数学公式
前端·javascript·vue.js
之歆19 分钟前
DAY_10 JavaScript 深度解析:原型链 · 引用类型 · 内置对象 · 数组方法全攻略(下)
开发语言·前端·javascript·ecmascript
行星飞行1 小时前
从 cursor 、 Claude code 迁移到 codex,30 分钟快速上手 codex 常用技巧
前端
__log1 小时前
ComfyUI 集成技术方案分析报告
javascript·python·django
Pu_Nine_91 小时前
前端埋点从入门到企业实践:手写一个Demo + 主流方案对比
前端·埋点
ZC跨境爬虫1 小时前
跟着 MDN 学 HTML day_56:(HTML 表格基础完全指南)
前端·javascript·ui·html·音视频
Dxy12393102161 小时前
CSS滤镜使用方法完全指南
前端·css
江晓曼*凡云基地1 小时前
Hermes Agent 多Agent模式:并行拆解复杂任务的实战指南
javascript·windows·microsoft
AC赳赳老秦1 小时前
OpenClaw与WPS宏联动:批量执行WPS复杂操作,解决办公表格批量处理难题
java·前端·数据库·自动化·需求分析·deepseek·openclaw
小白学大数据2 小时前
Python 爬虫动态 JS 渲染与无头浏览器实战选型指南
开发语言·javascript·爬虫·python