Javascript 角度入口cdkPortal指令抛出表达式已更改错误

Javascript 角度入口cdkPortal指令抛出表达式已更改错误,javascript,angular,angular-material,Javascript,Angular,Angular Material,我使用角材质门户将元素移动到另一个位置 我使用cdkPortal和cdkPortalOutlet 我不明白为什么在这个超级简单的例子中角度投掷表达式发生了变化 import { Component, ViewChild } from '@angular/core'; import { CdkPortal } from '@angular/cdk/portal'; @Component({ selector: 'my-app', templateUrl: './app.component

我使用角材质门户将元素移动到另一个位置

我使用
cdkPortal
cdkPortalOutlet

我不明白为什么在这个超级简单的例子中角度投掷表达式发生了变化

import { Component, ViewChild } from '@angular/core';
import { CdkPortal } from '@angular/cdk/portal';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  @ViewChild(CdkPortal, { static: false }) portal: CdkPortal
}
在此处检查代码:

打开控制台查看错误:

错误:ExpressionChangedTerithasBeenCheckedError:检查后,表达式已更改。上一个值:“门户:未定义”。当前值:“门户:[对象]”

您正在将同一对象引用到
cdkPortalOutlet
。实际上,您需要另一个
ng模板及其
ViewChild

<ng-template #templatePortalContent>Hello, this is a template portal</ng-template>


您可以查看更多信息:


以下是。

您应该在此处包含代码段和控制台错误,并更准确地说明您不了解的部分错误错误:ExpressionChangedTerithasBeenCheckedError:Expression在检查后已更改。上一个值:“门户:未定义”。当前值:“门户:[对象]”。在您的演示中,您遇到了相同的问题,控制台中出现了相同的错误表达式已更改“您现在可以检查答案+演示”。您需要添加
cdr.detectChanges()
来手动触发更改检测。你可以找到更多信息
// 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();
}
this.componentPortal = new ComponentPortal(ComponentPortalExample);
<ng-template [cdkPortalOutlet]="componentPortal"></ng-template>