Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 @Input and lifecycle hook

Tags:

angular

input

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

like image 377
mondayguy Avatar asked Jul 03 '17 04:07

mondayguy


People also ask

What are lifecycle hooks in Angular 2?

Angular 2 - Lifecycle Hooks. Angular 2 application goes through an entire set of processes or has a lifecycle right from its initiation to the end of the application. The following diagram shows the entire processes in the lifecycle of the Angular 2 application. Following is a description of each lifecycle hook.

Do all lifecycle methods need to be implemented in angular?

There are a few who only execute once after component initialization. All lifecycle methods are available from @angular/core. Although not required, Angular recommends implementing every hook. This practice leads to better error messages regarding the component.

How do I respond to events in the angular lifecycle?

Respond to events in the lifecycle of a component or directive by implementing one or more of the lifecycle hook interfaces in the Angular core library. The hooks give you the opportunity to act on a component or directive instance at the appropriate moment, as Angular creates, updates, or destroys that instance.

How do I use hook methods in angular?

After your application instantiates a component or directive by calling its constructor, Angular calls the hook methods that you have invoked at the appropriate point in that instance's lifecycle. Angular executes hook methods in the following order. You can use it to perform the following types of tasks.


1 Answers

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)

like image 62
Max Koretskyi Avatar answered Nov 05 '22 05:11

Max Koretskyi