Angular 5 动画:如何在组件从 DOM 中移除时使用 :leave 过渡

akc*_*soy 5 angular angular-animations

我们一直在我们的项目中使用@ng-bootstrap/ng-bootstrap 库来处理一些行为/组件,比如 Modal。最近我想消除这种依赖性并使用 Angular 实现引导模式行为。这实际上很容易。让我简单地告诉你它是如何工作的:

我有一个模态服务和一个模态组件。服务通过 ComponentFactoryResolver 动态创建模态组件(详细信息可以在这篇 SO post 中看到)并添加到 DOM 中。通过关闭模态,模态只是调用从服务中定义的回调函数,这只会破坏组件,从 DOM 中删除。

所以:我有这个模态组件的 2 个动画状态,进入和离开。输入效果很好。一旦组件出现在 dom 中,预定义的 :enter 状态就会被触发,我的动画就可以工作了。但是 :leave 没有。

这正是关闭模态的工作原理:模态是打开的,您单击关闭按钮或模态背景上的任何其他位置。这只是调用 close 函数,它被定义为一个输入,并在创建过程中从服务中给出。

@Input() closeCallback: Function;
Run Code Online (Sandbox Code Playgroud)

服务只是从 DOM 中删除组件。

由于单击关闭按钮后组件就会被删除,因此我认为动画没有它需要的时间。所以 :leave 不起作用。

我想关闭超时(延迟),并手动触发动画,但由于我想使用预定义的行为:输入和:离开,我无法弄清楚这是怎么可能的。那么我怎样才能让我的离开动画工作呢?(有或没有:离开)

服务代码:

@Injectable()
export class ModalService implements OnDestroy {

  private renderer: Renderer2;
  private componentRef: ComponentRef<ModalComponent>;

  constructor(private rendererFactory: RendererFactory2,
              private componentFactoryResolver: ComponentFactoryResolver,
              private appRef: ApplicationRef,
              private injector: Injector) {
    this.renderer = rendererFactory.createRenderer(null, null);
  }

  ngOnDestroy() {
    this.componentRef.destroy();
  }

  open(content: string, titel: string, primaryButtonLabel: string, secondaryButtonLabel?: string, primaryButtonCallback?: Function, secondaryButtonCallback?: Function) {
    // 1. Create a component reference from the component
    this.componentRef = this.componentFactoryResolver
      .resolveComponentFactory(ModalComponent)
      .create(this.injector);

    this.componentRef.instance.content = content;
    this.componentRef.instance.titel = titel;
    this.componentRef.instance.primaryButtonLabel = primaryButtonLabel;
    this.componentRef.instance.secondaryButtonLabel = secondaryButtonLabel;
    this.componentRef.instance.primaryButtonCallback = primaryButtonCallback;
    this.componentRef.instance.secondaryButtonCallback = secondaryButtonCallback;
    this.componentRef.instance.closeCallback = (() => {
      this.close();
    });

    // 2. Attach component to the appRef so that it's inside the ng component tree
    this.appRef.attachView(this.componentRef.hostView);

    // 3. Get DOM element from component
    const domElem = (this.componentRef.hostView as EmbeddedViewRef<any>)
      .rootNodes[0] as HTMLElement;

    // 4. Append DOM element to the body
    this.renderer.appendChild(document.body, domElem);
    this.renderer.addClass(document.body, 'modal-open');
  }

  close() {
    this.renderer.removeClass(document.body, 'modal-open');
    this.appRef.detachView(this.componentRef.hostView);
    this.componentRef.destroy();
  }
}
Run Code Online (Sandbox Code Playgroud)

模态组件.ts:

@Component({
  selector: '[modal]',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss'],
  animations: [
    trigger('modalSlideInOut', [
      transition(':enter', [
        style({opacity: 0, transform: 'translateY(-100%)'}),
        animate('0.3s ease-in', style({'opacity': '1', transform: 'translateY(0%)'}))
      ]) ,
      transition(':leave', [
        style({opacity: 1, transform: 'translateY(0%)'}),
        animate('0.3s ease-out', style({'opacity': '0', transform: 'translateY(-100%)'}))
      ])
    ])
  ]
})
export class ModalComponent implements AfterViewInit {

  ....
  @Input() closeCallback: Function;

  constructor() { }

  close() {
    this.closeCallback();
  }
}
Run Code Online (Sandbox Code Playgroud)

Modal-HTML 不是很相关,但你可以想象这样的事情:

<div [@modalSlideInOut] role="document" class="modal-dialog">
  <div ....
      <button (click)="close()">
        CLOSE
      </button>

       ...
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 5

我今天遇到了类似的问题,我找到的解决方案是简单地将动画绑定到 Host 组件本身:

@HostBinding('@modalSlideInOut')
Run Code Online (Sandbox Code Playgroud)

这样,您就不必对动画计时进行任何处理。当您调用 destroy 时,Angular 知道组件将消失,因此它会为您处理它,就像您在组件上调用 ngIf 一样。

  • 我知道这已经很旧了,但对于我见过的许多问题来说,这是一个很好的答案。谢谢! (2认同)

akc*_*soy 1

所以我已经找到了解决方法。但我提出了一个问题,是否有更好的方法可以做到这一点。

根据我的理解, :leave 动画是 (* => void) 的快捷方式。* 是“任何状态”,void 是“标签不可见”。因此,当一个组件从 DOM 中删除时,它是不可见的,但动画仍然不起作用,因为该元素不再存在(我的假设)。

所以我给了模态父元素一个 ngIf 标志:

<div *ngIf="showModal" [@modalSlideInOut] role="document" class="modal-dialog">
Run Code Online (Sandbox Code Playgroud)

showModal 默认为 true,因为我们希望模态在 DOM 中后立即显示。close 函数首先将标志 auf 设置为 false,使模式不可见。超时后,调用回调函数,从 DOM 中删除组件。这是关闭函数:

  close() {
    this.showModal = false;
    setTimeout(() => {
      this.closeCallback();
    }, 300);
  }
Run Code Online (Sandbox Code Playgroud)

300 是组件被移除之前的等待时间,因为我的动画需要 0.3 秒。