我正在尝试在div容器中打开材料底页,默认情况下它作为主体内的最后一个元素打开。
看着documentation,我需要使用viewContainerRef
,但我无法使它工作。
这与我要执行的操作类似:
app.component.html:
...
<div #container></div>
...
app.component.ts:
export class AppComponent implements AfterViewInit {
@ViewChild('container', { read: ViewContainerRef }) _container;
...
constructor(
private bottomSheet: MatBottomSheet,
) {}
ngAfterViewInit() {
this.bottomSheet.open(MySheetComponent, {
panelClass: 'my-modal',
viewContainerRef: this._container,
});
}
}
但是似乎没有任何改变。
任何帮助将不胜感激。
提前感谢
[[0]选项的真正含义似乎有误解。
[在查看了角材料的代码(v。8.x)之后,使用viewContainerRef
创建了MatBottomsheet
:
ComponentPortal
源代码:const containerPortal =
new ComponentPortal(MatBottomSheetContainer, config.viewContainerRef, injector);
const containerRef: ComponentRef<MatBottomSheetContainer> = overlayRef.attach(containerPortal);
https://github.com/angular/components/blob/master/src/material/bottom-sheet/bottom-sheet.ts#L140是一个门户,在附加时实例化某些组件。-文档:ComponentPortal
https://material.angular.io/cdk/portal/api#ComponentPortal
export declare class ComponentPortal<T> extends Portal<ComponentRef<T>> {
constructor(
component: ComponentType<T>,
viewContainerRef?: ViewContainerRef | null,
injector?: Injector | null,
componentFactoryResolver?: ComponentFactoryResolver | null
);
在哪里:
/ *** [可选]附加组件应位于Angular的logical组件树中的位置。*这与组件renders的位置不同,后者由PortalOutlet确定。*当主机位于Angular应用程序上下文之外时,源是必需的。* /
现在,我们真正需要定制的是viewContaineRef
,它是:
容器元素,其中所有单个叠加层元素都位于呈现。默认情况下,叠加层容器直接附加到文档正文。
docs:OverlayContainer
技术上可以提供custom覆盖容器,但是不幸的是,这会产生新的问题:
[https://material.angular.io/cdk/overlay/overview#the-overlay-container,MatBottomSheet
和MatDialog
组件使用相同的OverlayContainer,因此所有对话框和小吃栏将在此自定义容器中打开。
如果您真的想使用此自定义容器,我已改编了一个位于MatSnackbar
的解决方案。
将以下提供程序添加到应用程序模块:
https://github.com/angular/components/issues/7764#issuecomment-337335591
import {OverlayContainer} from '@angular/cdk/overlay';
@NgModule({
// ..
providers: [
{ provide: OverlayContainer, useFactory: () => new AppOverlayContainer() },
]
}}
在哪里:
AppOverlayContainer
这里是堆栈闪电战:export class AppOverlayContainer extends OverlayContainer {
constructor() {
super(undefined);
}
protected _createContainer(): void {
const container: HTMLDivElement = document.createElement('div');
container.classList.add('app-overlay-container');
const element: Element | null = document.querySelector('#content-container');
if (element !== null) {
element.appendChild(container);
this._containerElement = container;
}
}
}