Victoria
Victoria

Reputation: 187

Angular reactive form: Displaying error text when form has error

I´m struggling with displaying error message under the textarea in my form. I have custom-textarea which is a normal texarea component with some handy attributes. One of them is helper text which is displayed below the textarea box. I find the logic of my conditional rendering okay, although it is not being displayed on the screen when the specific error occurs. Hardcoded value for my helper text works, so there is no problem with the text being displayed. Do you have any idea what could be the problem here?

<form [formGroup]="editForm" (ngSubmit)="editComment()">
    <custom-textarea
      formControlName="text"
      helper-text="{{!editForm.valid ? ((editForm.controls.text.errors?.['required'] ? 'Text for the comment is required!' : null) || (editForm.controls.text.errors?.['minlength'] ? 'Minimal length of text is 3 characters!' : null)) : null}}"
    ></custom-textarea>
</form>
export class EditCommentComponent implements OnInit {
@Input() comment: Comment;
editForm: FormGroup;
ngOnInit(): void {
    this.editForm = new FormGroup({
      text: new FormControl('', [Validators.required, Validators.minLength(3)]),
    });
}

ngOnChanges(): void {
    this.editForm.controls.text.setValue(this.comment.text);
  }

Upvotes: 0

Views: 1289

Answers (2)

archelite
archelite

Reputation: 174

Use property binding for helper-text. Change :

helper-text="{{!editForm.valid ? ((editForm.controls.text.errors?.['required'] ? 'Text for the comment is required!' : null) || (editForm.controls.text.errors?.['minlength'] ? 'Minimal length of text is 3 characters!' : null)) : null}}"

by :

[helper-text] = "!editForm.valid ? ((editForm.controls.text.errors?.['required'] ? 'Text for the comment is required!' : null) || (editForm.controls.text.errors?.['minlength'] ? 'Minimal length of text is 3 characters!' : null)) : null"

This way, helper-text property will no longer be static but dynamic (Check Angular Documentation on Property Binding)

Upvotes: 1

Jose Vicente
Jose Vicente

Reputation: 187

In your .html file add this:

<form [formGroup]="editForm" (ngSubmit)="editComment()">
    <custom-textarea
      formControlName="text"
      helper-text="{{!editForm.valid ? ((editForm.controls.text.errors?.['required'] ? 'Text for the comment is required!' : null) || (editForm.controls.text.errors?.['minlength'] ? 'Minimal length of text is 3 characters!' : null)) : null}}"
    ></custom-textarea>
<span class="error invalid-feedback"
                  *ngIf="editForm.errors? && editForm.controls.text">Error in form</span>
</form>

I assume that you are using bootstrap and you can use this class "error invalid-feedback"

Upvotes: 0

Related Questions