gpt4 book ai didi

javascript - 为什么我的表格没有正确发送? [(ngModel)] 与发送表单 - Angular 2

转载 作者:行者123 更新时间:2023-11-30 14:27:23 25 4
gpt4 key购买 nike

我要发送一个用于登录屏幕的表单。

因为我将表单本身传递到后端,所以我已经更改了实现以停止绑定(bind)到输入 [(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)]="username"

<input class="form-control" id="username" name="username" type="text" autofocus required
placeholder="username"/>

最佳答案

您的输入需要绑定(bind)。你可以用 react 形式来做到这一点:

应用.ts

import {FormControl} from "@angular/forms";

...
usernameCtrl = new FormControl();

onSubmit()
{
if(this.usernameCtrl.valid)
{
// do something
}
}

应用.html

<input ... [formControl]="usernameCtrl" />

编辑

NgModel 和 NgControl 的区别:Difference between using ng-model and ng-control in angular2?

他们说:

Controls are responsible to get hints about the state of the form or a specific input (valid, pristine, touched, ...). It's commonly used to display validation errors if any.

我认为比 FormControl 更好的解决方案是 FormGroup(如果您有多个输入):

应用.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
}
}
}

应用.html

<form [formGroup]="reactiveForm">
<input ... formControlName="usernameCtrl" name="usernameCtrl"/>
<button [disabled]="!reactiveForm.valid">Submit</button>
</form>

关于javascript - 为什么我的表格没有正确发送? [(ngModel)] 与发送表单 - Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51722035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com