【问题标题】:Trigger Angular animation on form error在表单错误时触发 Angular 动画
【发布时间】:2018-08-27 05:46:26
【问题描述】:

当用户尝试发送输入错误的表单时,我试图给他一个视觉反馈。因此,当他尝试发送包含错误的表单时,我想为输入字段设置动画。

ts文件中的动画:

trigger('error', [
      transition('* => *', useAnimation(shake)),
      ]),

html文件中的表单:

<mat-form-field [@error]="error">

是否可以在每次用户尝试发送表单并且包含错​​误时触发此动画?

StackBlitz example (Updated with solution)

如您所见,摇动动画在开始时播放,然后不再播放。

解决方案:

从下面的答案中,我更改了设置 onAddErrAnim 变量的顺序。现在onAddErrAnim 首先设置为false,然后在setTimout 内调用if 语句,时间为0 毫秒。现在用户可以每毫秒调用一次onAdd(),动画就会播放到最后(如果没有触发新的动画)。

onAdd() {
  this.onAddErrAnim = false;

  setTimeout( () => {

    if (this.myFormControl.invalid) {
      this.onAddErrAnim = true;
      return;
    } else {
      this.myArray.unshift([this.inputExample]);
    }

  }, 0 )

}

【问题讨论】:

    标签: angular animation angular5 angular-forms angular-animations


    【解决方案1】:

    我更新了你的code example

    <div class="example-container" >
      <mat-form-field 
        floatPlaceholder="never" 
        class="input-box" 
        style="width: 100%" 
        (keyup.enter)="onAdd()"
        [@error]="myFormControl.invalid">
    

    表单无效时会触发@error

    加载页面时仍会调用动画。我该如何避免呢?

    CODE EXAMPLE 2 (UPDATED).

    而且我希望动画仅在 onAdd() 上触发 功能

    我在组件类中创建了一个animationState属性:

    animateError = 'false';
    

    并将其绑定到[@error] 触发器。根据状态变化,它会触发相应的动画。

    来自模板文件内的false =&gt; true

     ...
     transition('false => true', useAnimation(shake)),
    

    模板内部:

    [@error]="animateError">
    

    onAdd()函数被调用时,它通过myFormControl的验证来更新状态:

        onAdd() {
        if (this.myFormControl.invalid) {
          this.animateError = 'true';
           // after animation is done, restore the initial state
           setTimeout(() => {
              this.animateError = false;
           }, 500);
    
          return;
        } else {
          this.animateError = 'false';
        }
        console.log(this.myFormControl);
        this.myArray.unshift([this.inputExample]);
    
      }
    

    2018 年 3 月 19 日更新:

    小改进代码示例,将动画状态的string 变量替换为boolean

     trigger('error', [
          state('0', style({})),
          state('1', style({})),
          transition('0 => 1', useAnimation(shake)),
        ]),
    

    ...

     animateError = 'false'; =>  animateError = false;
    

    不应该有更高效的方式来触发动画吗 没有在变量中保存布尔值?

    在这种情况下,不。使用自定义动画状态时,我们需要在某处保存状态值。它可能在组件类,数据模型类...因为在你的具体情况下,我们需要手动控制动画(动画需要在onAdd()函数被调用时触发)。

    【讨论】:

    • 加载页面时仍然调用动画。我该如何避免呢?而且我希望动画只在onAdd()函数上触发
    • @NightTrain,为您的第一个问题添加了代码示例 2
    • @NightTrain,回答了你的第二个问题
    • 难道不应该有一种更高效的方式来触发动画而不在变量中保存布尔值吗?
    • @NightTrain,我认为这个操作(2个或多个状态更改)不能在一个digest cycle中完成,因此我们使用setTimeout在下一个周期运行它
    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多