-1

I was looking for ways to load styles conditionally in a component. While I was doing that I try'ed the following:

@Component({
    selector:console.log('test',this)||'login-with-password', //logs: undefined
    templateUrl:'./login-with-password.html',
    styleUrls:['./login-with-password.css'],
    preserveWhitespaces:false
})

For my surprise this was logged as undefined. I was wandering how can this be, since the this keyword should always point to something, ether window or null.

In what context does the decorator run that its context is undefined?

TKDev
  • 493
  • 1
  • 4
  • 19
  • "In what context does the decorator run that its context is undefined?" — Did you read this question before asking it? – Ingo Bürk Jun 03 '18 at 07:34
  • A decorator runs in *strict mode*, so `this` is undefined. The trick you've tried to use isn't supported in AOT, so it's not a good idea to do this in Angular. The way it should be done depends on what you're trying to achieve. If you're interested in solving it, consider re-asking the question with your case explained. – Estus Flask Jun 03 '18 at 10:55

1 Answers1

1

@Component is a decorator that just holds the component metadata, defines an angular class as a component.

Window object is the browsers window object, try logging window in your console.log() inside @component() and it will log the window object.

It is not necessary that 'this' keyword should always point to something. In strict mode if the value of 'this' is not set, it will be undefined. this keyword will just hold the reference to an object. It contains the value of the object that invokes the function.

ngOnInit() is the method that is called first time when the component is loaded, you can console.log(this) and you will find all the data of the object that invokes ngOnInit() method.

Avinash
  • 1,245
  • 11
  • 19