如何在将现有组件留在前台的同时使用 CDK 覆盖?



角度材质CDK库提供了包括叠加在内的各种功能。我能找到的所有示例都显示了如何在覆盖层顶部显示新组件。我的目标有点不同。我想在覆盖层的顶部显示一个现有组件(屏幕上的几个组件之一(。

我想到的行为是,当用户在特定对象上进入某种编辑模式时,表示该对象的组件将"浮动"在叠加层之上,直到编辑完成或取消。

有什么直接的方法可以做到这一点吗?似乎cdkConnectedOverlay指令可能有用,但我不知道如何使其工作。

Angular CDK 为您提供了两种实现此目的的方法(指令和服务(。

使用Overlay服务,您需要调用传递positionStrategyprop 的create方法:

@Component({
....
})
class AppComponent {
@ViewChild('button') buttonRef: ElementREf;
...
ngOnInit() {
const overlayRef = overlay.create({
positionStrategy: getOverlayPosition(),
height: '400px',
width: '600px',
});
const userProfilePortal = new ComponentPortal(UserProfile);
overlayRef.attach(userProfilePortal);
}
getOverlayPosition(): PositionStrategy {
this.overlayPosition = this.overlay.position()
.connectedTo(
this.buttonRef,
{originX: 'start', originY: 'bottom'},
{overlayX: 'start', overlayY: 'top'}
)
return this.overlayPosition;
}
...
}

我做了一个例子来向您展示如何使用CDK覆盖服务和类。

叠加演示

如果您更喜欢指令方式,请查看这篇中等文章并检查应用指令方式的示例:

使用 RxJS 的材料 CDK 叠加

最新更新