Home > front end >  Angular reactive form: Displaying error text when form has error
Angular reactive form: Displaying error text when form has error

Time:02-10

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

CodePudding user response:

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)

CodePudding user response:

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 
                  *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"

  • Related