[英]Angular Portal cdkPortal directive throw Expression Changed error
我使用 Angular Material Portal 將元素移動到另一個地方。
我使用cdkPortal
和cdkPortalOutlet
。
我不明白為什么 angular 拋出表達式在這個超級簡單的例子中發生了變化
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]'
您將相同的 object 引用到cdkPortalOutlet
。 您實際上需要另一個帶有ViewChild
ng-template
<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>
您可以在此處查看更多信息:
這是演示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.