My goal is to reset the form fields and validators. It's currently clearing both after the first form submission. But then you are able to submit again without validation. Please see my stackblitz - Submit the form normally, then leave the form fields empty and click the 'Add' button again. You'll see that the form submits fine without errors. That shouldn't happen. I need the validation working properly EVERY time the 'Add' button is clicked. I've tried various combinations of the following to no avail:
- .markAsPristine()
- .markAsUntouched()
- .clearValidators()
- using a formGroup
- using a formGroupDirective
HTML
<table style="width: 300px;">
<thead>
<tr>
<th style="text-align: left;">Name</th>
<th style="text-align: left;">Value</th>
<th></th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of customData; let i=index;">
<td>{{ data.name }}</td>
<td>{{ data.value }}</td>
<td style="text-align: right;"><button (click)="remove(i)">X</button></td>
</tr>
</tbody>
</table>
<br><br>
<form (ngSubmit)="add()">
<mat-form-field class="full-width">
<mat-label>Name</mat-label>
<input matInput required [formControl]="customDataNameControl" />
<mat-error *ngIf="customDataNameControl.hasError('required')">Required.</mat-error>
</mat-form-field>
<br><br>
<mat-form-field class="full-width">
<mat-label>Value</mat-label>
<input matInput required [formControl]="customDataValueControl" />
<mat-error *ngIf="customDataValueControl.hasError('required')">Required.</mat-error>
</mat-form-field>
<br><br>
<button type="submit">Add</button>
</form>
TS
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-item-list',
templateUrl: './item-list.component.html'
})
export class ItemListComponent implements OnInit {
customData = [
{ name: 'sample name 1', value: 'sample value 1' },
{ name: 'sample name 2', value: 'sample value 2' },
{ name: 'sample name 3', value: 'sample value 3' }
];
customDataNameControl = new FormControl('', [Validators.required]);
customDataValueControl = new FormControl('', [Validators.required]);
constructor() {}
ngOnInit(): void {}
// Remove
remove(index: any) {
let confirmation = window.confirm('Delete? This cannot be undone!');
if (confirmation == true) {
this.customData.splice(index, 1);
}
}
// Add
add() {
if (this.customDataNameControl.valid && this.customDataValueControl.valid) {
let newCD: any = {
name: this.customDataNameControl.value,
value: this.customDataValueControl.value
};
this.customData.push(newCD);
this.customDataNameControl.reset();
this.customDataValueControl.reset();
this.customDataNameControl.setErrors(null);
this.customDataValueControl.setErrors(null);
}
}
}