Carlos Campos Carlos Campos - 1 month ago 5
TypeScript Question

how to implement a js function in an Angular 2 component

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?

Answer

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 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.