6

I have following component:

export class AddressListComponent implements AfterViewInit{   
  @Input() districts: District[] = [];

  constructor() { }

  ngAfterViewInit() {
    console.log(this.districts);   } }

So it console logs districts as empty array, but I send it as input non-empty array and it displays well this html:

<a *ngFor = "let district of districts; let i = index"  class="list-group-item clearfix" >
        WORKS
 </a>

So my question is next: when in the lifecycle hook am I able to console log data from districts array? Because I need to change it before displaying on html

mondayguy
  • 973
  • 2
  • 12
  • 34

2 Answers2

4

when in the lifecycle hook am I able to console log data from districts array

All inputs are available in the ngOnInit lifecycle hook for the first time the component is initialized. For the consequent updates use ngOnChanges. Or you can use ngOnChanges only since it's also called when the component is initialized.

You can see it from the order of operations mentioned in the Everything you need to know about change detection in Angular:

1) updates input properties on a child component/directive instance
...
3) calls OnChanges lifecycle hook on a child component if bindings changed
4) calls OnInit and ngDoCheck on a child component (OnInit is called only during first check)

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
3

It should work fine. I think your parent component it's being populating the variable districts after AddressListComponent it's loaded. Check to load your child component before you set the variable districts, or use ngOnChanges instead of ngAfterViewInit (ngOnChangess hooks to every change , and not only to the init of the component)

Sebastian Giro
  • 718
  • 1
  • 7
  • 17
  • 1
    ngOnChanges worked! I found what was the problem. THe problem was that ngOnInit is called BEFORE districts is loaded from server side – mondayguy Jul 03 '17 at 04:50
  • Maybe you can add a callback too, so you can set a loading in the app, and load all the components after that. But yes, it's a pain some of the lifecycle hooks – Sebastian Giro Jul 03 '17 at 06:22