如何在angular 4中将值从index.html页传递到component.ts文件

时间:2019-04-03 05:27:40

标签: javascript html angular typescript

你好,我是Angular的新手,如何将Index.html文件连接到component.ts?请在下面检查我的代码。我在我的角度index.html文件中创建了一个名为scannerOutput的函数。该功能运行正常。但是此功能很难发送到component.ts。

这是我的INDEX.HTML

........
<script>
.......
 function scannerOutput(s) {      
 alert(s);
}
 </script>
</head>

我认为直接调用该函数到component.ts的另一种方法无法获取该值,因此我选择先调用索引页然后获取它。

在警报“ s”中将显示该值,我想将“ s”值传递到我的component.ts文件。

在这里,我尝试将调用直接连接到component.ts文件:

scannerOutput() {
    scannerOutput();
    function scannerOutput() {    // function definition   
        if (typeof Android !== "undefined" && Android !== null) {
            alert("2nd scan start");
            //console.log("function 1called")
        }
        alert("2nd scan stop");
        console.log("function 3called")
    }
    scannerOutput()

但是它不起作用。在这里,我使用一个android设备扫描项目并将值发送到此处,但是无法将值传递给component.ts,所以我选择了index.html。现在,我在index.html中获得了值,我的问题是我想将该值传输到component.ts文件。

3 个答案:

答案 0 :(得分:0)

您必须将应用程序组件选择器添加到index.HTML文件。通过找到您的应用程序组件来执行此操作。 ts文件夹。 @components()方法中有一个选择器属性。将此复制到index.html文件的正文中。 例如,如果选择器名称是app-root。  应该添加到index.HTML。

答案 1 :(得分:0)

  • 默认情况下,index.html是在Angular中调用的默认html页面,位于index.html加载内-称为app.component.html。

  • 对于Ex:app.component.html包含内容

    欢迎使用App组件

    ,当调用index.html时-在浏览器中显示为“欢迎使用App”组件

  • 结束语,您可以使app.component.ts中的app.component.html值直接显示在index.html

  • For通过“插值”将值从ts传递到HTML内容 例如:在ts类中具有变量name =“ myname”,在html中,可以使用

    {{name}}

    ,其中html和ts驻留在同一组件中。

  • 如果它适合您,别忘了投票。

答案 2 :(得分:0)

通常在Angular中,您不会将代码添加到index.html中。 当使用angular cli创建项目时,您将获得包含以下代码的html:

<body class="cui">
    <div class="content-fluid">
        <main>
           <app-root></app-root>
        </main>
    </div>
</body>

应用程序根选择器将index.html“连接”到应用程序组件组件。 在应用程序组件中,您应该找到4个文件:

  • app-component.ts-这是您的功能所在
  • app-component.html-这是将停靠在选择器所在的索引中的html
  • app-component.css-这将包含您组件的样式
  • app-component.spec.ts-这是您的测试的占位符。

因此,您的函数位于app-component.ts中,从这里开始,您可以通过多种方法来调用它,这取决于您希望何时/如何运行它,我认为您应该将其作为来自您的回调的方式运行html,作为对某些事件的响应: 因此,在您的html文件中,您应该具有:

   <button (click)="yourFunction($event)">

,并且在ts文件中,您应该具有:

yourFunction(arg: any): void {
   ...
}

为了扩展代码,您应该创建更多组件,并将逻辑放在其中,而不是在app组件中。