Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
deepthan opened this issue Nov 26, 2020 · 0 comments
Open

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

deepthan opened this issue Nov 26, 2020 · 0 comments

Comments

@deepthan
Copy link
Owner

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);
  }
}


@deepthan deepthan changed the title Angular cdk 如何做一个绝对定位 Angular cdk如何做一个以父元素为基准的绝对定位 Nov 26, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant