I can dynamically inject my component if I have the viewContainerRef in the component i.e: In my component I declare:
@ViewChild('parent', {read: ViewContainerRef})
And in my template I have
<div #parent></div>
My aim is to have a table which loops through few dataset. When you click on an item, it should load a component dynamically. The problem I am having is when I click on an element and it adds the viewContainerRef, by this point the component does not know what the parent reference is.
Any ideas?
Full code
export class MyComponent {
@Input() someData: any;
@ViewChild('parent', {read: ViewContainerRef})
parent: ViewContainerRef;
childComponent= null;
errorMessage:any;
constructor (private myService: MyService, private componentFactoryResolver: ComponentFactoryResolver) {
this.childComponent = this.componentFactoryResolver.resolveComponentFactory(AnotherComponent);
}
//Show child when row clicked
showChildRow(event:any, trade: Object){
var tableId = jQuery(event.target).closest('table')[0].id;
var table = jQuery('#' + tableId).DataTable();
var tr = jQuery(event.target).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
jQuery('div.slider', row.child()).slideUp( function () {
row.child.hide();
tr.removeClass('shown');
} );
}
else {
// Open this row
this.myService.callSomeMethod("aaaa", "01-Jan-2015", "01-Jan-2017")
.subscribe(
data => this.format(data, row, tr),
error => this.errorMessage = <any>error
)
}
}
//Show child when row clicked
format ( data, row, tr ) {
var childRow = '<div class="slider col-xs-12">'+
'<div #parent></div>';
row.child(childRow).show();
tr.addClass('shown');
jQuery('div.slider', row.child()).slideDown();
this.parent.createComponent(this.childComponent, 0);
component.instance.data= data;
}
}