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
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)
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.