Validation 如何在表单提交后在Angular 2中重置验证
我有一些简单的验证测试表。我的验证在提交表单时工作正常 HTMLValidation 如何在表单提交后在Angular 2中重置验证,validation,angular2-forms,Validation,Angular2 Forms,我有一些简单的验证测试表。我的验证在提交表单时工作正常 HTML <section> <form (ngSubmit)="savePerson()" #personForm="ngForm"> <div> <label for="name">Name: </label> <input type="text" name="name" [(ngModel)]="person.name
<section>
<form (ngSubmit)="savePerson()" #personForm="ngForm">
<div>
<label for="name">Name: </label>
<input type="text" name="name" [(ngModel)]="person.name" required #name="ngModel" >
<div [hidden]="name.valid || name.pristine" class="error">
Name is required.
</div>
</div>
<div>
<label for="weight">Weight: </label>
<input type="number" name="weight" [(ngModel)]="person.weight" min="20" #weight="ngModel">
</div>
<div *ngIf="weight.errors && (weight.dirty || weight.touched)" class="error">
<p [hidden]="!weight.errors.min">
Weight must be higher than a feather's. {{weight.value}} is way too low.
</p>
<p [hidden]="!weight.errors.max">
Weight can't be higher than a Rancor's. {{weight.value}} is too high
</p>
</div>
<div>
<label for="height">Height: </label>
<input type="number" name="height" [(ngModel)]="person.height">
</div>
<div>
<label for="profession">Profession: </label>
<select name="proffesion" [(ngModel)]="person.proffesion" #proffesion="ngModel" min=1>
<option [ngValue]="0">Select Proffession</option>
<option *ngFor="let p of allproffesion" [value]="p.id">{{p.title}}</option>
</select>
</div>
<div>
<p>{{message}}</p>
<button type="submit" [disabled]="!personForm.form.valid">Save</button>
</div>
</form>
</section>
<button (click)="gotoPeoplesList()">Back to peoples list</button>
提交表格后:
我的问题是在提交表单后,我想重置验证。我不想重置表单,尽管。因为我想显示成功插入的消息
在savePerson方法中,应该调用FormGroup markAsPristine方法 该方法的官方文件如下:
要访问component类中的FormGroup对象,可以使用@ViewChild。如果要清除表单控件的
触摸的
和脏的
标志,可以使用FormGroup
操作。这将在内部将所有子体标记为原始的和未触及的
重置方法还获取表单状态值的映射,以便您可以保留所有(或上一次表单提交中的部分)值。看
也从你的问题:
因为我想显示成功插入的消息
表单重置不会影响您显示此信息,因为
消息
属性不是表单的一部分-它只是组件上的常规属性。我必须更改代码的结构才能使表单组正常工作。Formgroup是否比我选择的方法更好?我认为你不必改变你的方法,你可以继续使用模板驱动的表单,并调用personForm.reset()
你的第二个链接(指向示例)不会转到显示示例的页面。
export class AddPersonComponent {
person : Person = { id : 0, height : 0, weight : 0, name : "", proffesion : 0};
message : String = "";
allproffesion : Proffesion [];
constructor(private route: ActivatedRoute, private router: Router, private peopleService:PeopleService){
this.getAllProffession();
}
getAllProffession(){
this.peopleService.getAllProffession().subscribe(i=>this.allproffesion = i);
}
gotoPeoplesList(){
let link = ['/'];
this.router.navigate(link);
}
savePerson(){
this.peopleService.addPerson(this.person).subscribe(i=>{ this.reset(i)});
}
reset(person1 : Person){
if(person1.id != 0){
console.log(this.person);
this.message = "Person Added Successfully.!";
this.person = { id : 0, height : 0, weight : 0, name : "", proffesion : 0};
}
else{
this.message = "Something Went Wrong";
}
}