2

I am building a web component in Angular. My objective is to evaluate if the consumer of the web component provided a given input, in this case "accessToken". However the input is undefined in ngOnInit(), but prints in ngOnChanges()

    _accessToken;
    @Input('accessToken')
    set accessToken(accessToken: string) {
        this._accessToken = accessToken;
        console.log(accessToken); // This prints the token, but after ngOnInit??
    }

    ngOnInit() {
      console.log(this._accessToken); // Why is this undefined?
    }

    ngOnChanges(changes) {
      console.log(changes); // This prints the token??
    }

Why it's not available in the ngOnInit life-cycle hook, and how do I determine if the user provided the input or not in the most efficient way?

Any ideas are welcome

R. Richards
  • 24,603
  • 10
  • 64
  • 64
DauleDK
  • 3,313
  • 11
  • 55
  • 98
  • I guess it is not defined in ngOnInit hook since it is passed later. In ngOnChanges hook you're logging object which will show you value at the time you're expanding its properties in dev tool console – yurzui May 24 '20 at 12:16
  • how are you passing the input, if you are passing some value directly (no async operation) then you should definitely get the value in ngOnit as ngOnchanges get calls before ngOnit. So if it is like this then you will get the value in ngOnit(). But if you are passing some value like then it will not be available in ngOnit as it will be bind to the value when the async operation complete. You can also check the sequence of console. – Darpan May 24 '20 at 12:30
  • I am passing the value directly - both in parent angular app and “normal” HTML app – DauleDK May 24 '20 at 14:15

1 Answers1

2

I can't believe that this answers the question, but apparently I simply had to change my input from accessToken ==> access_token.

I find out by using the Chrome dev tools, and inspecting the component(!)

enter image description here

This is also explained here:

You should always use lowercase characters.

One of those days - but it works now. Also in ngOnInit()

DauleDK
  • 3,313
  • 11
  • 55
  • 98
  • Hi this is working for me too but using this syntax I can only pass string literals as inputs not the variables themselves. Using your syntax access-token='var' I would get the string "var" not the variable. I tried access-token="{{var}}" but this is not working either. Any suggestions? – B Snow Jan 20 '21 at 07:55
  • Also, if I change my @Input variable to one word like 'name' instead of 'access-token' and use it like this: I am getting the correct value instead of the string literal but now I have the original problem where in ngOnInit() its undefined but in ngOnChanges() it has the value. From what I can gather, depending on the syntax, ngOnInit will run before ngOnChanges or vice versa :( – B Snow Jan 20 '21 at 08:13