将@Output()与动态添加的组件一起使用

时间:2018-05-17 10:10:35

标签: javascript angular

我正在创建一个购物清单。 它将由两个组成部分组成:shopping-cartshopped-item

购物车有一个按钮,可以在<div>中动态添加新的购物项目。

添加后的购物项目可以标记为有效或未标记,因此我创建了一个更改标记/未标记值的EventEmmiter。 但由于组件是动态添加的,我不知道在购物车组件中将其添加到哪里......

我怎样才能让它像这样工作:

添加购物项目后,它会显示在一个带有标记/未标记值的数组中,当它在购物项目组件中单击时会更改?

干杯!

Shopped-item.ts 档案:

export class ShoppedItemComponent implements OnInit {

  _ref:any;   
  removeObject(){
    this._ref.destroy();
  } 

  @Output() statusChange = new EventEmitter<{status: boolean}>();

  marked;

  unmarkItem () {
    this.marked = !this.marked;
    this.statusChange.emit({status: this.marked});
  }


  constructor() {    
   }

}

Shopping-cart.ts 档案:

export class ShoppingCartComponent implements OnInit {

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

  constructor(
    private resolver: ComponentFactoryResolver
  ) { }

  isMarked = [];

  shoppedItemStatus (statusChange: {status: boolean}) {
    this.isMarked.push({
      status: statusChange.status
    })
  }

  addItem() {
    const shoppedItem = 
      this.resolver.resolveComponentFactory(ShoppedItemComponent);
    const component = this.boughtItems.createComponent(shoppedItem);
    component.instance._ref = component;        
  }

}

Shopping-cart.html 文件:

  <div #boughtItems>
    <button (click)="addItem()">ADD</button>
  </div>

1 个答案:

答案 0 :(得分:1)

为什么要手动创建组件?

我会在视图中使用* ngFor

<div #boughtItems>
  <button (click)="addItem()">ADD</button>
  <div *ngFor="let item of items">
    <app-item-bought xxxx="item" (markToggle)="myFunction(item)"></app-item-bought>
  </div>
</div>

其中xxxx是使用Input(&#39; xxxx&#39;)装饰的ShoppedItemComponent类的字段。 (markToggle)是ShoppedItemComponent中发射器的名称,myFunction(item)是购物车中定义的函数,它将接收触发事件的项目。

希望它有所帮助!