Я пытаюсь очистить элементы управления Очистить формы контроля и проверки , но в angular 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)])
});
Мой код для демонстрации
<code><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 }}
Форма нетронутая? {{carForm.pristine | json}}
Форма коснулась? {{carForm.touched | json}}
Значение формы:
{{ carForm.value | json }}
--------------- import {NgModule} из '@ angular / core'; импортировать {CommonModule} из '@ angular / common'; импортировать {BrowserModule} из '@ angular / platform-browser'; импортировать {ReactiveFormsModule} из '@ angular / forms'; import {AppComponent} из './app.component'; @NgModule ({import: [BrowserModule, ReactiveFormsModule, CommonModule], объявления: [AppComponent], bootstrap: [AppComponent]}) класс экспорта AppModule {} ---------------- import {Component, OnInit} из "@ angular / core"; import {FormGroup, FormControl, Validators} из '@ angular / forms'; @Component ({selector: "my-app", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"]}) класс экспорта AppComponent реализует OnInit {carForm : Любые; ngOnInit () {this.carForm = new FormGroup ({name: new FormControl ('', [Validators.required]),}); } publi c hasError = (controlName: string, errorName: string) => {вернуть this.carForm.controls [controlName] .hasError (errorName); } constructor () {} submit (): void {if (this.carForm.valid) {this.carForm.reset (); }}}