首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >导航后不应重新运行Angular指令

导航后不应重新运行Angular指令
EN

Stack Overflow用户
提问于 2021-08-23 10:14:04
回答 1查看 24关注 0票数 0

我有一个指令,它应该是一个div内容的动画。动画运行良好,但每次导航后都会重播。有没有办法只让它在初始页面加载时运行?

**编辑

我正在制作动画的元素在导航时被重新渲染。

代码语言:javascript
运行
复制
@Directive({
  selector: '[appAnimateText]'
})
export class AnimateTextDirective implements AfterViewInit, OnInit {

  @HostBinding('style.white-space') whiteSpace = 'pre';
  private animateTo: string | undefined;

  constructor(private el: ElementRef) {
  }

  get innerText(): string {
    return this.el.nativeElement.innerText;
  }

  set innerText(newText: string) {
    this.el.nativeElement.innerText = newText;
  }

  ngOnInit(): void {
    this.animateTo = this.innerText;
    // placeholder nbsp string which is than transformed back to the text
    this.innerText = this.innerText.split('').map(() => ' ').join('');
  }

  ngAfterViewInit(): void {
    if (this.animateTo) {
      this.animate(this.animateTo.split(''));
    }
  }

  animate(animateTo: string[]): Promise<void> {
     // animation placeholder
     return new Promise((res) => setTimeout(res, 2000))
  }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-23 10:48:50

我能够通过在我的a服务中包含动画状态来解决这个问题。

我添加了一张带有ngContentId和布尔型天气的地图,不管是否完成。

代码语言:javascript
运行
复制
// Service
export class AppService {
  // ...
  public appAnimationState = new Map<string, boolean>();

  public getAnimationState(elementId: string): boolean | undefined {
    return this.appAnimationState.get(elementId);
  }

  public setAnimationState(elementId: string, state: boolean): void {
    this.appAnimationState.set(elementId, state);
  }

  // ...
}

// Directive
export class AnimateTextDirective implements OnInit {

  @HostBinding('style.white-space') whiteSpace = 'pre';
  private animateTo: string | undefined;
  private ngContentId: string | undefined;

  constructor(private el: ElementRef, private appService: AppService) {
  }

  get innerText(): string {
    return this.el.nativeElement.innerText;
  }

  set innerText(newText: string) {
    this.el.nativeElement.innerText = newText;
  }

  ngOnInit(): void {
    this.ngContentId = this.el.nativeElement.attributes[0].name;

    // I use the ngContentId assigned by angular, which does not change on
    // navigation, that the animation only runs once
    if (this.ngContentId && !this.appService.getAnimationState(this.ngContentId)) {
      this.animateTo = this.innerText;
      this.innerText = this.innerText.split('').map(() => ' ').join('');
      this.animate(this.animateTo.split(''));
      this.appService.setAnimationState(this.ngContentId, true);
    }
  }

  animate(animateTo: string[]): Promise<void> {
  // ...
  }

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68890824

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档