console.log not working in Angular2 Component (Typescript)

It’s not working because console.log() it’s not in a “executable area” of the class “App”.

A class is a structure composed by attributes and methods.

The only way to have your code executed is to place it inside a method that is going to be executed. For instance: constructor()

console.log('It works here')

@Component({..)
export class App {
 s: string = "Hello2";
            
  constructor() {
    console.log(this.s)            
  }            
}

Think of class like a plain javascript object.

Would it make sense to expect this to work?

class:  {
  s: string,
  console.log(s)
 }

If you still unsure, try the typescript playground where you can see your typescript code generated into plain javascript.

https://www.typescriptlang.org/play/index.html

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)