我知道Angular 2目前缺乏一种方法可以轻松地将表单重置为原始状态.我找到了一个类似下面的解决方案来重置表单字段.
有人建议我需要删除控制组并创建一个新的控制组来重建表单作为原始.我很难找到最好的方法来做到这一点.我知道我需要在一个函数中包装表单构建,但是在构造函数中执行此操作时遇到错误.
重建控件组以完全重置表单的最佳方法是什么?
class App {
name: Control;
username: Control;
email: Control;
form: ControlGroup;
constructor(private builder: FormBuilder) {
this.name = new Control('', Validators.required);
this.email = new Control('', Validators.required);
this.username = new Control('', Validators.required);
this.form = builder.group({
name: this.name,
email: this.email,
username: this.username
});
}
onSubmit(value: any): void {
// code that happens when form is submitted
// then reset the form
this.reset();
}
reset() {
for (let name in this.form.controls) {
this.form.controls[name].updateValue('');
this.form.controls[name].setErrors(null);
}
}
}
Run Code Online (Sandbox Code Playgroud) 我在我的页面上有一个表单,当我调用FormGroup.reset()它时将表单类设置为ng-pristine ng-untouched但FormControl.hasError(...)仍然返回truthy.我在这做错了什么?
模板
<form [formGroup]="myForm" (ngSubmit)="submitForm(myForm)">
<mat-form-field>
<input matInput formControlName="email" />
<mat-error *ngIf="email.hasError('required')">
Email is a required feild
</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="password" formControlName="password" />
<mat-error *ngIf="password.hasError('required')">
Password is a required feild
</mat-error>
</mat-form-field>
<button type="submit">Login</button>
</form>
Run Code Online (Sandbox Code Playgroud)
零件
export class MyComponent {
private myForm: FormGroup;
private email: FormControl = new FormContorl('', Validators.required);
private password: FormControl = new FormControl('', Validators.required);
constructor(
private formBuilder: FormBuilder
) {
this.myForm = formBuilder.group({
email: this.email,
password: this.password
}); …Run Code Online (Sandbox Code Playgroud) 我正在开发一个简单的Angular 2应用程序,但我无法重置ngForm但保留默认值:
预期的行为是单击"重置"时,输入框将重置为默认值(在本例中为"默认")以及返回默认值的所有角度特定类(即ng-untouched,ng-pristine,等等)
我所看到的是默认值也被清除,即使我在重置表单后明确设置它也是如此
以下代码段:
HTML:
<form (ngSubmit)="onTrainSearchClick()" novalidate #trainForm="ngForm">
<input type="text" [(ngModel)]="id" name="someId"/>
<button type="button" (click)="reset(trainForm)">Reset</button>
<button type="submit">Search</button>
</form>
Run Code Online (Sandbox Code Playgroud)
TypeScript(省略了导入和@Component):
export class TrainSearchTestComponent implements OnInit {
id: string = 'DEFUALT';
constructor() { }
ngOnInit() { }
onTrainSearchClick(){ }
reset(form: NgForm){
form.resetForm();
this.id = 'DEFUALT';
}
}
Run Code Online (Sandbox Code Playgroud) 例如我有下面的表格。
searchForm = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl('')
})Run Code Online (Sandbox Code Playgroud)
问题是,当我使用searchForm.reset()初始值设置为null而不是空字符串时'',我在FormControl.
我试过做下面的代码并且它有效。问题是,例如我有 20 FormControl,我需要全部输入并初始化它.reset({firstName:'', other20properties..})
this.searchForm.reset(
{
firstName: '',
lastName: ''
}
);Run Code Online (Sandbox Code Playgroud)
有没有办法重置表单并将其所有初始值设置为空字符串''。