从另一个组件动态创建组件

时间:2017-07-21 18:10:38

标签: html angular typescript

我正在尝试创建一个动态加载项目的购物车。

补充工具栏.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));
}

补充工具栏组件.HTML

<ng-template #cartContainer></ng-template>

购物车组件.TS

export class CartComponent {
  @Input() public type = 'success';
  @Output() output = new EventEmitter();
}

购物车组件.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组件.TS

constructor(private _sidebarComponent: SidebarComponent){}

private addItem(key: string, value: object) {
  this._sidebarComponent.createComponent(value);
}

StoreItems组件.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>

但是,当我调用addItem()并调用createComponent()时,它无法识别我的ViewChild()

Cannot read property 'clear' of undefined

我错过了什么?

1 个答案:

答案 0 :(得分:1)

我尝试了类似这样的事情并且它对我来说很好

import { Directive, ViewContainerRef } from '@angular/core';

@Directive({
  selector: '[my-host]',
})
export class MyHostDirective {
  constructor(public viewContainerRef: ViewContainerRef) {
  }
}

import { Component, ViewChild, ComponentFactoryResolver } from '@angular/core';
export class YourComponent{
 @ViewChild(MyHostDirective) myHost: MyHostDirective;
ngAfterViewInit() {
    this.renderDynamicComponents();
  }


  renderDynamicComponents() {
    let component = this.widgetsStoreFactory.getWidgetComponent("ComponentName");
    let componentFactory = this._componentFactoryResolver.resolveComponentFactory(component);
    let viewContainerRef = this.myHost.viewContainerRef;
    viewContainerRef.clear();
    let componentRef = viewContainerRef.createComponent(componentFactory);
    (<IModel>componentRef.instance).YourProperty = "DataToPass";


  }
}


<ng-template my-host>


</ng-template>

最后,请将动态组件添加到模块的entryComponents

https://angular.io/guide/dynamic-component-loader

https://fromjami.com/2017/06/26/load-components-dynamically-at-runtime-in-angular-4/