我是 Angular 2 的新手。我正在尝试使用FormBuilder
和FormGroup
创建一个简单的表单。但是由于某种原因,我在视图中的用户名字段中输入的任何内容都没有在我的组件上更新,当我单击提交按钮时看不到新值。我的观点和组件代码如下,有人可以指出我有什么问题吗?
登录.ts
import { Component} from "@angular/core";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
@Component({
selector:"login-page",
templateUrl: "login.html"
})
export class LoginPage {
loginForm : FormGroup;
constructor(formBuilder :FormBuilder) {
this.loginForm = formBuilder.group({
'username':[
'',
Validators.required
]
});
}
validate() : boolean {
if (this.loginForm.valid) {
return true;
}
}
submit() : void {
if (!this.validate()) {
console.info("Invalid input")
}
let control = this.loginForm.controls['username'].value;
console.log(control);
}
}
登录.html
<ion-header style="text-align:center">
<ion-navbar>
<ion-title>Please login</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h3 style="text-align:center">Welcome to your first Ionic app!</h3>
<form class ="list" [formGroup]="loginForm" (ngSubmit)="submit()">
<ion-item class="loginInput center">
<ion-label floating>Email</ion-label>
<ion-input type="text" name='username' ngControl="username" ></ion-input>
</ion-item>
<div class="loginBtn"><button style="width: 140px" ion-button type="submit">Login</button></div>
</form>
</ion-content>
更改
<ion-input type="text" name='username' ngControl="username" ></ion-input>
自
<ion-input type="text" [formControl]="loginForm.controls['username']" ></ion-input>
您需要执行以下更改。
.ts
loginForm : FormGroup;
constructor(formBuilder :FormBuilder) {
this.loginForm = formBuilder.group({
username:['',Validators.required]
});
}
。.html
<form class ="list" [formGroup]="loginForm" (submit)="submit(loginForm)">
<ion-item class="loginInput center">
<ion-label floating>Email</ion-label>
<ion-input type="text" name='username' formControlName="username" ></ion-input>
</ion-item>
<div class="loginBtn">
<button style="width: 140px" ion-button type="submit">Login</button>
</div>
</form>