Angular中如何让MatDialog内容跟随对话框尺寸自适应调整?
问题描述
我已调整MatDialog的尺寸,但内容仍沿用原有尺寸,相关示例截图如下:
我检索相关解决方案后得知可通过CSS调整,因此做了如下尝试:
ngOnInit() { this.dialogRef.updateSize('60%', '60%'); } //MatDialogComponent Custom Size
<mat-dialog-content class="many-inputs" style="height:fit-content; width: fit-content;"> <div class="input-container"> <h2>{{model.name}}</h2> </div> <div class="input-container" *ngFor="let category of model.categories"> <h2>{{category}}</h2> <h2 *ngIf="category=='System'">{{model.domains[0]}}</h2> <h2 *ngIf="category=='Web'">{{model.domains[1]}}</h2> <h2 *ngIf="category=='Mobile'">{{model.domains[2]}}</h2> <permissionProject-manager [data]="model" [category]="category" [customers]="data.customers" [allProjects]="data.allProjects" formControlName="permissions"></permissionProject-manager> </div>
调整后对话框尺寸确实发生了变化,但内容无法完全适配对话框大小。我不想使用px手动固定宽高,担心不同屏幕尺寸下显示效果不一致,请问有没有方法可以让内容完全跟随MatDialog的尺寸适配?
解决方案
首先移除mat-dialog-content标签上的style="height:fit-content; width: fit-content;"属性,该属性会让内容宽高优先适配自身内容大小,无法继承父级对话框的尺寸。
接下来通过flex布局实现自适应,步骤如下:
- 调整对话框打开配置(可选,可替换原有
updateSize写法,效果一致)
在调用Dialog打开的位置直接配置尺寸,相比组件内调用updateSize更直观:
const dialogRef = this.dialog.open(你的Dialog组件类名, { width: '60vw', height: '60vh', // vw/vh为相对视口单位,适配不同屏幕尺寸 panelClass: 'custom-fullsize-dialog' });
- 添加适配样式
在全局样式文件styles.css中添加如下规则,或者在Dialog组件的样式文件中添加(需加::ng-deep前缀):
/* 全局styles.css写法 */ .custom-fullsize-dialog .mat-dialog-container { padding: 0; display: flex; flex-direction: column; box-sizing: border-box; } .custom-fullsize-dialog .many-inputs { flex: 1; width: 100%; overflow-y: auto; padding: 1rem; /* 可根据需求调整内边距 */ box-sizing: border-box; } .custom-fullsize-dialog .input-container, .custom-fullsize-dialog permissionProject-manager { width: 100%; box-sizing: border-box; }
如果要保留原有updateSize的写法,只需要把.custom-fullsize-dialog前缀去掉,直接修改.mat-dialog-container的规则即可。
按以上配置后,对话框尺寸会始终保持为视口的60%,内容区域会自动占满对话框的可用空间,内容超出时自动出现纵向滚动条,不会出现适配异常,也不需要固定px单位。
内容的提问来源于stack exchange,提问作者ander99
相关产品推荐
相关产品推荐

