Angular Material 6.0.1:如何在卡片类视图内打开Bottom Sheet
让Angular Material 6.0.1的Bottom Sheet显示在卡片内部的解决方案
我之前也碰到过这个问题——官方文档说指定viewContainerRef就能让Bottom Sheet挂载到目标容器,但实际操作时总是没效果。结合你的场景来看,问题主要出在容器引用的正确获取和默认样式的覆盖这两点上,下面一步步来解决:
1. 给卡片添加挂载容器并获取ViewContainerRef
首先得在你的卡片内部定义一个专门用来挂载Bottom Sheet的占位元素,然后通过@ViewChild拿到它的ViewContainerRef:
模板部分(HTML)
在卡片里加一个带模板引用的<div>,放在卡片的底部位置最合适:
<mat-card class="example-card"> <!-- 卡片原有内容 --> <mat-card-content> <p>这是一张测试卡片,点击按钮打开内嵌的Bottom Sheet</p> </mat-card-content> <mat-card-actions> <button mat-button (click)="openBottomSheet()">打开Bottom Sheet</button> </mat-card-actions> <!-- 挂载Bottom Sheet的容器 --> <div #bottomSheetHost></div> </mat-card>
组件类部分(TS)
导入ViewContainerRef和ViewChild,然后获取这个容器的引用:
import { Component, ViewChild, ViewContainerRef } from '@angular/core'; import { MatBottomSheet } from '@angular/material'; // 导入你的Bottom Sheet组件 import { BottomSheetOverviewExampleSheet } from './bottom-sheet-overview-example-sheet'; @Component({ selector: 'bottom-sheet-overview-example', templateUrl: './bottom-sheet-overview-example.html', styleUrls: ['./bottom-sheet-overview-example.css'] }) export class BottomSheetOverviewExample { // 关键:指定read: ViewContainerRef来获取容器引用 @ViewChild('bottomSheetHost', { read: ViewContainerRef }) bottomSheetHost: ViewContainerRef; constructor(private bottomSheet: MatBottomSheet) {} openBottomSheet() { // 打开Bottom Sheet时传入viewContainerRef配置 this.bottomSheet.open(BottomSheetOverviewExampleSheet, { viewContainerRef: this.bottomSheetHost, // 可选:添加自定义面板类,方便后续样式调整 panelClass: 'card-embedded-bottom-sheet' }); } }
2. 覆盖默认样式让Bottom Sheet适配卡片
Angular Material的Bottom Sheet默认是全屏宽度且固定在屏幕底部的,所以必须修改样式让它贴合卡片容器:
在组件的CSS文件里添加以下样式:
/* 针对自定义的卡片内嵌Bottom Sheet调整样式 */ .card-embedded-bottom-sheet { position: absolute !important; bottom: 0; left: 0; right: 0; width: 100% !important; margin: 0; border-radius: 4px 4px 0 0; /* 可选:添加阴影,和卡片风格统一 */ box-shadow: 0 -2px 8px rgba(0,0,0,0.15); }
3. 排查示例无效的常见原因
看你提供的演示场景,大概率是这两个问题导致的:
- 没有指定
{ read: ViewContainerRef }:直接获取模板引用的话,默认拿到的是ElementRef,而不是我们需要的ViewContainerRef - 没覆盖默认样式:即使Bottom Sheet挂载到了卡片里,默认的全屏样式会让它看起来还是在屏幕底部
按照上面的步骤修改后,Bottom Sheet就会乖乖显示在卡片内部的底部了。
内容的提问来源于stack exchange,提问作者Jjj
相关产品推荐
相关产品推荐

