在 angular 4 中仅在点击时执行动画,而不是在页面加载时执行

Execute animation in angular 4 on click only not on page load

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

点击搜索我显示结果。

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

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

这是我目前尝试过的方法

<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>

这是我的幻灯片in/out动画的代码

 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: '*' }))
      ])
    ])
  ]

请建议我如何处理这个问题?

您正在使用 * => voidvoid => *,它们等同于 :enter:leave。每次元素 appears/disappears(使用 *ngIf)时它们都会被触发。

要控制动画并在单击时触发它,您应该使用自定义转换(我下面的代码中的 active => inactiveinactive => 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;
}