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

相关推荐
风之舞_yjf28 分钟前
Vue基础(14)_列表过滤、列表排序
前端·javascript·vue.js
belldeep1 小时前
QuickJS 如何发送一封邮件 ?
javascript·curl·smtp·quickjs
BillKu1 小时前
scss(sass)中 & 的使用说明
前端·sass·scss
疯狂的沙粒1 小时前
uni-app 项目支持 vue 3.0 详解及版本升级方案?
前端·vue.js·uni-app
Jiaberrr1 小时前
uniapp Vue2 获取电量的独家方法:绕过官方插件限制
前端·javascript·uni-app·plus·电量
谢尔登2 小时前
【React】React 18 并发特性
前端·react.js·前端框架
Joker`s smile2 小时前
使用React+ant Table 实现 表格无限循环滚动播放
前端·javascript·react.js
国家不保护废物2 小时前
🌟 React 魔法学院入学指南:从零构建你的第一个魔法阵(项目)!
前端·react.js·架构
然我2 小时前
从原生 JS 到 React:手把手带你开启 React 业务开发之旅
javascript·react.js·前端框架
import_random2 小时前
[机器学习]svm支持向量机(优势在哪里)
前端