我正在使用角度2并且使用FormBuilder和FormGroup。在提交表单时,我正在传递FormGroup类型的form.value。
当我要访问我的属性并重新启动lite服务器时,它没有启动应用程序并抛出一个异常,即userName属性未定义为FieldGroup。
代码段是:
import { Component } from '@angular/core';
import { FormBuilder,FormGroup} from '@angular/forms';
import { LoginService } from '../../services/login.service';
@Component({
selector: 'login-selector',
templateUrl: './app/components/login/login.component.html',
})
export class LoginComponent {
form:FormGroup;
constructor(
private formBuilder:FormBuilder){
}
ngOnInit() {
this.form=this.formBuilder.group({
userName:this.formBuilder.control(''),
password:this.formBuilder.control(''),
remember:this.formBuilder.control(''),
textCaptcha:this.formBuilder.control('')
});
}
onSubmit(loginForm:FormGroup){
alert(`UserName is `+loginForm+`
and password is `+loginForm);
}
}
HTML
<form id="loginform" class="form-horizontal" role="form" [formGroup]="form" (ngSubmit) = "onSubmit(form.value)">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="password" ngModel type="password" class="form-control" name="password" placeholder="password" formControlName="password">
</div>
<div class="col-sm-12 controls">
<button type="submit" class="btn btn-primary">Login </button>
<a id="btn-login" href="#" (click)="reset()" class="btn btn-warning">Reset </a>
</div>
如果我添加警报属性正在运行但是在重新启动服务器时它会抛出错误并且必须删除该属性。所以我无法使用表单值
alert(`UserName is `+loginForm.userName+`
and password is `+loginForm.password);
错误是
app/components/login/login.component.ts(50,34): error TS2339: Property 'userName
' does not exist on type 'FormGroup'.
答案 0 :(得分:0)
试试这个:loginForm.value.userName
loginForm.value
包含具有以下所有属性的对象:
{
userName: "asdfasdf",
password: "asdfas"
}
答案 1 :(得分:0)
我通过创建接口并将接口引用传递给表单提交功能
来解决了这个问题interface User{
userName:string,
password:string,
textcaptcha:string,
remember:boolean
}
onSubmit(loginForm:User){
alert(loginForm.userName);
}
重启服务器现在没有抛出任何错误