I am trying to create a cart that loads the items dynamically.
Sidebar Component .TS
@ViewChild('cartContainer', { read: ViewContainerRef }) public container;
public componentRef: ComponentRef<any>;
public createComponent(type: any) {
this.container.clear();
const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(CartComponent);
this.componentRef = this.container.createComponent(factory);
this.componentRef.instance.type = type;
this.componentRef.instance.output.subscribe(event => console.log(event));
}
Sidebar Component .HTML
<ng-template #cartContainer></ng-template>
Cart Component .TS
export class CartComponent {
@Input() public type = 'success';
@Output() output = new EventEmitter();
}
Cart Component .HTML
<div id="cd-cart" class="speed-in">
<h1 (click)="output.next('output')">Cart {{ type | json}}</h1>
<ul class="cd-cart-items" style="height: 50vh!important;">
<li *ngFor="let CartItem of CartItems; let index = i;">
<span class="cd-qty">1x</span> CRISTOMORADO MAIZMORADO KG
<div class="cd-price">S/.7.00</div>
<a href="#0" class="cd-item-remove cd-img-replace">Remove</a>
</li>
StoreItems Component .TS
constructor(private _sidebarComponent: SidebarComponent){}
private addItem(key: string, value: object) {
this._sidebarComponent.createComponent(value);
}
StoreItems Component .HTML
<div class="ui-g">
<div *ngFor="let Item of Items" class="ui-g-2">
<a href="javascript:;" (click)="addItem('cart', Items)"><md-card class="item-card">
<div class="ui-g-2-top">{{ Item.Item_Description }}</div>
<div class="ui-g-2-bottom">{{ MONEY_CHAR }}{{ Item.ITEM_Sale_Price | number : '1.2-2'}}</div>
</md-card></a>
</div>
LayoutComponent .HTML
<app-sidebar></app-sidebar>
However, when I call addItem() and it calls createComponent(), it doesn't recognize my ViewChild()
Cannot read property 'clear' of undefined
What am I missing?
addItem?ng-template? can you try withng-container?SidebarComponentcreated and injected? can you maybe create a plunker? it's hard to understand your setup