如何清除表格后提交角度2?

我有一些简单的角2分量与模板。如何清除表单和提交后的所有字段?.我无法重新加载页面。 设置后的数据与 date.setValue('')字段仍然是 touched

import {Component} from 'angular2/core';
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators, Control} from 'angular2/common';


@Component({
selector: 'loading-form',
templateUrl: 'app/loadings/loading-form.component.html',
directives: [FORM_DIRECTIVES]
})


export class LoadingFormComponent {
private form:ControlGroup;
private date:Control;
private capacity:Control;


constructor(private _loadingsService:LoadingsService, fb:FormBuilder) {
this.date = new Control('', Validators.required);
this.capacity = new Control('', Validators.required);
this.form = fb.group({
'date': this.date,
'capacity': this.capacity
});
}


onSubmit(value:any):void {
//send some data to backend
}
}

Load-form. Component. html

<div class="card card-block">
<h3 class="card-title">Loading form</h3>


<form (ngSubmit)="onSubmit(form.value)" [ngFormModel]="form">
<fieldset class="form-group" [class.has-danger]="!date.valid && date.touched">
<label class="form-control-label" for="dateInput">Date</label>
<input type="text" class="form-control form-control-danger form-control-success" id="dateInput"
min="0" placeholder="Enter loading date"
[ngFormControl]="form.controls['date']">
</fieldset>
<fieldset class="form-group" [class.has-danger]="!capacity.valid && capacity.touched">
<label class="form-control-label" for="capacityInput">Capacity</label>
<input type="number" class="form-control form-control-danger form-control-success" id="capacityInput"
placeholder="Enter capacity"
[ngFormControl]="form.controls['capacity']">
</fieldset>
<button type="submit" class="btn btn-primary" [disabled]="!form.valid">Submit
</button>
</form>
</div>
310763 次浏览

另见 https://angular.io/docs/ts/latest/guide/reactive-forms.html(“重置表单标志”部分)

> = RC.6

在 RC.6中,应该支持更新表单模型。创建一个新的表单组并分配给 myForm

[formGroup]="myForm"

will also be supported (https://github.com/angular/angular/pull/11051#issuecomment-243483654)

> = RC.5

form.reset();

在新的表单模块(> = RC. 5)中,NgForm有一个 reset()方法,并且还支持一个表单 reset事件。 Https://github.com/angular/angular/blob/6fd5bc075d70879c487c0188f6cd5b148e72a4dd/modules/%40angular/forms/src/directives/ng_form.ts#l179

< = RC.3

This will work:

onSubmit(value:any):void {
//send some data to backend
for(var name in form.controls) {
(<Control>form.controls[name]).updateValue('');
/*(<FormControl>form.controls[name]).updateValue('');*/ this should work in RC4 if `Control` is not working, working same in my case
form.controls[name].setErrors(null);
}
}

参见

关于这一点有一个新的讨论(https://github.com/angular/angular/issues/4933)。到目前为止,只有一些技巧允许清除表单,比如在提交之后重新创建整个表单: https://embed.plnkr.co/kMPjjJ1TWuYGVNlnQXrU/

在 Angular2RC5中,myFormGroup.reset()似乎起到了作用。

我找到了另外一个解决方案,虽然有点粗糙,但是在有角度的世界里是可以广泛使用的。

由于 * ngIf 指令删除表单并重新创建它,因此可以简单地向表单添加 * ngIf 并将其绑定到某种类型的 formSuccessfullySent变量。这将重新创建表单,从而重置输入控件状态。

Of course, you have to clear the model variables also. I found it convenient to have a specific model class for my form fields. This way i can reset all fields as simple as creating a new instance of this model class. :)

在提交表格后重置表格,你只需调用 this.form.reset(),通过调用 reset()它会:

  1. 将控件和子控件标记为 保持原样
  2. 将控件和子控件标记为 untouched
  3. 将控件和子控件的值设置为 定制价格无效
  4. 更新受影响方的 价值/有效性/错误

Please find this 撤回请求 for a detailed answer. FYI, this PR has already been merged to 2.0.0.

希望这可以有所帮助,让我知道,如果你有任何其他问题关于 Angular2形式。

嗯,现在(2017年1月23日,角度2.4.3)我让它这样工作:

newHero() {
return this.model = new Hero(42, 'APPLIED VALUE', '');
}
<button type="button" class="btn btn-default" (click)="heroForm.resetForm(newHero())">New Hero</button>
import {Component} from '@angular/core';
import {NgForm} from '@angular/forms';
@Component({
selector: 'example-app',
template: '<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
<input name="first" ngModel required #first="ngModel">
<input name="last" ngModel>
<button>Submit</button>
</form>
<p>First name value: \{\{ first.value }}</p>
<p>First name valid: \{\{ first.valid }}</p>
<p>Form value: \{\{ f.value | json }}</p>
<p>Form valid: \{\{ f.valid }}</p>',
})
export class SimpleFormComp {
onSubmit(f: NgForm) {


// some stuff


f.resetForm();
}
}
resetForm(){
ObjectName = {};
}

到角度版本4,你可以使用这个:

this.heroForm.reset();

但是,您可能需要一个初始值,比如:

ngOnChanges() {
this.heroForm.reset({
name: this.hero.name, //Or '' to empty initial value.
address: this.hero.addresses[0] || new Address()
});
}

解决对象引用中的 null 问题很重要。

参考 链接,搜索“重置表单标志”。

在.ts 文件中调用 clearForm();

Try like below example code snippet to clear your form data.

clearForm() {


this.addContactForm.reset({
'first_name': '',
'last_name': '',
'mobile': '',
'address': '',
'city': '',
'state': '',
'country': '',
'zip': ''
});
}

Here is how I do it in Angular 7.3

// you can put this method in a module and reuse it as needed
resetForm(form: FormGroup) {


form.reset();


Object.keys(form.controls).forEach(key => {
form.get(key).setErrors(null) ;
});
}

没有必要打电话给 form.clearValidators()

下面的代码适用于我的角度4

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class RegisterComponent implements OnInit {
registerForm: FormGroup;


constructor(private formBuilder: FormBuilder) { }


ngOnInit() {
this.registerForm = this.formBuilder.group({
empname: [''],
empemail: ['']
});
}


onRegister(){
//sending data to server using http request
this.registerForm.reset()
}


}

我是这么做的,角度8:

获取表单的本地参考信息:

<form name="myForm" #myForm="ngForm"></form>
@ViewChild('myForm', {static: false}) myForm: NgForm;

每当需要重置表单时,调用 resetForm方法:

this.myForm.resetForm();

您将需要 @angular/forms中的 FormsModule来使其工作。请确保将其添加到模块导入中。

This.myForm.reset () ;

这就足够了... 你可以得到想要的输出

要在提交时重置完整的表单,可以使用角度复位()。下面的例子是用角8实现的。 下面是一个订阅表格,我们正在采取电子邮件作为输入。

<form class="form" id="subscribe-form" data-response-message-animation="slide-in-left" #subscribeForm="ngForm"
(ngSubmit)="subscribe(subscribeForm.value); subscribeForm.reset()">
<div class="input-group">
<input type="email" name="email" id="sub_email" class="form-control rounded-circle-left"
placeholder="Enter your email" required ngModel #email="ngModel" email>
<div class="input-group-append">
<button class="btn btn-rounded btn-dark" type="submit" id="register"
[disabled]="!subscribeForm.valid">Register</button>
</div>
</div>
</form>

参考官方文件: https://angular.io/guide/forms#show-and-hide-validation-error-messages