Angular Portal cdkPortal директива throw Выражение Измененная ошибка - PullRequest
0 голосов
/ 04 ноября 2019

Я использую Angular Material Portal для перемещения элемента в другое место.

Я использую 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
}

Проверьте код здесь: 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]'

1 Ответ

0 голосов
/ 04 ноября 2019

Вы ссылаетесь на тот же объект на 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>

Вы можете проверить здесь для получения дополнительной информации:

Вот демоверсия .

...