【问题标题】:Angular wait for template to update before proceeding with calculations?Angular 在继续计算之前等待模板更新?
【发布时间】:2020-10-03 15:32:04
【问题描述】:

我正在尝试从自动高度动画到零然后再返回。在 jQuery 中,我会嗅探自动容器的高度,对该高度进行硬编码,然后将高度更改为零并允许 css 转换来完成它们的工作。要返回,我会取消设置 0 高度,抓取 og 高度,重置 0 高度,动画到 og 高度,最后再次取消设置样式以使一切恢复正常。

对于 Angular,它似乎不想这样做,大概是因为它不会在此函数调用完成之前更新模板,尽管检测到多个更改?

代码:

  onMaximize(e) {
    const height = this.headerNav.nativeElement.offsetHeight;
    this.headerHeight = 'flex: 0 0 ' + height + 'px';
    this.change.detectChanges();
    setTimeout(() => {
      this.headerHeight = 'flex: 0 0 0';
      this.change.detectChanges();
    },0)
  }
  onRestore(e){
    this.headerHeight = 'flex: 0 0 auto; transition: all 0s !important';
    this.change.detectChanges();

    const height = this.headerNav.nativeElement.offsetHeight;
    this.headerHeight = 'flex: 0 0 0';
    this.change.detectChanges();

    this.headerHeight = 'flex: 0 0 ' + height + 'px';
    this.change.detectChanges();

    this.headerHeight = '';
    this.change.detectChanges()
  }

我获得了使用 setTimeout 的最大化,但深度嵌套它们或并行运行它们以进行恢复不起作用。

有没有办法说“等待模板更新,因为我还有更多事情要做”?

【问题讨论】:

    标签: angular


    【解决方案1】:

    我想为此建议角度动画。请使用它们,您可以在那里获得更可行的动画。无需动态更改 CSS。对于那些动态变化的 CSS,角度变化检测和其他 ng-zone 相关的变化触发可能没有正确的时间。

    如果你是动画新手,可以按照这个官方指南进行操作

    试试这个例子,还有很多 stackblitz 你也可以试试。

    除了这个 stackoverflow - Angular 2 animation add overflow property on end 问题你可以找到类似的最大化最小化动画

       state(
          'maximize', 
          style({
            height: '*',
            overflow: 'visible' // or e.g. 'inherit'
        })),
        state('minimize',
          style({
            height: '0',
            overflow: 'hidden'
        }))
    
    ------------------------------------------------------------------
    transition(
      'maximize => minimize',
      group([
        animate('300ms ease-in', style({ height: 0 })),
        animate('300ms steps(1,start)', style({ overflow: 'hidden' }))
      ])
    ),
    transition(
      'minimize=> maximize',
      group([
        animate('300ms ease-out', style({ height: '*' })),
        animate('300ms steps(1,end)', style({ overflow: 'visible' }))
      ]) 
    )
    

    照着做

    【讨论】:

      猜你喜欢
      • 2017-07-31
      • 1970-01-01
      • 2020-01-15
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多