user9315861
user9315861

Reputation:

How to use CDK overlay while leaving an existing component in the foreground?

The Angular Material CDK library provides various features including overlays. All the examples I can find show how to display a new component on top of the overlay. My goal is a little different. I want to display an existing component (one of several on the screen) on top of the overlay.

The behavior I have in mind is that when the user goes into a kind of editing mode on a particular object, the component representing that object would sort of "float" on top of an overlay, until editing is done or cancelled.

Is there any straightforward way to do that? It seems that the cdkConnectedOverlay directive might be useful, but I can't figure out how to make it work.

Upvotes: 2

Views: 12874

Answers (1)

Cristian Martinez
Cristian Martinez

Reputation: 178

Angular CDK Provides you two ways to achieve that (Directives and Services).

Using the Overlay service you will need to call the create method passing the positionStrategy prop:

@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;
    }

    ...
}

I made an example to show you how to use the CDK overlays services and classes.

Overlay demo

If you prefer the directive way Look at this medium article and check the examples applying the directive way:

Material CDK Overlay with RxJS

Upvotes: 4

Related Questions