asdasd
asdasd

Reputation: 7250

How to show a form on a dropdown in angular material?

I want to show a simple form (as shown in image below) as a dropdown when an icon is clicked. I looked into the component list of angular material but I couldn't find any suitable component for this. There is menu but that can't be used in this case.

Does someone know how can I achieve this?

enter image description here

Upvotes: 4

Views: 6295

Answers (2)

G. Tranter
G. Tranter

Reputation: 17958

You can use MatMenu, but you need to do a few things to make it work.

The first is to not use mat-menu-item. This forces styling on the item so that it has a fixed height of what you would expect for a menu item.

The second is to prevent interaction from propagating back to the menu causing it to close whenever you try to use the form. Use the Event.stopPropagation() function on the outer-most parent of your form inside the menu. You might also want to prevent the menu from closing when you click outside it on the backdrop (and add your own close or cancel button). That will look something like:

<mat-menu class="menu-form-wrapper" [hasBackdrop]="false">
  <div (click)="$event.stopPropagation()" (keydown)="$event.stopPropagation()">
    <form class="menu-form">
    ...

You also need to take care of styling issues. Your form container needs to take up the entire menu so that the user can't click outside of it but still on the menu, causing it to close. And you need to override the default padding that MatMenu adds to its mat-menu-content container. This style needs to be in your global style sheet, not in the component style, and it is where you will add your form's layout:

// override mat-menu-content padding
.menu-form-wrapper .mat-menu-content:not(:empty) {
  padding: 0;
}

// layout for the form
.menu-form-wrapper .menu-form {
  display: flex;
  flex-direction: column;
  padding: 24px;
}

Here it is on StackBlitz.

Upvotes: 10

Abhishek Kumar
Abhishek Kumar

Reputation: 2539

If   Menu Api   is not helpful in your case,
then you can use   Dialog Api   with updatePosition and with hasBackdrop: false.

Open Dialog from Component as :

let  dialogRef = this.dialog.open(ExampleDialogComponent, {
        width: '250px',
        data: filterData,
        hasBackdrop: false,
        panelClass: 'filter-popup'
      });

In Dialog Component :

ngOnInit() {
    this.filterData = this.data;
    const rightMostPos = window.innerWidth - Number(this.filterData.left);
    this.dialogRef.updatePosition({ top: `${this.filterData.top}px`,
    right: `${rightMostPos}px`});
  }

Application Code :
https://stackblitz.com/edit/angular-mat-dialog-updated-position?file=app%2Fexample%2Fexample-dialog%2Fexample-dialog.component.ts

Upvotes: 3

Related Questions