Angular2 ngForm不起作用 [英] Angular2 ngForm not working
本文介绍了Angular2 ngForm不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试做一个登录表单组件,但是我无法读取表单数据.
I am trying to do a login form component but I cannot read the form data.
当我尝试在控制台上写用户名时,会写'undefined'.
When I try to write username on the console, 'undefined' writes.
一切似乎都很平常,但是表单数据并没有包含在内.
Everything seems usual but form data does not come to component.
下面是html代码:
<form (ngSubmit)="onSubmit(myForm)"
#myForm="ngForm"
class="form-signin">
<div class="form-group">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text"
id="inputUsername"
name="inputUsername"
class="form-control"
placeholder="User Name"
required>
<input type="password"
id="inputPassword"
name="inputPassword"
class="form-control"
placeholder="Password" >
</div>
<button class="btn btn-lg btn-primary btn-block"
type="submit">Sign in</button>
</form>
组件ts:
@Component({
selector: 'signin',
templateUrl: './signin.component.html',
encapsulation: ViewEncapsulation.None
})
export class SigninComponent implements OnInit{
constructor(){}
ngOnInit(){ }
onSubmit(form: NgForm){
console.log(form.value.inputUsername);
}
}
谢谢.
推荐答案
您需要将ngModel
指令添加到每个表单字段中.这会将表单字段注册到您的表单中.
You need to add the ngModel
directive to each of the form fields. This registers the form fields to your form.
<input type="text"
id="inputUsername"
name="inputUsername"
class="form-control"
placeholder="User Name"
ngModel
required>
这篇关于Angular2 ngForm不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文