2

I understand and use often the @ViewChild, but what's the {read} prop used for?

as in: @ViewChild('putStuffHere', {read: ViewContainerRef}) putStuffHere;

see code below:

import {Component, ViewChild, ViewContainerRef, ComponentResolver} from '@angular/core';

@Component({
  selector: 'my-component',
  template `<h1>my-component</h1>`
})
class MyComponent{}

@Component({
  selector: 'my-app',
  template: `
    <h2>Above</h2>
    <div #putStuffHere></div>
    <h2>Below</h2>
  `
})
export class AppComponent {
  @ViewChild('putStuffHere', {read: ViewContainerRef}) putStuffHere;

  constructor(
      public view:ViewContainerRef,
      public compResolver:ComponentResolver
  ){}

  ngAfterViewInit(){
    this.compResolver.resolveComponent(MyComponent)
      .then(factory => {
        this.putStuffHere.createComponent(factory);    
      })

  }
}

regards

Sean

born2net
  • 24,129
  • 22
  • 65
  • 104

1 Answers1

3

It allows having access to a ViewContainerRef instance instead of an ElementRef one.

Here is a sample:

@ViewChild('putStuffHere') putStuffHere1:ElementRef;
@ViewChild('putStuffHere', {read: ViewContainerRef}) putStuffHere2:ElementRef;
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360