如何在没有中断更改检测的情况下使用 <ng-template>?

how to use <ng-template> without break change detection?

我正在尝试通过修改标准 stackblitz.com "Hello" 项目来学习如何使用 ng-template,以便 Hello 组件由 ng-template 呈现。不幸的是,它得到了一个讨厌的 ExpressionChangedAfterItHasBeenCherredError。

前一个值:'name: undefined'。当前值:'name: Angular'。看起来该视图是在其父项及其子项经过脏检查后创建的。是否已在更改检测挂钩中创建

有人可以解释一下这可以在没有错误的情况下完成吗?

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

  constructor(private _vcr: ViewContainerRef) { }

  ngAfterViewInit() {
    this._vcr.createEmbeddedView(this.tpl);
  }

}

app.component.html:

<ng-template #tpl>
    <hello name="{{ name }}"></hello>
</ng-template>

link:https://stackblitz.com/edit/angular-48ptik?file=src%2Fapp%2Fapp.component.html

您应该在 ngOnInit 中执行此操作:

  ngOnInit() {
    this._vcr.createEmbeddedView(this.tpl);
  }

因为 ngDoCheckngOnInit 之后 ngAfterViewInit 之前 被调用。

有关 Lifecycle Hooks 的更多信息。

Some of Lifecycle hooks are called before the rendering part when Angular processes bindings and some are called after

Angular 为应用程序组件调用 ngAfterViewChecked 生命周期挂钩,应用程序组件的所有绑定已经 checked.But 您正在检查后添加视图容器

为了避免你可以使用 ngOnInit 生命周期钩子

ngOnInit() {
    this._vcr.createEmbeddedView(this.tpl);
  }

或使用 setTimeOut

ngAfterViewInit() {
    setTimeout(()=>this._vcr.createEmbeddedView(this.tpl))
  }

参考:https://blog.angularindepth.com/a-gentle-introduction-into-change-detection-in-angular-33f9ffff6f10