0

I have a web page and I want to improve it with angular 2, and I would like to use my JS functions in the angular component, this is an example of what I have:

this is my app.component.ts:

import { Component } from '@angular/core';

@Component({
selector: 'myApp',
template: `
    <div>
         <label for="Hour">Start:</label>
         <select id="Hour" class="form-control">
         </select>
    </div>
    `
})
export class MyApp {}

then I have my JS with a function that will fill the select with an inner-html:

function fillValues() {
var d = new Date();
var n = d.getHours();
var options = "";
for (var i = 0; i <= 23; i++) {
    if (i == n) {
        options += "<option id=" + i + " value=" + i + " selected>" + i + "</option>";
    } else {
        options += "<option id=" + i + " value=" + i + ">" + i + "</option>";
    }
}
document.getElementById('Hour').innerHTML = options;
}

and in the index.html I call the component and the JS:

<body>
    <myApp>Loading...</myApp>
    <script src=“assets/js/my_js.js”></script>
</body>

my question is, how can I still use my JS functions and use them inside my components?

Carlos Campos
  • 15
  • 2
  • 6
  • Nothing is stopping you from calling your old functions just like you have before. – Mike Cluck Oct 24 '16 at 20:06
  • I suggest rethinking that code in terms of Angular such that you're binding the options of the select to an array of numbers rather than setting the `innerHTML` of select manually. – Heretic Monkey Oct 24 '16 at 20:48

1 Answers1

3

Since all JS is valid Typescript, you can access your JS function without any problems. As you've included the script file in your index.html you need to tell Typescript that the function exists so you can call it, you can do that by placing;

declare var fillValues: any;

after your import statements. Then you can call the function as normal from you component. You likely want to do that in ngAfterViewInit() in this case, see the Lifecyle Hooks Docs for more details.

If you want to access the <select> element directly in typescript, there are a number of ways you can do that, @ViewChild for example. See this question for more details on how to do that.

Community
  • 1
  • 1
Robert Di Paolo
  • 219
  • 1
  • 11