2

I am using angular 4 in visual studio code. I want to include a javascript function in my code .

home.component.html

 <html>
 <body>

 <button onclick="myFunction()">Click me</button>

 <p id="demo"></p>

 <script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
  </script>

</body>
</html>

But when i clicking on the button, then its showing error : "Uncaught ReferenceError: myFunction is not defined at HTMLButtonElement.onclick"

2
  • Why do declare a function in HTML instead of component? Commented Oct 30, 2018 at 4:40
  • 1
    you don't need html tag inside your component and angular has a way to implement events. Check this:angular.io/guide/user-input Commented Oct 30, 2018 at 4:40

2 Answers 2

1

You can also use script file into your angular project.

  1. create js file and put your script code into it, and put that js file into assets folder.
  2. Now goto root directory of your angular app, there you can find a file name .angular-cli.json

Now edit that file, find "scripts" and write "script": ["assets/your_script_file.js"].

Now you can call the functions written in that script in your html file.

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

Comments

0

You dont need to write javascript code in HTML file in angular.

There is seprate typescript file withextension .ts where you can put your javascript code in typescript style.

Use below structure for above code in angular :

home.component.html

 <button (click)="myFunction()">Click me</button>
 <p>{{demo}}</p>

home.component.ts

import {Component} from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
  providers: []
})
export class AppComponent {
 public demo: string;

myFunction(){
this.demo="Hello World";
}
}

Code online :https://stackblitz.com/edit/angular-gwrvbn?file=src%2Fapp%2Fapp.component.ts

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.