3

I cant find out the solve if this problem.

I have 2 components:

@Component({
  selector: 'my-app',
  template : `
   <product *ngFor="let prod of products" [product]='product'>
  `
})
export class App {
    public products =['object',object]; //its only example of products objects array
}

@Component({
      selector: 'product',
      template : `
      <p>{{product.name}}</p>
      `
    })

export class App {
    @Input() product:any;
}

Right now how can i delete one specyfic product component? May be component can do this itself? I check this posts and still dont have any idea Angular 2 - Adding / Removing components on the fly and How to destroy all the Components created using DynamicComponentLoader in angular2?

In app the product list will be downloaded from serwer and displayed like this. I want to add a button to remove single product it self from the list. Right now i have a function which deletes this product from server but i think its a stupid idea to download the list of product again. So i think it will be beter remove it from from the DOM maybe with ElemntRef or ComponentRef

Community
  • 1
  • 1
Przemysław Zamorski
  • 741
  • 2
  • 14
  • 31
  • `products` is just a local copy. If you remove it from there, it's not removed from the server. This doesn't sound at all like a use case to remove the element yourself. In Angular2 the preferred way is to update the model and let directives like `*ngFor`, `*ngIf`, `*ngSwitchCase` do the DOM updating. – Günter Zöchbauer Nov 25 '16 at 10:19
  • I have a funtion which deletes product on server but i dont want to reload a list again. – Przemysław Zamorski Nov 25 '16 at 10:20

1 Answers1

2

Just remove the item from products and the <product> component will be removed by *ngFor.

Besides that, there is no way to remove components added by Angular2. You can only remove components that you added yourself.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • In app the product list will be downloaded from serwer and displayed like this. I want to add a button to remove single product it self from the list. Right now i have a function which deletes this product from server but i think its a stupid idea to download the list of product again. So i think it will be beter remove it from from the DOM maybe with ElemntRef or ComponentRef – Przemysław Zamorski Nov 25 '16 at 10:20
  • See my comment above. There is no need to download again. Just send a command to the server to delete it there and also delete it in the `products` array. This way you don't need to fetch the data again and Angular2 will take care the component gets removed. – Günter Zöchbauer Nov 25 '16 at 10:21
  • This is it ! Thanks You :) – Przemysław Zamorski Nov 25 '16 at 10:34