Angular为什么要将`cdk-overlay-container`添加到body中?
创始人
2024-10-29 23:00:53
0

在 Angular 中,cdk-overlay-container 是 Overlay 模块使用的一个容器,用于显示过渡效果和实现弹出框等组件。将 cdk-overlay-container 添加到 body 是为了确保 Overlay 可以覆盖整个页面,并且不会受到其他元素的影响。

以下是一些代码示例,说明如何手动将 cdk-overlay-container 添加到 body:

app.component.html:


  

app.component.ts:

import { Component, Injector, ViewContainerRef } from '@angular/core';
import { Overlay, OverlayConfig, OverlayContainer } from '@angular/cdk/overlay';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private overlay: Overlay, private injector: Injector, private overlayContainer: OverlayContainer) { }

  showOverlay() {
    const overlayRef = this.overlay.create(this.getOverlayConfig());
    const overlayPortal = new TemplatePortal(this.overlayTemplate, this.viewContainerRef);
    overlayRef.attach(overlayPortal);
  }

  private getOverlayConfig(): OverlayConfig {
    const positionStrategy = this.overlay.position().global().centerHorizontally().centerVertically();
    const overlayConfig = new OverlayConfig({
      positionStrategy,
      hasBackdrop: true,
      scrollStrategy: this.overlay.scrollStrategies.block(),
      panelClass: 'my-overlay-container'
    });
    return overlayConfig;
  }

  get overlayTemplate(): TemplateRef {
    return this.injector.get(TemplateRef);
  }

  get viewContainerRef(): ViewContainerRef {
    return this.injector.get(ViewContainerRef);
  }

}

在上面的代码中,我们通过 Overlay 模块创建了一个 Overlay,并使用 TemplatePortal 将模板渲染到 Overlay 上。需要注意的是,在 getOverlayConfig 方法中,我们指定了一个 CSS 类名 my-overlay-container,这个类

相关内容

热门资讯

德扑之星有猫腻!扑克王辅助工具... 德扑之星有猫腻!扑克王辅助工具(透视)往昔真的有挂(详细辅助解密教程)是一款可以让一直输的玩家,快速...
德扑之星有作弊!云扑克辅助透视... 德扑之星有作弊!云扑克辅助透视(透视)原本是真的有挂(详细辅助必胜教程)1)德扑之星有作弊辅助挂:进...
wpk有外挂!wepoke用模... 自定义wpk有外挂系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅助器,不管你是...
wepower有外挂!wepo... wepower有外挂!wepoke靠谱吗(透视)原生真的有挂(详细辅助详细教程)wepower有外挂...
wpk透视辅助测试!wopok... 一、wpk透视辅助测试简介了解软件请加微:136704302wpk透视辅助测试是一款在线扑克游戏平台...
wpk提高胜率!红龙扑克是真是... wpk提高胜率!红龙扑克是真是假(透视)往昔是真的有挂(详细辅助扑克教程)是一款可以让一直输的玩家,...
德州之星有辅助挂!wepoke... 德州之星有辅助挂!wepoke辅助软件下载链接(透视)原生存在有挂(详细辅助软件教程)是一款可以让一...
wepoke插件!wepoke... wepoke插件!wepoke辅助插件(透视)最初是真的有挂(详细辅助攻略教程)您好,wepoke辅...
wepoke辅助挂!微扑克中牌... wepoke辅助挂!微扑克中牌率(透视)果然存在有挂(详细辅助必备教程);致您一封信;亲爱wepok...
aapoker有外挂!微扑克中... aapoker有外挂!微扑克中牌率(透视)最初是有挂(详细辅助详细教程)1、许多玩家不知道aapok...