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

相关推荐
deli00728 分钟前
手机20%突然关机?电量百分比是估的,SOC曲线4组实测
前端
深蓝AI11 小时前
Meta 开源用了八年的设计系统 astryx:连坐两天 GitHub 总榜第一,组件库开始写给 agent 的说明书
前端·人工智能
IT_陈寒12 小时前
Vue的watch把我坑惨了,原来要这样用才靠谱
前端·人工智能·后端
1-1=012 小时前
Vue 3 模板语
前端·javascript·vue.js
用户76103044737112 小时前
【转战智能眼镜开发】ROKID AIUI 小游戏 亚马逊标枪项目实战讲解
前端
风卿12 小时前
看着AI写代码太孤独了,来欣赏星云吧:一个DSH 装饰插件
前端·javascript
牧艺12 小时前
弹层不用再手算坐标了:CSS Anchor Positioning 从原理到可上线
前端·javascript·css
用户老李12 小时前
YOLO 目标检测自学教程 07:YOLOv3——多尺度预测
前端
moshuying13 小时前
ESP32 墨水屏金价牌(上):从点亮到把图片推过去
前端
李剑一13 小时前
别再抬杠,前端岗已经没了!无论前后端,我们最终都要成“全干”工程师
前端·面试