1

After struggling with accessing @ViewChild in constructor I've come to an observation I do not understand. It had quite important consequences in my app.

Simplified app.component.ts code to demonstrate the point:

export class MyApp {
myProp: string;

constructor() {
    console.log( this ); //line A
    console.log( this.myProp ); //line B 
    this.myProp = 'my string'; //line C
}

Question is: why does line A output the whole app object WITH myProp set to 'my string' while line B shows myProp as undefined?

In line A this should have myProp as undefined as well since it is only set in line C.

It is all against code order..

Roman C
  • 49,761
  • 33
  • 66
  • 176
Joey
  • 409
  • 1
  • 3
  • 11
  • 1
    There is nothing to do with angular2 here. http://stackoverflow.com/questions/7389069/console-log-object-at-current-state – yurzui Mar 19 '17 at 13:04
  • Yes, I supposed it was more of the way javascript in general is executed but could not find any clear answer. Many thanks, exactly what I stumbled on! – Joey Mar 19 '17 at 13:07
  • How is that related to `@ViewChild()`? – Günter Zöchbauer Mar 19 '17 at 14:15
  • My initial problem was trying to load a page into 'nav' in the constructor. First I referenced it like so: @ViewChild( 'mainNav' ) nav: Nav; In the constructor 'this.nav' was undefined however 'this' had 'nav' property set properly (in console.log()). I solved the problem with ngOnInit hook (realized the view was not ready in the constructor stage) but discovered the 'issue' with the order in question. Sorry if the opening about @ViewChild was confusing. – Joey Mar 19 '17 at 17:01

1 Answers1

0

This is order:

constructor() {
    console.log( this ); //line A
    this.myProp = 'my string'; //line B
    console.log( this.myProp ); //line C 
}
 
Roman C
  • 49,761
  • 33
  • 66
  • 176