【问题标题】:How to get TextField value from HTML file to TypeScript file?如何从 HTML 文件中获取 TextField 值到 TypeScript 文件?
【发布时间】:2018-05-03 08:27:35
【问题描述】:

我是 nativescript 的新手。我想将用户数据存储在我的手机中。为此,我使用了 Couchbase 数据库。现在我的要求是在单击保存按钮时获取 TextField 值。 `

<TextField hint=" firstName " [text]="_fname ">

</TextField>
<TextField hint="lastname " [text]="_lname ">

</TextField>

<button (tap)="save()" class="btn btn-primary active" text="Save"></button>

`

在上面我需要在按钮单击时获取两个 TextField 值。 请解释如何从文本字段访问当前值。提前致谢。

【问题讨论】:

    标签: html angular2-nativescript


    【解决方案1】:

    解决此问题的最佳方法是通过双向数据绑定。您需要做的第一件事是将NativeScriptFormsModule 添加到NgModule 导入列表中,如下所示。

    app.module.ts

    import { NgModule } from "@angular/core";
    import { NativeScriptFormsModule } from "nativescript-angular/forms";
    import { NativeScriptModule } from "nativescript-angular/nativescript.module";
    
    import { AppComponent } from "./app.component";
    
    @NgModule({
      imports: [
        NativeScriptModule,
        NativeScriptFormsModule
      ],
      declarations: [AppComponent],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    然后您需要更新您的组件.html 文件以使用双向数据绑定。这会将指定元素绑定到您在组件的 .ts 文件中拥有的属性。

    <TextField hint=" firstName " [(ngModel)]="_fname "> </TextField>
    <TextField hint="lastname " [(ngModel)]="_lname "> </TextField>
    
    <button (tap)="save()" class="btn btn-primary active" text="Save"></button>
    

    最后,确保表单的 .ts 文件中有 _fname_lname 属性。

    export class SomeComponent {
        _fname = "";
        _lname = "";
    
        save() {
            console.log(this._fname);
            console.log(this._lname);
            // Send values to your DB
        }
    }
    

    【讨论】:

    • 正是我发现了我的问题。我忘了添加 app.module.ts。现在它正在工作。没有人解释我们必须在 app.modules.ts 中进行更改。感谢您的回答。
    • 我忘记在 app.module.ts 中添加这一行 import { NativeScriptFormsModule } from "nativescript-angular/forms";
    猜你喜欢
    • 1970-01-01
    • 2017-02-19
    • 2011-06-03
    • 2021-11-22
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多