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

2 Answers 2

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)

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

6 Comments

@mondayguy, try ngOnChanges but something is wrong with your setup because inputs should be avalaible in ngOnInit. Maybe add some more information to your question details
@mondayguy Please reproduce it. You are doing something wrong or you didn't provide enough information
ngOnChanges worked! I found what was the problem. THe problem was that ngOnInit is called BEFORE districts is loaded from server side
@mondayguy, okay, maybe consider accepting my answer then
sorry, I just +1 your answer, Sebastian gave correct answer too. Thank you on more time
|
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)

2 Comments

ngOnChanges worked! I found what was the problem. THe problem was that ngOnInit is called BEFORE districts is loaded from server side
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

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.