0

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

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

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 ?

1 Answer 1

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:

@Component({
  selector: 'app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  

  constructor() { }

  ngOnInit(): void {
    console.log("testing console");
  }

}

Sign up to request clarification or add additional context in comments.

1 Comment

As an addition: depending on your use case on when you want to execute the code, you can also use other Lifecycle hook interfaces. Check this documentation for that You could also put it in the constructor, but I'm not sure whether that's recommended or not.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.