Angular Material mat-menu-item to be the same size as the mat-menu button
我将Angular Material的mat-menu与不同的mat-menu-item一起使用,并且我希望菜单项的列表与按钮的大小相同。
那就是我所拥有的:
而我希望:
我试图使用CSS更改菜单的大小,但是无法正常工作。
CSS:
1 2 | .cdk-overlay-pane {width: 100%;} .mat-menu-panel {width: 100%;} |
HTML:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <button mat-raised-button [matMenuTriggerFor]="menu" class="btn-block btn-blue"> <mat-icon>more_vert</mat-icon> <span fxFlex>OPTION</span> </button> <mat-menu #menu="matMenu"> <button mat-menu-item> <mat-icon>unarchive</mat-icon> <span>First</span> </button> <button mat-menu-item> <mat-icon>file_copy</mat-icon> <span>Second</span> </button> </mat-menu> |
我为我的菜单做了一个StackBlitz HERE。
先感谢您!
编辑:我更改了代码,因为我在引导类" btn-block"中使用了响应式按钮。
使用
1 2 3 4 | ::ng-deep .mat-menu-panel { padding: 0 10px!important; width: 100%!important; } |
查看工作代码
将menuOpened事件用于matMenuTriggerFor并添加宽度运行时
HTML:
1 2 3 4 5 6 | <button mat-raised-button [matMenuTriggerFor]="menu" class="btn-block btn-blue" (menuOpened)="onMenuOpened()" id="button"> <mat-icon>more_vert</mat-icon> <span fxFlex>OPTION</span> </button> |
TS:
1 2 3 4 5 6 7 8 9 10 11 12 | onMenuOpened() { const btn = document.getElementById('revisitSection'); if (btn) { const elems = document.getElementsByClassName('button') as any; // for (let i = 0; i < elems.length; i++) { // elems[i].style.width = `${btn.offsetWidth}px`; // } for (const item of elems) { item.style.width = `${btn.offsetWidth}px`; } } } |
我不建议使用ngDoCheck。 它有更多的性能问题。
我发现一个解决方案确实不干净,但是这里是:StackBlitz HERE
如果有人有CSS解决方案,我很感兴趣。
HTML:
1 2 3 4 5 6 | <button mat-raised-button [matMenuTriggerFor]="menu" class="btn-block btn-blue" id="button"> <mat-icon>more_vert</mat-icon> <span fxFlex>OPTION</span> </button> |
TS:
1 2 3 4 5 6 7 8 9 10 | export class AppComponent implements DoCheck{ ngDoCheck(){ var widthButton=document.getElementById("button").offsetWidth; var elems = document.getElementsByClassName('mat-menu-panel'); for(var i = 0; i < elems.length; i++) { elems[i].style.width = widthButton+"px"; } } } |
CSS:
1 2 | .cdk-overlay-pane {width: 100%!important;} .mat-menu-panel {max-width: 100%!important; min-width: 64px!important;} |
演示: