【问题标题】:Angular 5 Form reset displays error back - ReactiveFormsModule [duplicate]Angular 5 Form重置显示错误 - ReactiveFormsModule [重复]
【发布时间】:2018-08-19 13:08:43
【问题描述】:

我有以下代码,我只是提交一些细节并在成功提交后重置表单。

ngOnInit() {
    this.initContactForm();    
}

initContactForm(){
    this.contactForm = this.formBuilder.group({
            fullname: ['', Validators.compose([Validators.required, Validators.minLength(2), Validators.maxLength(30)])],
            email: ['', Validators.compose([Validators.required])],
            phone: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(12)])],
            subject: ['', Validators.compose([Validators.required, Validators.maxLength(25), Validators.minLength(5)])],
            message: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(200)])]
        });
}

onSubmit(model){
    if (this.contactForm.valid){
        this.contactModel = model;
        this.dataService.sendContactMessage(this.contactModel).then((resp) => {
            if (resp){
                this.openSnackBar('Message has been sent', 'Done');    
                this.contactForm.reset();
                this.contactForm.updateValueAndValidity();
                this.contactForm.setErrors(null);
            }else{
                console.log('Error');
            }

        });
    }else{
        alert('Invalid form');
    }
}

查看

<form autocomplete="off" [formGroup]="contactForm" novalidate (ngSubmit)="onSubmit(contactForm.value)">
    <div class="row">
        <div class="col m4 s12">
            <mat-form-field>
                <input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" maxlength="30" matInput type="text" placeholder="Full Name" value="" name="fullname" formControlName="fullname" required>
                <mat-error *ngIf="contactForm.controls['fullname'].hasError('required')">
                    <strong>Please enter your Fullname</strong>
                </mat-error>
            </mat-form-field>
         </div>
         <div class="col m4 s12">
            <mat-form-field>
                <input matInput type="email" placeholder="Email Address" value="" name="email" formControlName="email" required email>
                <mat-error *ngIf="contactForm.controls['email'].hasError('required')">
                     <strong>Please enter your Email Id</strong>
                </mat-error>
            </mat-form-field>
         </div>
         <div class="col m4 s12">
            <mat-form-field>
                <input matInput type="tel" placeholder="Contact Number" value="" name="contact" formControlName="phone" required tel>
                <mat-error *ngIf="contactForm.controls['phone'].hasError('required')">
                    <strong>Please enter your Contact number</strong>
                 </mat-error>
            </mat-form-field>
        </div>
    </div>
    <div class="clearfix"></div>
    <div class="row">
        <div class="col m12 s12">
            <mat-form-field>
                <input matInput type="text" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" maxlength="25" placeholder="Subject" value="" name="subject" formControlName="subject" required>
                <mat-error *ngIf="contactForm.controls['subject'].hasError('required')">
                    <strong>Please enter Subject</strong>
                </mat-error>
             </mat-form-field>
        </div>
        <div class="col s6 s12">
            <mat-form-field>
                <textarea matInput type="text" style="resize:none;" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" maxlength="200" placeholder="Message" value="" name="message" formControlName="message"
                rows="5" required></textarea>
                <mat-error *ngIf="contactForm.controls['message'].hasError('required')">
                    <strong>Please enter your Message</strong>
                </mat-error>
            </mat-form-field>
        </div>
     </div>
     <div class="row margin-top20">
        <div class="col l6 push-l6 s12 right-align">
            <button type="submit" mat-button class="btn btn-primary">Send</button>
        </div>
        </div>
</form>

每当我调用contactForm.reset() 时,值都会被清除,但所有错误都会再次出现。

我已经尝试了各种其他方法来清除它,如下所示:

  • 尝试在form reset之后调用initContactForm()

  • 尝试循环遍历每个表单控件并使用markAsUntouched()markAs Pristine() 等,

在这里

Object.keys(this.contactForm.controls).forEach(key => {
    this.contactForm.controls[key].setErrors(null);
    this.contactForm.controls[key].updateValueAndValidity();
});

我还有什么可以尝试的吗?在reset..之后我仍然无法清除错误。希望得到一些帮助。

【问题讨论】:

  • 我猜你需要将 markAsTouched` 设置为 false 以实现整个表单
  • @MKhalidJunaid 没有运气兄弟.. :(
  • 查看 Harry Ninh 的回答 stackoverflow.com/a/48217303/9499885
  • @borutc .. 太棒了。极好的。太棒了..你刚刚移除了我的开销。非常感谢兄弟.. :)

标签: angular angular2-forms angular-reactive-forms


【解决方案1】:

一旦您重置表单,值就会被清除。

Validators.required 然后将被处理,您的字段将变为无效,因为它是空的。 如果您只想在用户与表单控件交互时显示错误,请将其添加到您的条件中:

mat-error *ngIf="contactForm.controls['phone'].hasError('required') && contactForm.controls['phone'].dirty"

【讨论】:

  • Nope bro..即使没有显示错误消息,控件仍然无效.. :(
  • 这很正常,因为您的Validators.required 将返回错误。你会看到一开始,在任何交互之前,你的表单就已经无效了。
  • 但即使我设置了form.setErrors(null)form.updateValueAndValidity(),表单仍然有错误。怎么会.. :(
  • 再一次:这很正常。您不能绕过表单的验证工作流程。当您使用form.updateValueAndValidity() 时,将处理验证并设置错误。 form.setErrors(null) 仅在您手动管理整个表单的验证时才有效。
  • 在清除错误后尝试不调用 updateValueAndValidity() 函数
【解决方案2】:

重置表单后尝试添加此内容

    this.contactForm.markAsPristine();
    this.contactForm.markAsUntouched();
    this.contactForm.updateValueAndValidity();

【讨论】:

  • 不起作用,伙计!
猜你喜欢
  • 2018-01-11
  • 2018-12-16
  • 2014-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 2018-09-22
相关资源
最近更新 更多