0

I try clear controls clear control forms and validation but in angular 9 does not work correct. Ofcourse I have cleared controls but I get validations on my controls. I check also other examples

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)])
      }); 

code

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

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

error

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)

update

            //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)])
            });

My code for demo

<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();
      }
  }
}
Rafał Developer
  • 2,135
  • 9
  • 40
  • 72

1 Answers1

1

According to the posted FormGroup definition, we can assume that you do not have a FormControl called controlName.

To make it work, you have to use a valid FormControl key, like this:

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

or:

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

PS: Replace 'name' with the name of the control you want to.

developer033
  • 24,267
  • 8
  • 82
  • 108
  • I added first example and yes now I have removed validation but I would like to have once again validation to add new object. I updated mu post - update – Rafał Developer Mar 29 '20 at 16:39
  • @RafałDeveloper Well, the question you asked is solved, right? Now you updated the post with a different question. Help me to understand what you're trying to achieve... what do you want to do in reality? Just reset the form, clearing errors and values, but keeping the validators? Is that it? – developer033 Mar 29 '20 at 16:44
  • Just reset the form, clearing errors and values, but keeping the validators -> yes only this. Ofcourse I accepted because you solved first problem :) – Rafał Developer Mar 29 '20 at 16:46
  • normal situation after create - clear form and don`t show validation because object was validated – Rafał Developer Mar 29 '20 at 16:50
  • @RafałDeveloper Take a look at this [**demo**](https://stackblitz.com/edit/angular-dh5mqm). – developer033 Mar 29 '20 at 16:55
  • in your example validation does not work. I added to my post "My code for demo" and you will understand my problem after click submit – Rafał Developer Mar 29 '20 at 17:52
  • ok. I found solution this same in Angular 8 https://stackoverflow.com/questions/34742023/how-to-clear-form-after-submit-in-angular-2 – Rafał Developer Mar 29 '20 at 19:11