我有一个要发送给登录屏幕的表格。
由于我将表单本身传递到后端,因此我更改了实现以停止绑定到输入[[ngModel)] ...这通过了我最初编写的原始测试,但是现在实际的应用实施不再有效...
有人可以解释这里的问题吗?我发布的代码只是一个易于理解的示例,因为我的代码更加冗长。
之前
app.ts
username: string;
onSubmit(form: NgForm) {
if (form.valid) {
// do something with this.username...
// this.username will be set to whatever is entered in the input box as it is bound with [(ngModel)]
}
}
app.html
<input class="form-control" id="username" name="username" type="text" autofocus required
placeholder="username" [(ngModel)]="username"/>
之后
app.ts
username: string;
onSubmit(form: NgForm) {
this.username = form.value.username
if (form.valid) {
// do something with this.username...
// this.username should now be what is passed via the form
}
}
app.html 现在不再具有[(ngModel)] =“用户名”
<input class="form-control" id="username" name="username" type="text" autofocus required
placeholder="username"/>
答案 0 :(得分:2)
您的输入需要绑定。您可以使用反应形式来完成它:
app.ts
import {FormControl} from "@angular/forms";
...
usernameCtrl = new FormControl();
onSubmit()
{
if(this.usernameCtrl.valid)
{
// do something
}
}
app.html
<input ... [formControl]="usernameCtrl" />
NgModel与NgControl之间的区别:Difference between using ng-model and ng-control in angular2?
他们说:
控件负责获取有关表单状态或特定输入(有效,原始,已触摸...)的提示。通常用于显示验证错误。
我认为比FormControl更好的解决方案是FormGroup(如果您有多个输入):
app.ts
import {FormBuilder, FormGroup} from "@angular/forms";
...
//decorator
export class SomeClass implements OnInit
{
public reactiveForm = new FormGroup();
constructor(private fb: FormBuilder){}
public ngOnInit()
{
this.reactiveForm = this.fb.group({username: [""]});
}
public onSubmit()
{
if(this.reactiveForm.valid)
{
const raw = this.reactiveForm.getRawValue(); //output -> { username: "blabla"}
// do something with raw
}
}
}
app.html
<form [formGroup]="reactiveForm">
<input ... formControlName="usernameCtrl" name="usernameCtrl"/>
<button [disabled]="!reactiveForm.valid">Submit</button>
</form>