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

相关推荐
bloglin9999929 分钟前
npm和nvm和nrm有什么区别
前端·npm·node.js
2501_910227541 小时前
web3 前端常见错误类型以及错误捕获处理
前端·web3
哎哟喂_!1 小时前
Node.js 同步加载问题详解:原理、危害与优化策略
前端·chrome·node.js
__BMGT()1 小时前
C++ QT图片查看器
前端·c++·qt
OK_boom2 小时前
React-useRef
javascript·react.js·ecmascript
未来之窗软件服务2 小时前
solidwors插件 开发————仙盟创梦IDE
前端·javascript·数据库·ide·仙盟创梦ide
小白学大数据2 小时前
基于Scrapy-Redis的分布式景点数据爬取与热力图生成
javascript·redis·分布式·scrapy
Varpb2 小时前
【vue】【环境配置】项目无法npm run serve,显示node版本过低
前端·vue.js·npm
读心悦2 小时前
CSS 溢出内容处理、可见性控制与盒类型设置深度解析
前端·css
Minyy113 小时前
Vue3指令(二)--v-text、v-html数据渲染,计算属性
前端·javascript·vue.js·前端框架·vue·html