Вы ссылаетесь на тот же объект на cdkPortalOutlet
. На самом деле вам нужен еще один ng-template
с ViewChild
<ng-template #templatePortalContent>Hello, this is a template portal</ng-template>
и файлом ts:
// This is the reference for the ng-template that we added
@ViewChild("templatePortalContent", { static: false }) templatePortalContent: TemplateRef<any>;
// This is the variable that will hold the new template
templatePortal;
constructor(private _viewContainerRef: ViewContainerRef, private cdr: ChangeDetectorRef) {}
ngAfterViewInit() {
this.templatePortal = new TemplatePortal(
this.templatePortalContent,
this._viewContainerRef
);
this.cdr.detectChanges();
}
Это для TemplatePortal.
Если вынужен ComponentPortal, это означает, что если у вас уже есть компонент, вам нужно будет создать портал и назначить его в переменной cdkPortalOutlet
вместо templatePortal
.
this.componentPortal = new ComponentPortal(ComponentPortalExample);
и
<ng-template [cdkPortalOutlet]="componentPortal"></ng-template>
Вы можете проверить здесь для получения дополнительной информации:
Вот демоверсия .