gpt4 book ai didi

validation - 如何在 Angular 2 中提交表单后重置验证

转载 作者:行者123 更新时间:2023-12-02 01:08:13 24 4
gpt4 key购买 nike

我已经通过一些简单的验证来测试表单。我的验证在提交表单时完美运行。

HTML

<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>

TS

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";
}
}

enter image description here提交表格后: enter image description here

My issue is after submitting the form, I want to reset validation. I don't want to reset form although. As I want to show message for successful insert.

最佳答案

您可以使用FormGroup reset如果你想清除表单控件的 toucheddirty 标志。在内部,这会将所有后代标记为 pristineuntouched

reset 方法还获取表单状态值的映射,因此您可以保留所有(或先前表单提交的部分值)。参见 this example

同样来自你的问题:

As I want to show message for successful insert

表单重置不会影响您显示它,因为 message 属性不是表单的一部分 - 它只是组件上的常规属性。

关于validation - 如何在 Angular 2 中提交表单后重置验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46526688/

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