Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use external Javascript function in Angular 2 template?

I have a template in the component with 4 div tags. The JavaScript function I want to call, changeValue(), is supposed to change the content of the first div from 1 to Yes!. I'm new to TypeScript and Angular 2, so I'm not sure how I can get the template to interact with the function from dtest2.js:

 /**app.component.ts */

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

@Component({
selector: 'my-app',
template: `
  <div id="boolean"><p id="bv">1</p></div>
  <div id="numeric"><p id="nv">2</p></div> 
  <div id="string"><p id="sv">3</p></div> 
  <div id="enum"><p id="ev">4</p></div>
  `
})

export class AppComponent { }

//dtest2.js

function changeValue(){
  var newVal= "Yes!"; 
  document.getElementById("bv").innerHTML= newVal;
}

changeValue();
<html>
  <head>
    <title>Angular 2 QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">

    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>

    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="file:^html/angular/app/bs.min.js"></script>
    <script src="file:^html/dtest2.js"></script>
    
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
  </head>

  <body>
    <my-app>Loading...</my-app>
  </body>
</html>
like image 804
xdc17 Avatar asked Nov 08 '22 10:11

xdc17


1 Answers

Is there a special reason to use this external js function? It would be better to use Angular's binding methods to solve your problem..

/**app.component.ts */

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

declare function changeValues(anyArgs: string, canBeHere: string) : void;

@Component({
selector: 'my-app',
template: `
  <div id="boolean"><p id="bv">{{booleanValue ? 'Yes' : 'No'}}</p></div>
  <div id="numeric"><p id="nv">2</p></div> 
  <div id="string"><p id="sv">3</p></div> 
  <div id="enum"><p id="ev">4</p></div>
  `
})

export class AppComponent {
    booleanValue: boolean = true;

    constructor() { changeValues(...); }

    anyFunctionToChangeTheValue() {
        this.booleanValue = false;
    }
}
like image 131
slaesh Avatar answered Nov 14 '22 21:11

slaesh