Javascript code not executing within app.component.html

In my app.component.html I have delcared this code:

<script type="text/javascript">
  console.log('testing console')

When I load app.component.html the javascript is not executed as the message ‘testing console’ is not printed to the browser console.

I’m using the Angular version:

Angular CLI: 11.2.0
Node: 14.15.5
OS: darwin x64

Angular: 11.2.0
... animations, cli, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, router
Ivy Workspace: Yes

Package                         Version
@angular-devkit/architect       0.1102.0
@angular-devkit/build-angular   0.1102.0
@angular-devkit/core            11.2.0
@angular-devkit/schematics      11.2.0
@schematics/angular             11.2.0
@schematics/update              0.1102.0
rxjs                            6.6.3
typescript                      4.1.5

I realise executing javascript code within app.component.html could be bad practice. How/can javascript code be executed within an Angular page ?

2 thoughts on “Javascript code not executing within app.component.html”

  1. That’s correct, it’s possible but severely not recommended to run JS that way in an Angular app. You could use the ngOnInit() function in your app.component.ts file like this:

      selector: 'app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    export class AppComponent implements OnInit {
      constructor() { }
      ngOnInit(): void {
        console.log("testing console");

Leave a Comment