setting its value to form control. this.FrmGroup.get("name").setValue(this.quill.root.innerHTML)`
setting its value to form control. this.FrmGroup.get("name").setValue(this.quill.root.innerHTML)`
setting its value to form control. this.FrmGroup.get("name").setValue(this.quill.root.innerHTML)`

Angular - Form control invalid error not showing if set the value to form control

363 Views Asked by At

I have this editor

<div id="editor"></div>

setting its value to form control.

this.FrmGroup.get("name").setValue(this.quill.root.innerHTML)`
<div *ngIf="FrmGroup.get('name').invalid && (FrmGroup.get('name').dirty || FrmGroup.get('name').touched)">
  <small class="validation-error">Please provide a name.</small>
</div>

The value is empty but the error is not shown.

Form group Structure:

this.FrmGroup = this.fb.group({
  name: ['', Validators.required],
  Description: ['', Validators.required],
});
2

There are 2 best solutions below

0
Yong Shun On

The problem is in here:

*ngIf="FrmGroup.get('name').invalid && (FrmGroup.get('name').dirty || FrmGroup.get('name').touched)"

which the HTML element is rendered only by fulfilling:

  1. The form control is invalid
  2. At the same time the form control is either dirty or touched.

Either:

You should mask the form control dirty or touched after setting the value.

this.FrmGroup.get('name')!.setValue(this.quill?.root.innerHTML);
this.FrmGroup.get('name')!.markAsDirty();
// Or
this.FrmGroup.get('name')!.markAsTouched();

Demo @ StackBlitz

Or remove the logic for checking the form control is dirty or touched if it is not required.

*ngIf="FrmGroup.get('name').invalid"
0
tenebrone On

Alternatively, you can use control status css classes, like in documentation https://angular.io/guide/form-validation#control-status-css-classes