【问题标题】:how to use <ng-template> without break change detection?如何在没有中断更改检测的情况下使用 <ng-template>?
【发布时间】:2019-05-23 19:11:36
【问题描述】:

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

上一个值:'名称:未定义'。当前值:“名称: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>

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

【问题讨论】:

标签: angular ng-template


【解决方案1】:

一些生命周期钩子在渲染部分之前被调用 Angular 进程绑定和一些在之后调用

Angular 为应用组件调用 ngAfterViewChecked 生命周期钩子,应用组件的所有绑定都已检查。但是您在检查后添加视图容器

为了避免你可以使用 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

【讨论】:

    【解决方案2】:

    您应该改为使用ngOnInit

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

    因为ngDoCheck 被称为after ngOnInitbefore ngAfterViewInit

    更多关于Lifecycle Hooks的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-14
      • 1970-01-01
      相关资源
      最近更新 更多