0

I'm trying to learn how use ng-template by modifying the standard stackblitz.com "Hello" project so that the Hello component is rendered by an ng-template. Unfortunately, it gets a nasty ExpressionChangedAfterItHasBeenCherredError.

Previous value: 'name: undefined'. Current value: 'name: Angular'. It seems like the view has been created after its parent and its children have been dirty checked. Has it been created in a change detection hook?

Can someone explain this can be accomplished without the error?

@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>

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

Skyler
  • 777
  • 1
  • 9
  • 34
  • Good explanation at https://stackoverflow.com/questions/46338790/what-is-the-difference-between-createembeddedview-and-createcomponent-in-angular – rickz Dec 24 '18 at 18:30

2 Answers2

0

You should do it in a ngOnInit instead:

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

Because ngDoCheck is called after the ngOnInit and before the ngAfterViewInit.

More info on Lifecycle Hooks.

Maarti
  • 3,600
  • 4
  • 17
  • 34
0

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

Angular calls the ngAfterViewChecked lifecycle hook for the app component,All the binding for app component already checked.But you are adding the viewcontainer after the check

To avoid you can use ngOnInit lifecycle hook

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

or Use setTimeOut

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

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

Chellappan வ
  • 23,645
  • 3
  • 29
  • 60