首页 > 解决方案 > 从验证中重置 Angular 9 Reactive

问题描述

我尝试清除控件清除控件表单和验证,但在角度 9 中无法正常工作。当然,我已经清除了控件,但我的控件得到了验证。我还检查了其他示例

验证

this.carForm = new FormGroup({
         name: new FormControl('', [Validators.required, Validators.maxLength(200)]),
         mark: new FormControl('', [Validators.required]),
         type: new FormControl('', [Validators.required]),
         description: new FormControl('', [Validators.required, Validators.maxLength(300)]),
         pricePerDay: new FormControl('', [Validators.required]),
         year: new FormControl('', [Validators.required, Validators.pattern("^[0-9]*$"), Validators.maxLength(4)])
      }); 

代码

 this.carService.create(car).subscribe(
         (response) => {
            if (response != null)
               this.getCars();

            this.carForm.reset();   
            this.carForm.controls.controlName.clearValidators()           
         }
      );

错误

core.js:5882 ERROR TypeError: Cannot read property 'clearValidators' of undefined
    at SafeSubscriber._next (car-dictionary-list.component.ts:149)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)
    at Subscriber.next (Subscriber.js:49)
    at MapSubscriber._next (map.js:35)
    at MapSubscriber.next (Subscriber.js:49)
    at FilterSubscriber._next (filter.js:33)
    at FilterSubscriber.next (Subscriber.js:49)
    at MergeMapSubscriber.notifyNext (mergeMap.js:72)

更新

            //clear controls
            this.carForm.reset();  

            //clear validation
            this.carForm.controls.name.clearValidators();
            this.carForm.controls.name.updateValueAndValidity()         
            this.carForm.controls.mark.updateValueAndValidity()   

            //how to once again give validation?????
            this.carForm = new FormGroup({
               name: new FormControl('', [Validators.required, Validators.maxLength(200)]),
               mark: new FormControl('', [Validators.required]),
               type: new FormControl('', [Validators.required]),
               description: new FormControl('', [Validators.required, Validators.maxLength(300)]),
               pricePerDay: new FormControl('', [Validators.required]),
               year: new FormControl('', [Validators.required, Validators.pattern("^[0-9]*$"), Validators.maxLength(4)])
            });

我的演示代码

<form [formGroup]="carForm" autocomplete="off" novalidate >
  <div>
    <label for="name">Name</label>
    <input formControlName="name" id="name">
    <div style="color: red" *ngIf="hasError('name', 'required')">
      Required
    </div>
  </div>
</form>

<button (click)="submit()">Submit</button>

<hr>

<div>
  Form errors:<pre>{{ carForm.errors | json }}</pre>
  Form pristine? {{ carForm.pristine | json }}<br>
  Form touched? {{ carForm.touched | json }}<br>
  Form Value: <pre>{{ carForm.value | json }}</pre>
</div>

---------------

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';

@NgModule({
  imports:      [ BrowserModule, ReactiveFormsModule, CommonModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

----------------

import { Component, OnInit } from "@angular/core";
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  carForm: any;

   ngOnInit(){
      this.carForm = new FormGroup({
         name: new FormControl('', [Validators.required]),
      });
   }

   public hasError = (controlName: string, errorName: string) => {
      return this.carForm.controls[controlName].hasError(errorName);
   }

  constructor() {
  }

  submit(): void {
     if (this.carForm.valid) {
          this.carForm.reset();
      }
  }
}

标签: angularangular9

解决方案


根据发布的FormGroup定义,我们可以假设您没有FormControl被调用的controlName.

要使其工作,您必须使用有效的FormControl密钥,如下所示:

this.carForm.controls.name.clearValidators();

或者:

this.carmForm.get('name').clearValidators();

PS:将“名称”替换为您想要的控件名称。


推荐阅读