kyserslick kyserslick - 2 months ago 10
TypeScript Question

Cannot read property 'createComponent' of undefined using ViewContainerRef

I'm trying to inject dynamicaly a componant to a parent location using @ViewChild but I'm getting error:

Cannot read property 'createComponent' of undefined

on the ReferenceTableComponent componant where I'm trying to inject I have

selector: 'app-reference-table',
templateUrl: './refTable.component.html',
styleUrls: ['./refTable.component.scss']
export class ReferenceTableComponent implements OnInit {

observable: Observable<any>;

@ViewChild('selectorTarget', {read: ViewContainerRef}) selectorTarget;

// colors
@Input() public datas: Array<string>;

public availableColors: Array<string>;

@Input() public nextRow: Array<string>;

@Input() public headList: Array<string>;

public rows: Array<any> = [{}];

public rowIDs: Array<any> = [];

constructor(private _cr: ComponentFactoryResolver, private _viewContainerRef: ViewContainerRef) {

ngOnInit() {

addRow() {
console.log('this.availableColors 2: ', this.availableColors)

computeAvailableColors() {
this.availableColors = _.concat([''], this.datas);
this.rowIDs =, 'color')
this.availableColors = _.difference(this.availableColors, this.rowIDs);
const select: ComponentRef<SelectOptionsComponent> =

select.instance.availableColors = this.availableColors;
select.instance.row = this.rows[0];

on the componant html I have

<td onSelectColor($event) #selectorTarget>

the component I'm trying to inject

selector: 'kia-select-options',
template: `<div><select [(ngModel)]="row.color" (ngModelChange)="sendColorEvent(row, $event)">
// value is a string or number
<option *ngFor="let obj of availableColors">{{obj}}</option>
export class SelectOptionsComponent {

// couleurs
@Input() public availableColors: Array<string>;

@Input() public row: {};

public color: string;

public changed = new EventEmitter();

constructor(private injector: Injector) {

sendColorEvent(row, color) {
this.changed.emit({ color: color, row: row });

Knowing that ReferenceTableComponent is it self lodaded dynamicaly from a parent componant using, and it's working fine

@ViewChild('target', {read: ViewContainerRef}) target;
const factory = this.componentFactoryResolver.resolveComponentFactory(ReferenceTableComponent);
const ref =;

Answer Source

@ViewChild() queries aren't available in ngOnInit() yet. Only when ngAfterViewInit() is called:

ngAfterViewInit() {