在Angular 7中,如果你在使用Angular CDK的Portal时遇到了"错误 必须提供一个用于附加的门户",通常是因为你没有提供一个用于附加的门户。
要解决这个问题,你需要确保你在使用Portal时提供了一个正确的门户。
以下是一个示例代码,展示了如何使用Angular CDK Portal并提供一个门户:
npm install @angular/cdk
import { Component, ViewChild, TemplateRef, ViewContainerRef } from '@angular/core';
import { CdkPortal, CdkPortalOutlet } from '@angular/cdk/portal';
TemplateRef
和ViewContainerRef
,并使用@ViewChild
装饰器将其与HTML模板中的相应元素进行关联:@Component({
selector: 'app-example',
template: `
This is the content of the portal
`,
})
export class ExampleComponent {
@ViewChild('portalContent', { static: true }) portalContent: TemplateRef;
@ViewChild('portalContainer', { read: ViewContainerRef, static: true })
portalContainer: ViewContainerRef;
}
CdkPortal
和CdkPortalOutlet
来创建并附加一个门户:export class ExampleComponent {
@ViewChild('portalContent', { static: true }) portalContent: TemplateRef;
@ViewChild('portalContainer', { read: ViewContainerRef, static: true })
portalContainer: ViewContainerRef;
ngAfterViewInit() {
const portal = new CdkPortal(this.portalContent);
this.portalContainer.attach(portal);
}
}
通过这种方式,你就可以将portalContent
模板的内容附加到portalContainer
元素中。
请注意,在ngAfterViewInit
生命周期钩子中附加门户是很重要的,因为在这个时候模板和视图容器已经准备好了。
希望这个例子能帮助你解决"错误 必须提供一个用于附加的门户"的问题!