0

I'm creating a shopping list. It will be made out of two components: shopping-cart and shopped-item.

The shopping-cart has a button that dynamically adds a new shopped-item in a <div>.

The shopped-item after being added can be marked as active or unmarked so I created an EventEmmiter that changes the value marked/unmarked. But since the component is added dynamically I don't know where to add it in shopping-cart component...

How can I make it work like this:

After the shopped-item is added it appears in an array with marked/unmarked value that changes when it's clicked in the shopped-item component?

Cheers!

Shopped-item.ts file:

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 file:

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 file:

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

1 Answer 1

1

Why are you creating the components by hand?

I would use a *ngFor in the view

<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>

where xxxx is a field of your class ShoppedItemComponent decorated with Input('xxxx'). (markToggle) is the name of the emitter in ShoppedItemComponent and myFunction(item) is a function defined in the Shopping-cart that will receive the item that has fired the event.

Hope it helps!

Sign up to request clarification or add additional context in comments.

2 Comments

But what should be in the addItem() method?
I don't have all the code, but I guess that in Shopping Cart you will have a list of shopped items (the "items" in the *ngFor). In addItem you only have to add the item to the list and the view will refresh smoothly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.