keep mat-menu open angular

2019-05-10 09:30发布

问题:

I am trying to use checkbox options in a menu, but I need to keep the menu open until the user is finished selecting options. I am using the latest version of Angular. Thank you in advance!

I have combined the nested mat-menu from here with checkboxes:

What I have tried, but the menu closes after a checkbox is selected:

<mat-menu #worldtest="matMenu" md-prevent-menu-close="md-prevent-menu-close">
     <section><mat-checkbox class="example-margin" [(ngModel)]="checked">Checked</mat-checkbox></section>
     <section><mat-checkbox class="example-margin" [(ngModel)]="indeterminate">Indeterminate</mat-checkbox></section>
</mat-menu>

回答1:

When you use a checkbox (or any interactive element that responds to clicks) on a mat-menu, and you don't want the menu to close when you click it, you need to prevent the menu from receiving the click event by stopping it with MouseEvent.stopPropagation(). Try something like this:

<mat-checkbox (click)="$event.stopPropagation()">Check Me</mat-checkbox>

The md-prevent-menu-close feature is from the old Angular Material for AngularJS - the 'latest version' of Angular Material (v6) doesn't have that feature. Angular Material (v1.x for AngularJS) and Angular Material2 (v2/5/6 for Angular) are not interchangeable.