我是 CDK 覆盖层/门户的新手。我根据CDK docs中的示例代码创建了一个组件。我删除了 templatePortal 和 domPortal 的示例代码,以便集中精力讨论 componentPortal。我现在正在尝试弄清楚如何删除在覆盖层中创建的组件。这是一个Stackblitz 链接。我已经搜索了互联网和在线文档,但还没有找到这种程序化删除的解决方案或示例(只有单击覆盖层的示例)。
在“父级”中,我有一个按钮调用一个方法来尝试删除或销毁创建的子级:
<button (click)="destroyRef()" style="background-color: orange">DESTROY</button>
在家长中,我正在尝试这样的事情:
export class CdkPortalOverviewExample implements AfterViewInit {
private parentElement: HTMLElement;
componentPortal: ComponentPortal<ComponentPortalExample> =
new ComponentPortal(ComponentPortalExample);
overlayRef: OverlayRef;
componentRef: ComponentRef<any>;
constructor(private overlay: Overlay, private cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
this.parentElement = document.getElementById('parentId')!;
this.overlayRef = this.overlay.create();
// this.overlayRef = this.overlay.create(this.getOverlayConfig());
this.componentRef = this.overlayRef.attach(this.componentPortal);
const element = this.componentRef.location.nativeElement;
}
destroyRef() {
// PROBLEM 1: these lines are not causing the component to be destroyed.
this.overlayRef.detach();
this.componentRef.destroy();
// this.cdr.markForCheck();
console.log('destroy() called');
}
这是创建的“子”组件:
@Component({
selector: 'component-portal-example',
template: `
<button (click)="youClickedMe('HELLO WORLD')">
CLICK ME
</button>
`,
standalone: true,
})
export class ComponentPortalExample {
youClickedMe(event: any) {
console.log('You clicked me', event);
this.optionSelected.emit('YOU CLICKER!');
}
}
注意 - 在我的示例中,由于某种原因我得到了两个实例化。左上角的那个是 div.cdk-overlay 中的那个。我不明白为什么创建的孩子会出现在两个地方。但是,这并没有发生在我计算机上的应用程序中,所以这不是我主要关心的问题。但是,如果您也理解这一点,也请随时指出该解决方案。 谢谢。
看到您正在使用
document.getElementById('parentId')
但您有一个模板引用变量
//your code
<div class="example-portal-outlet" #parentId>
</div>
//should be
<div class="example-portal-outlet" id="parentId">
</div>
另请参阅您使用
<ng-template [cdkPortalOutlet]="componentPortal"></ng-template>
如果您想手动附加,则不需要
你的分叉堆栈闪电战