问题的根源在于Angular CDK Overlay仅在第一次设置时应用动画。解决此问题的一个方法是在每次显示Overlay时重新创建动画。以下是示例代码:
import { Component, AfterViewInit, OnDestroy } from '@angular/core';
import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { ComponentPortal } from '@angular/cdk/portal';
@Component({
selector: 'app-overlay-example',
template: `
`,
styles: [`
.my-overlay {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background-color: red;
}
`],
animations: [
trigger('myAnimation', [
state('open', style({ opacity: 1 })),
state('closed', style({ opacity: 0 })),
transition('* => open', animate('500ms ease-in')),
transition('* => closed', animate('500ms ease-out'))
])
]
})
export class OverlayExampleComponent implements AfterViewInit, OnDestroy {
private overlayRef: OverlayRef;
private componentPortal: ComponentPortal;
state: 'open' | 'closed' = 'closed';
constructor(private overlay: Overlay) {}
ngAfterViewInit() {
this.componentPortal = new ComponentPortal(this.overlayTemplateRef);
}
ngOnDestroy() {
if (this.overlayRef && this.overlayRef.hasAttached()) {
this.overlayRef.dispose();
}
}
showOverlay() {
if (!this.overlayRef || !this.overlayRef.hasAttached()) {
this.overlayRef = this.overlay.create();
this.overlayRef.attach(this.componentPortal);
}
// Force re-creation of an animation by switching state.
this.state = (this.state === 'closed' ? 'open' : 'closed');
}
}
在这个示例代码中,我们定义了一个名为'myAnimation'的动画,它仅在透明度从0到1的过程中触发。我们还在Overlay组件中定义了一个'template',它包含了我们的Overlay内容以及将动画绑定到的
在另一个组件中,我们将OverlayExampleComponent插入到模板中。每次用户点击“Show Overlay”按钮时,我们都会