NativeScript 2 / Angular 2数据绑定[(ngModel)]如何以编程方式更新TextField。

时间:2016-08-11 17:00:28

标签: data-binding angular textfield angular-ngmodel

我想使用angular2数据绑定以编程方式更新TextField文本属性。从here看起来我会在我的布局中设置[(ngModel)] =“email”,然后在我的代码中添加一个属性电子邮件。使用当前设置,我可以在加载时更改文本属性,但是如果我尝试以编程方式从按钮更改文本属性,则单击对电子邮件的更改不会反映在视图的TextField文本属性中。

import { Component, OnInit } from '@angular/core';
import { User }              from '../../shared/user/user';
import { LoginModel }        from '../../model/login/login-model';
import { HttpService }       from '../../services/http/http-service';

@Component({
    selector:'login',
    templateUrl:'pages/login/login.component.html',
    providers: [HttpService]
})

export class LoginComponent implements OnInit {
    email:string = "test@live.com";
    user: User;
    //model: LoginModel;
    constructor(private _httpService: Httpservice) {
        //this.model = new LoginModel();
        this.user = new User();
    } //default constructor

    ngOnInit() {}

    onButtonTap() {
        //alert("onButtonTap clicked ");
        //this._mpixService.register(this.model.user);

        this.email = "Changed@live.com";
        alert("onButtonTap clicked " + this.email);
    }
}

我的观点

<ActionBar title="Login Mpix Tap To Print">
  <ActionItem text="Login" android.systemIcon="ic_menu_share_holo_dark" ios.systemIcon="9" ios.position="right"></ActionItem>
</ActionBar>
<StackLayout>
    <TextField hint="Email Address" keyboardType="email"
        autocorrect="false" autocapitalization="none" [text]="email"></TextField>
    <TextField hint="Password" secure="true" keyboardType="password" 
        autocorrect="false" autocapitalization="none" [(ngModel)]="password"></TextField>

    <Button text="Sign In" (Tap)='onButtonTap()'></Button>
    <Button text="Sign up for Mpix" [nsRouterLink]="['/signup']"></Button>
</StackLayout>

我也尝试过TextField视图属性的变体

<TextField hint="Email Address" keyboardType="email"       autocorrect="false" autocapitalization="none" [text]="email" (emailChange)="email=$event"></TextField>

<TextField hint="Email Address" keyboardType="email"       autocorrect="false" autocapitalization="none" [(ngModel)]="email" [text]=email></TextField>

<TextField hint="Email Address" keyboardType="email"       autocorrect="false" autocapitalization="none" [(ngModel)]="email">{{email}}</TextField>

首次加载界面时,文本字段设置为test@live.com。

2 个答案:

答案 0 :(得分:17)

您可能必须将表单模块从NativeScript导入到NgModule导入数组中:

从&#34; nativescript-angular / forms&#34;中导入{NativeScriptFormsModule};

和NgModule属性

@NgModule({imports:[NativeScriptFormsModule]})

答案 1 :(得分:0)

此问题已通过最近的更新修复。在下面的链接中有更多详细信息,基本上存在一个无关的构建问题,即在我的代码能够运行之前停止代码。在更新了tns-core-modules和nativescript-angular后,它使用了上面的代码。

Nativescript 2.2 exception