【问题标题】:Execute animation in angular 4 on click only not on page load仅在点击时以角度 4 执行动画,而不是在页面加载时
【发布时间】:2018-10-11 15:30:10
【问题描述】:

我有一个在页面加载时显示的输入字段。

点击搜索我会显示结果。

点击隐藏你的搜索参数我隐藏搜索输入,点击显示我显示它。

但问题是,当我在搜索输入字段中应用幻灯片时,它会在页面加载时加载,它是动画。我只想在单击隐藏或显示您的搜索参数链接时添加动画。

这是我迄今为止尝试过的

<div class="row seven-cols" *ngIf="showSearch" [@slideIn]>
            <div class="col-md-2">
        <input class="form-control" placeholder="Store#">
                    </div>
                    <!-- Search Button -->
    <button type="button"[disabled]="isValidStoreId || !storeMod"
                            (click)="search(storeMod)">
                            {{componentContents.searchButton}}
                        </button>
                </div>

这是切换搜索的代码

<span class="filterPipe"><a href="javascript:void(0)" (click)="showSearch = !showSearch" class="toggleTxt">{{ showSearch == true ? 'Hide' : 'Show' }} {{componentDetails.searchToggleHead}}</a></span>

这是我的滑入/滑出动画的代码

 animations: [
    trigger('slideIn', [
      state('*', style({ 'overflow-y': 'hidden' })),
      state('void', style({ 'overflow-y': 'hidden' })),
      transition('* => void', [
        style({ height: '*' }),
        animate(250, style({ height: 0 }))
      ]),
      transition('void => *', [
        style({ height: '0' }),
        animate(250, style({ height: '*' }))
      ])
    ])
  ]

请建议我如何处理?

【问题讨论】:

  • 不要使用void* 状态,而是使用命名状态。这样,它在出现时什么都不做,并且您可以在点击时应用名称状态。
  • 你能给我一个例子,因为我是角度动画的新手
  • The documentation 为您服务!

标签: javascript angular angular-animations


【解决方案1】:

您正在使用* =&gt; voidvoid =&gt; *,它们等效于:enter:leave。每次元素出现/消失时都会触发它们(使用*ngIf)。

要控制动画并在点击时触发它,您应该使用自定义过渡(下面我的代码中的active =&gt; inactiveinactive =&gt; active)。

像这样改变你的动画:

animations: [
  trigger('slideIn', [
    state('active', style({ 'overflow-y': 'hidden' })),
    state('inactive', style({ 'overflow-y': 'hidden' })),
    transition('active => inactive', [
      style({ height: '*' }),
      animate(250, style({ height: 0 }))
    ]),
    transition('inactive => active', [
      style({ height: '0' }),
      animate(250, style({ height: '*' }))
    ])
  ])
]

然后在您的 HTML 中,删除 *ngIf 并像这样使用动画:

<div class="row seven-cols" [@slideIn]="showSearch?'active':'inactive'">

我还没有测试过代码。但它应该工作。如果有任何错误,请告诉我。

如果你必须使用*ngIf

如果需要使用*ngIf,您可以使用另一个变量并在动画完成时将其打开和关闭。像这样:

(@slideIn.done)="animDone($event)"

animDone(e: AnimationEvent) => {
  if (e.toState === 'active') showSearchNgIf = true;
  else if (e.toState === 'inactive') showSearchNgIf = false;
}

【讨论】:

  • 如果没有 *ngIf 我需要在点击链接时设置 showSearch 活动/非活动吗?
  • 没有 ngif 不会隐藏搜索栏
  • @user1881845 是的,与您的代码相同,您需要在单击链接时将 showSearch 设置为活动/非活动。也感谢您的报告
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 2018-02-24
  • 2021-12-30
  • 1970-01-01
相关资源
最近更新 更多