3

I have an "Angular2" component "ItemBoard" which is a container of "Item" components. I need to get cart data by remote service first and use it to create Items. I would like to know which lifecycle method in ItemBoard should be used for this action?

ngOnChanges()
ngOnInit()
ngDoCheck()

@Component(selector: '[itemBoard]', templateUrl: "itemBoard.html", directives: const [Item],  viewProviders: const [CartService])
class ItemBoard  {

      List cartItems= [];

      ItemBoard(){}

}

@Component(selector: '[item]', templateUrl: "item.html", directives: const [Item])
class ItemBoard  {

      @Input() List cartItems;


}
Roger Chan
  • 1,293
  • 2
  • 11
  • 24

1 Answers1

1

If you just change data that is used by bindings ngFor, ngIf, ngSwitch, [prop]="field", ... you don't have to care about lifecycle hooks. Just update the data and Angular takes care of the rest. If you update the data before Angular created the binding, Angular won't even notice otherwise change detection takes care of updating the view.

To avoid repeated work, try to do updates as early as possible and only as often as necessary.

If there are repeated updates it might be helpful to collect updates and update the fields Angular binds to with the collected changes at once.
This strategy can be simplified by changing the default change detection strategy to onPush and then notify Angular when "all" changes are applied and it's about time for Angular to update the view (Triggering Angular2 change detection manually).

If you modify the DOM using ElementRef or similar, ngAfterViewInit() is the correct lifecycle hook https://angular.io/docs/ts/latest/api/core/AfterViewInit-interface.html Let Angular complete view creation and then add your customizations.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567