Angular Portal cdkPortal指令抛出表达式更改错误

我使用Angular Material Portal将元素移动到另一个位置。

我使用cdkPortalcdkPortalOutlet

我不明白为什么在这个超级简单的示例中角度抛出表达式会发生变化

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
}

在此处检查代码: https://stackblitz.com/edit/angular-f6sb21

打开控制台以查看错误:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'portal: undefined'. Current value: 'portal: [object Object]'
Venus0808 回答:Angular Portal cdkPortal指令抛出表达式更改错误

您将同一对象引用到cdkPortalOutlet。您实际上还需要另一个ng-template

ViewChild

并在ts文件中:

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

这是用于TemplatePortal的。

如果您需要一个ComponentPortal,则意味着如果您已经有一个组件,则需要创建门户并将其分配在// 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(); } 而不是cdkPortalOutlet变量中。

templatePortal

this.componentPortal = new ComponentPortal(ComponentPortalExample);

您可以检查here以获得更多信息:

这里是demo

本文链接:https://www.f2er.com/3170124.html

大家都在问