【问题标题】:angular 6 animation *ngIf, transition not work角度 6 动画 *ngIf,过渡不起作用
【发布时间】:2018-10-22 08:24:22
【问题描述】:

该项目展示了两种动画变体。

动画选项 1,触发器('animationOption1')
毫无怨言地工作。

动画选项 2,trigger('animationOption2')
转换在这里不起作用。

Online check this project in StackBlitz.com

app.component.html

<h1>Animation Option 1</h1>
<div (click)="changeDivState()"
     [@animationOption1]="clickedDivState"
>Click Me
</div>

<h1>Animation Option 2</h1>
<button (click)="toggleMenu()">Click Me</button>
<ul *ngIf="isMenuOpen"
    [@animationOption2]="isMenuOpen ? 'open': 'close'"
>
  <li>Menu Item 1</li>
  <li>Menu Item 2</li>
  <li>Menu Item 3</li>
</ul>

app.component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  animations: [
    trigger('animationOption1', [
      state('start', style({
        backgroundColor: 'yellow',
        width: '150px',
        height: '150px'
      })),
      state('end', style({
        backgroundColor: 'green',
        width: '300px',
        height: '300px'
      })),
      transition('start => end', animate(1500)),
      transition('end => start', animate('800ms 0.5s ease-out'))
    ]),
    trigger('animationOption2', [
      state('close', style({
        opacity: 0,
        backgroundColor: 'yellow'
      })),
      state('open', style({
        opacity: 1,
        backgroundColor: 'green'
      })),
      transition('close <=> open', animate(3000)),
    ])
  ]
})
export class AppComponent {
  isMenuOpen = false;

  clickedDivState = 'start';

  changeDivState() {
    this.clickedDivState = 'end';
    setTimeout(() => {
      this.clickedDivState = 'start';
    }, 3000);
  }

  toggleMenu(): void {
    this.isMenuOpen = !this.isMenuOpen;
  }
}

谷歌搜索没有找到解决方案。

【问题讨论】:

    标签: angular animation transition


    【解决方案1】:

    要使其正常工作,您需要删除 &lt;ul&gt; 上的 *ngIf="isMenuOpen"。 Angular 无法计算 closed/open 状态之间的转换,因为当 isMenuOpenfalse 时元素根本不存在。

    这是一个StackBlitz,显示了删除*ngIf 的动画效果。

    或者,您可以利用entering/leaving 状态与*ngIf 结合使用。它看起来像这样:

    trigger('animationOption2', [      
      transition(':enter', [
        style({ backgroundColor: 'yellow' }),
        animate(300)
      ]),
      transition(':leave', [
        animate(300, style({ backgroundColor: 'yellow' }))
      ]),
      state('*', style({ backgroundColor: 'green' })),
    ])
    

    这是一个StackBlitz 在行动。

    【讨论】:

    • 好的,谢谢你,亚历山大!但是,当您求解该列表时,它仍保留在文档流中,但可以通过添加具有相应状态值的“显示”属性来轻松更正。
    • 如果您需要将其从文档流中移除,您实际上可以使用:enter:leave 转换。然后您可以使用*ngIf。看看这个question
    • 你也可以使用:enter:leave转场
    • 该死,现在可以理解需要这些":enter" and ":leave",谢谢
    • @AlexanderStaroselsky 我已经使用了提到的解决方案,但是我过去的时间不起作用。它只是像 *ngIf 默认值一样立即隐藏/显示。知道有什么问题吗?
    猜你喜欢
    • 2018-11-08
    • 1970-01-01
    • 2014-06-28
    • 2015-05-28
    • 2012-04-18
    • 2016-09-22
    • 2018-02-28
    • 2019-06-10
    • 1970-01-01
    相关资源
    最近更新 更多