deepthan / blog-angular

Angular 笔记
280 stars 58 forks source link

Angular cdk如何做一个以父元素为基准的绝对定位 #114

Open deepthan opened 3 years ago

deepthan commented 3 years ago

Angular cdk 如何做一个绝对定位

1. module中注入overaly模块

import { PortalModule } from "@angular/cdk/portal";
import { OverlayModule } from "@angular/cdk/overlay";

@NgModule({
  imports: [ OverlayModule, PortalModule],
})

2. 组件html

<!--父元素-->
<div
  cdkOverlayOrigin
  #tortelliniOrigin="cdkOverlayOrigin">
</div>

<!--浮动元素-->
<ng-template cdk-portal #tortelliniTemplate="cdkPortal">
  <ul class="right-menu" *ngIf="showRightMenu">
    <li (click)="editName(data)">修改名称</li>
    <li (click)="deleteNode(data)">删除</li>
  </ul>
</ng-template>

3. 组件ts

// 引入需要的包
import { ViewChild } from "@angular/core";
import { Overlay,OverlayOrigin, OverlayConfig, OverlayRef} from "@angular/cdk/overlay";
import { ComponentPortal,Portal,TemplatePortalDirective} from "@angular/cdk/portal";

export class xxx{
 // 获取元素引用
  @ViewChild("tortelliniOrigin") tortelliniOrigin: OverlayOrigin;
  @ViewChild("tortelliniTemplate") tortelliniTemplate: TemplatePortalDirective;

  ngOnInit() {
    // 初始化浮动的元素
    const strategy = this.overlay
      .position()
      .connectedTo(
        this.tortelliniOrigin.elementRef,
        { originX: "center", originY: "bottom" },
        { overlayX: "center", overlayY: "center" }
      );

    const config = new OverlayConfig({ positionStrategy: strategy });
    const overlayRef = this.overlay.create(config);

    overlayRef.attach(this.tortelliniTemplate);
  }
}