I am trying to add a dynamic component to the parent location using @ViewChild, but I get an error:
Unable to read property 'createComponent' undefined
in the ReferenceTableComponent component, where I am trying to insert,
@Component({
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;
@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() {
this.computeAvailableColors();
}
addRow() {
console.log('this.availableColors 2: ', this.availableColors)
this.rows.push({});
}
computeAvailableColors() {
this.availableColors = _.concat([''], this.datas);
this.rowIDs = _.map(this.rows, 'color')
this.availableColors = _.difference(this.availableColors, this.rowIDs);
const select: ComponentRef<SelectOptionsComponent> =
this.selectorTarget.createComponent(
this._cr.resolveComponentFactory(SelectOptionsComponent)
);
select.instance.availableColors = this.availableColors;
select.instance.row = this.rows[0];
}
on the html component i have
<td onSelectColor($event) #selectorTarget>
</td>
the component I'm trying to introduce
@Component({
selector: 'kia-select-options',
template: `<div><select [(ngModel)]="row.color" (ngModelChange)="sendColorEvent(row, $event)">
<option *ngFor="let obj of availableColors">{{obj}}</option>
</select></div>`
})
export class SelectOptionsComponent {
@Input() public availableColors: Array<string>;
@Input() public row: {};
public color: string;
@Output()
public changed = new EventEmitter();
constructor(private injector: Injector) {
}
sendColorEvent(row, color) {
console.log(event)
this.changed.emit({ color: color, row: row });
}
}
Knowing that a ReferenceTableComponent is dynamically dynamically using the parent component and it works great
@ViewChild('target', {read: ViewContainerRef}) target;
const factory = this.componentFactoryResolver.resolveComponentFactory(ReferenceTableComponent);
const ref = this.target.createComponent(factory);