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
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With