Open deepthan opened 3 years ago
import { PortalModule } from "@angular/cdk/portal"; import { OverlayModule } from "@angular/cdk/overlay"; @NgModule({ imports: [ OverlayModule, PortalModule], })
<!--父元素--> <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>
// 引入需要的包 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); } }
Angular cdk 如何做一个绝对定位
1. module中注入overaly模块
2. 组件html
3. 组件ts